问:
Best way to change UIViewController view NIB programmatically
I have this iPad application with different NIBs and views.
Each view has two NIBs, one for potrait orientation and one for landscape, so i'm searching for a method to programmatically switch NIB for a given UIViewController .

Right now i have this function that i'm using in the willRotateToInterfaceOrientation method of each controller :

```<code>void UIHandleRotation( UIViewController *controller, NSString *nibName, UIInterfaceOrientation orientation, BOOL transform ){
    double angle = 0.0;

    if( orientation == UIInterfaceOrientationPortrait ) {
        angle = PI * 2 /* 360° */;
    }
    else if( orientation == UIInterfaceOrientationLandscapeLeft ){
        angle   = PI + PI/2 /* 270 ° */;
        // Each landscape nib is [nib-name]L
        nibName = [NSString stringWithFormat:@"%@L", nibName];
    }

    [[NSBundle mainBundle] loadNibNamed:nibName owner:controller options:nil];
    if( transform ) {
        controller.view.transform = CGAffineTransformMakeRotation( angle );
    }
}
</code>```

But it's giving me strange behaviour (ui controls position messed, the outlets are not associated as in interface builder, and so forth).

Am i doing something wrong or there's just a better way to implement this ?
Thanks

NOTE: I'm not using a navigation controller, so i can't use this solution Easiest way to support multiple orientations? How do I load a custom NIB when the application is in Landscape?

答:
You shouldn't switch nibs, you should switch controllers.

See this answer for: Easiest Way to Support Multiple Orientations

Body:
I have this iPad application with different NIBs and views.
Each view has two NIBs, one for potrait orientation and one for landscape, so i'm searching for a method to programmatically switch NIB for a given UIViewController .

Right now i have this function that i'm using in the willRotateToInterfaceOrientation method of each controller :

void UIHandleRotation( UIViewController *controller, NSString *nibName, UIInterfaceOrientation orientation, BOOL transform ){
    double angle = 0.0;

    if( orientation == UIInterfaceOrientationPortrait ) {
        angle = PI * 2 /* 360° */;
    }
    else if( orientation == UIInterfaceOrientationLandscapeLeft ){
        angle   = PI + PI/2 /* 270 ° */;
        // Each landscape nib is [nib-name]L
        nibName = [NSString stringWithFormat:@"%@L", nibName];
    }

    [[NSBundle mainBundle] loadNibNamed:nibName owner:controller options:nil];
    if( transform ) {
        controller.view.transform = CGAffineTransformMakeRotation( angle );
    }
}

But it's giving me strange behaviour (ui controls position messed, the outlets are not associated as in interface builder, and so forth).

Am i doing something wrong or there's just a better way to implement this ?
Thanks

NOTE: I'm not using a navigation controller, so i can't use this solution Easiest way to support multiple orientations? How do I load a custom NIB when the application is in Landscape?


来源: stackexchange

问:
SQL Order by from another table
I'm trying to display my posts by upvote on my page.

My table posts:

```<code>(id, post_name, post_description, post_category, post_subcategory)
</code>```

and table votes:

```<code>(id, post_id, vote_rank)
</code>```

I can display all my post with

```<code>$bdd->query('SELECT * FROM posts WHERE post_subcategory = "'.$_GET['s'].'" ORDER BY post_name');
</code>```

I tried with JOIN but nothing appears.

```<code>$bdd->query('SELECT *
            FROM posts AS p
               JOIN votes as v ON v.post_id = p.id
            WHERE p.post_subcategory =  "'.$_GET['s'].'"
            ORDER BY v.vote_rank');
</code>```

Any idea?

答:
Try using the inner join</p>

```<code>$bdd->query('SELECT p.*
        FROM posts p inner join votes v on v.post_id = p.id
        where p.post_subcategory =  "'.$_GET['c'].'"
        order by v.vote_rank');
</code>```

ContentLicense: CC BY-SA 3.0

Title: SQL Order by from another table

Body:
I'm trying to display my posts by upvote on my page.

My table posts:

(id, post_name, post_description, post_category, post_subcategory)

and table votes:

(id, post_id, vote_rank)

I can display all my post with

$bdd->query('SELECT * FROM posts WHERE post_subcategory = "'.$_GET['s'].'" ORDER BY post_name');

I tried with JOIN but nothing appears.

$bdd->query('SELECT *
            FROM posts AS p
               JOIN votes as v ON v.post_id = p.id
            WHERE p.post_subcategory =  "'.$_GET['s'].'"
            ORDER BY v.vote_rank');

Any idea?

Body:
Try using the inner join

$bdd->query('SELECT p.*
        FROM posts p inner join votes v on v.post_id = p.id
        where p.post_subcategory =  "'.$_GET['c'].'"
        order by v.vote_rank');


问:
Initialise Array with Constructor - Java
I have 2 classes: Product and Room.
I want the user to be able to say how big the array to be, with creating an Object Room and enter an int.

```<code>public class Room{
  private int n;
  private int count = 0;
  Product [] space = new Product[n];

public Room(int n){
  this.n = n;
}
</code>```

Why doesnt the constructor create the array with the input n, I give him?
Any ideas what I'm doing wrong?

答:
You need to initialize the array inside the constructor.

```<code>public Room(int n) {
    this.n = n;
    this.space = new Product[n];
}
</code>```

Otherwise, when you're doing it outside, n has a default value of 0 and the array created is also of size 0. Basically useless.

Body:
I have 2 classes: Product and Room.
I want the user to be able to say how big the array to be, with creating an Object Room and enter an int.

public class Room{
  private int n;
  private int count = 0;
  Product [] space = new Product[n];

public Room(int n){
  this.n = n;
}

Why doesnt the constructor create the array with the input n, I give him?
Any ideas what I'm doing wrong?

Body:
You need to initialize the array inside the constructor.

public Room(int n) {
    this.n = n;
    this.space = new Product[n];
}

Otherwise, when you're doing it outside, n has a default value of 0 and the array created is also of size 0. Basically useless.


问:
Page_Load not called on POST request
I made a nice web page with jquery ajax calls, but noticed that Page_Load is not called for a jquery ajax POST request. I need the Page_Load call for access to the name of the logged in user, to store in the database with data received through POST, as the static WebMethod in code-behind has no access to the Page object.

My question: is it normal that Page_Load is not called on a POST request? If so, how to get the Page object for the user name, without using Page_Load?

In comment on this question I read: Support for WebMethod is no longer maintained. You should consider switching over to Web API, as it's well supported (and simpler!)

But googling did not really result in info about Web API, as this is a very general search term. Any info on this?

Update:

My problem is solved by using HttpContext in the static WebMethod, as commented below, so I do not need Page_Load.

答:
There are two ways to do that

In your javascript add a variable which set current username and pass this as a parameter to POST method.

var usrName = "@HttpContext.Current.User.Identity.Name";

HttpContext is also available in the static WebMethod in code-behind so you can directly achieve the same thing using this as well

Title: Page_Load not called on POST request


问:
Use Find in VBA word and paste graph in next paragaraph
I am using the find option in word VBA and want to paste a graph in the next paragraph wherever i find my text.

```<code>Set myRange = ActiveDocument.Content
With myRange.Find
      .Text = "Chart"
      .Forward = True
      .Wrap = wdFindStop
      .MatchWildcards = False
       bFound = .Execute
End With
If bFound Then
       Set ChartObj = wb1.ChartObjects("Chart 1")
       ChartObj.Chart.ChartArea.Copy
       .Words.Last.Paste
End If
</code>```

The .words.Last.Paste pastes the graph at the end of the document instead of pasting it at the end of word "Chart" which I am seraching. How do I instert a paragraph at the end of line where i find my text and paste the chart there ?

I also tried the bookmark approach, such that my graphs gets pasted at the next paragraph after text 'My Chart here', but don't know how to move the cursor to the end of my text and then add paragraph there.

```<code> .Bookmarks('chart').Range.Text = 'My Chart here'
</code>```

The text 'My chart here' has more than 1 character but when i use the code below i only get 1 as answer. What I am missing here ?

```<code>  Msgbox .Bookmarks('chart').Range.Characters.Count
</code>```

答:
.Words is a property of the Range object, so you need to use myRange.Words.Last.Paste

```<code>Sub test()
    Set myRange = ActiveDocument.Content
    With myRange.Find
        .Text = "Insert"
        .Forward = True
        .Wrap = wdFindStop
        .MatchWildcards = False
        bFound = .Execute
    End With
    If bFound Then
        Set ChartObj = wb1.ChartObjects("Chart 1")
        ChartObj.Chart.ChartArea.Copy
        myRange.Words.Last.Paste
    End If
End Sub|
</code>```

Body:
I am using the find option in word VBA and want to paste a graph in the next paragraph wherever i find my text.

Set myRange = ActiveDocument.Content
With myRange.Find
      .Text = "Chart"
      .Forward = True
      .Wrap = wdFindStop
      .MatchWildcards = False
       bFound = .Execute
End With
If bFound Then
       Set ChartObj = wb1.ChartObjects("Chart 1")
       ChartObj.Chart.ChartArea.Copy
       .Words.Last.Paste
End If

The .words.Last.Paste pastes the graph at the end of the document instead of pasting it at the end of word "Chart" which I am seraching. How do I instert a paragraph at the end of line where i find my text and paste the chart there ?

I also tried the bookmark approach, such that my graphs gets pasted at the next paragraph after text 'My Chart here', but don't know how to move the cursor to the end of my text and then add paragraph there.

 .Bookmarks('chart').Range.Text = 'My Chart here'

The text 'My chart here' has more than 1 character but when i use the code below i only get 1 as answer. What I am missing here ?

  Msgbox .Bookmarks('chart').Range.Characters.Count

Body:
.Words is a property of the Range object, so you need to use myRange.Words.Last.Paste

Sub test()
    Set myRange = ActiveDocument.Content
    With myRange.Find
        .Text = "Insert"
        .Forward = True
        .Wrap = wdFindStop
        .MatchWildcards = False
        bFound = .Execute
    End With
    If bFound Then
        Set ChartObj = wb1.ChartObjects("Chart 1")
        ChartObj.Chart.ChartArea.Copy
        myRange.Words.Last.Paste
    End If
End Sub|


问:
$timeout in a directive link function
So I'm using this directive to collapse a variable height card in Ionic. The directive grabs the auto height and changes it to a defined height so it can then be collapsed to 0 with a css animation. It was working fine for my needs, but now I need to use ng-src to dynamically load an image within the card. What's happening is the image is being loaded after the directive, so the image loads and overflows the card.

Directive:

```<code>.directive('collapse', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',

        link: function ($scope, ngElement, attributes) {
            var element = ngElement[0];

            $timeout(function(){
                $scope.$watch(attributes.collapse, function (collapse) {
                            var newHeight = collapse ? 0 : getElementAutoHeight();

                            element.style.height = newHeight +"px";
                            ngElement.toggleClass('collapsed', collapse);
                        });

            function getElementAutoHeight() {
                var currentHeight = getElementCurrentHeight();

                element.style.height = 'auto';
                var autoHeight = getElementCurrentHeight();

                element.style.height = currentHeight +"px";
                getElementCurrentHeight(); // Force the browser to recalc height after moving it back to normal

                return autoHeight;
            }

            function getElementCurrentHeight() {
                return element.offsetHeight
            }
         });
      }
    };
}])
</code>```

and HTML:

```<code><div ng-repeat="item in items | orderBy : '-'" collapse="item.deleted">
    <div class="list card">
        <img class="full-image" ng-src="{{item.image}}"/>
    </div>
</div>
</code>```

As you can see I've injected $timeout and leaving the interval blank in hopes it will wait until the DOM is loaded, but it seems no matter how I use it, the directive still explicitly sets the height of the element in css before the image child element is rendered. How can I delay the setting of element height until after ng-src is loaded in each ng-repeat item?

答:
First thing, angular $timeout without an $interval will not wait for the DOM tree to load, basically, what it does is waiting for the current digest cycle to finish before executing the function in the first parameter. By doing so, it will allow the your code to wait till the directive finish compile and render before calculating the height of the div.

However, there is no guarantee that the image will be loaded by that time. Images are loaded by the browser independently from DOM rendering, therefore, to calculate the height of the container having images precisely, you should make use of JS Image Object and the load event. Once the images are fully loaded, then you can update the height.

Also, for your directive, I don't think you need to calculate the height every times the collapse variable changed (inside the watch), you can simply wait till the image being loaded, calculate the height once, store it inside the scope object, and reuse it whenever the collapse variable change.

Title: $timeout in a directive link function

Body:
So I'm using this directive to collapse a variable height card in Ionic. The directive grabs the auto height and changes it to a defined height so it can then be collapsed to 0 with a css animation. It was working fine for my needs, but now I need to use ng-src to dynamically load an image within the card. What's happening is the image is being loaded after the directive, so the image loads and overflows the card.

Directive:

.directive('collapse', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',

        link: function ($scope, ngElement, attributes) {
            var element = ngElement[0];

            $timeout(function(){
                $scope.$watch(attributes.collapse, function (collapse) {
                            var newHeight = collapse ? 0 : getElementAutoHeight();

                            element.style.height = newHeight +"px";
                            ngElement.toggleClass('collapsed', collapse);
                        });

            function getElementAutoHeight() {
                var currentHeight = getElementCurrentHeight();

                element.style.height = 'auto';
                var autoHeight = getElementCurrentHeight();

                element.style.height = currentHeight +"px";
                getElementCurrentHeight(); // Force the browser to recalc height after moving it back to normal

                return autoHeight;
            }

            function getElementCurrentHeight() {
                return element.offsetHeight
            }
         });
      }
    };
}])

and HTML:

As you can see I've injected $timeout and leaving the interval blank in hopes it will wait until the DOM is loaded, but it seems no matter how I use it, the directive still explicitly sets the height of the element in css before the image child element is rendered. How can I delay the setting of element height until after ng-src is loaded in each ng-repeat item?


问:
720KB toolip not displaying on ion tab
in my project, i currently have a tabs controller template that allows the user to navigate to other views

I am currently using the 720KB tooltip in my ionic project. I have gotten it to work for all my elements except for the ion tabs in the tabs controller template.

With 720KB all you need to do is add this tooltips tooltip-template="I'm a tooltip!" to any element you will have the tooltip on hover for that specific element.

this is my code in the ionic tab controller

```<code><ion-view id="page1" ng-app="720kb">
</code>```

```<code><ion-tab title="Introduction" icon-off="acc-intro-off" icon-on="acc-intro-on" href="#/page1/page3" id="tabsController-tab3">
  <ion-nav-view name="tab2"></ion-nav-view>
</ion-tab>

<ion-tab title="Awards " icon-off="acc-category-off" icon-on="acc-category-on" href="#/page1/page4" id="tabsController-tab4">
  <ion-nav-view name="tab3"></ion-nav-view>
</ion-tab>

<ion-tab title="Awards Vote" icon-off="acc-vote-off" icon-on="acc-vote-on" href="#/page1/page6" id="tabsController-tab5">
  <ion-nav-view name="tab6"></ion-nav-view>
</ion-tab>

<ion-tab title="Award Nomination" icon-off="acc-nomination-off" icon-on="acc-nomination-on" href="#/page1/page5" id="tabsController-tab6">
  <ion-nav-view name="tab5"></ion-nav-view>
</ion-tab>

<ion-tab title="Result Category" icon-off="acc-results-off" icon-on="acc-results-on" href="#/page1/page7" id="tabsController-tab7">
  <ion-nav-view name="tab7"></ion-nav-view>
</ion-tab>
</code>```

I have a attempted to put a 720KB tool tip on the first ion tab but it does not appear on hover. If I inspect in chrome however, I see that the tool tip is generated.

Here is an example it working with any other element

However when I attach tooltips tooltip-template="I'm a tooltip!" to an ion-tab, it does not display however I see the html generated in the inspect as shown here

答: Try to Trigger the tooltip on focus event.</p>

Title: 720KB toolip not displaying on ion tab

Body:
in my project, i currently have a tabs controller template that allows the user to navigate to other views

I am currently using the 720KB tooltip in my ionic project. I have gotten it to work for all my elements except for the ion tabs in the tabs controller template.

With 720KB all you need to do is add this tooltips tooltip-template="I'm a tooltip!" to any element you will have the tooltip on hover for that specific element.

this is my code in the ionic tab controller

<ion-view id="page1" ng-app="720kb">

<ion-tab title="Introduction" icon-off="acc-intro-off" icon-on="acc-intro-on" href="#/page1/page3" id="tabsController-tab3">
  <ion-nav-view name="tab2"></ion-nav-view>
</ion-tab>

<ion-tab title="Awards " icon-off="acc-category-off" icon-on="acc-category-on" href="#/page1/page4" id="tabsController-tab4">
  <ion-nav-view name="tab3"></ion-nav-view>
</ion-tab>

<ion-tab title="Awards Vote" icon-off="acc-vote-off" icon-on="acc-vote-on" href="#/page1/page6" id="tabsController-tab5">
  <ion-nav-view name="tab6"></ion-nav-view>
</ion-tab>

<ion-tab title="Award Nomination" icon-off="acc-nomination-off" icon-on="acc-nomination-on" href="#/page1/page5" id="tabsController-tab6">
  <ion-nav-view name="tab5"></ion-nav-view>
</ion-tab>

<ion-tab title="Result Category" icon-off="acc-results-off" icon-on="acc-results-on" href="#/page1/page7" id="tabsController-tab7">
  <ion-nav-view name="tab7"></ion-nav-view>
</ion-tab>

I have a attempted to put a 720KB tool tip on the first ion tab but it does not appear on hover. If I inspect in chrome however, I see that the tool tip is generated.

Here is an example it working with any other element

However when I attach tooltips tooltip-template="I'm a tooltip!" to an ion-tab, it does not display however I see the html generated in the inspect as shown here


问:
Error: INT is incompatible with DATE while passing date argument
I am getting below error while passing date as parameter to stored procedure

Operand type clash: INT is incompatible with DATE

Tried with 2017-04-03 and '2017-04-03'.Still not working

Example:
exec > 20160403

Procedure defined as :

@stlddate date
...
...

Please help to resolve it.

答:
Get store procedure parameter as INT and then convert into date datatype :</p>

```<code> DECLARE @date INT;
 SET @date = 20170403
 SELECT CONVERT(varchar(20), CONVERT(date, CONVERT(varchar(8), @date),
 112),110)as datetime
</code>```

Body:
Get store procedure parameter as INT and then convert into date datatype :

 DECLARE @date INT;
 SET @date = 20170403
 SELECT CONVERT(varchar(20), CONVERT(date, CONVERT(varchar(8), @date),
 112),110)as datetime


问:
Python super() arguments: why not super(obj)?
I am trying to understand when and how to use super() in Python correctly (either 2.7.x or 3.x)

on >>> help(super) the interpreter tells me how to call it:

```<code>class super(object)
 |  super(type) -> unbound super object
 |  super(type, obj) -> bound super object; requires isinstance(obj, type)
 |  super(type, type2) -> bound super object; requires issubclass(type2, type)
</code>```

I understand that in Python3.x it's now possible to juse use super() within a class definition, but I don't understand why super(obj) is not possible. Or super(self) within a class definition.

I know there must be a reason for it, but I can't find it. To me those lines are equivalent to super(obj.__class__, obj) or super(self.__class__, self) and those would work right?

I would think that just typing super(obj) would be a nice shortcut even in Python 3.x.

答:
Trying a short answer:

self.__class__ is always the actual ("sub-most") class of your object instance – not necessarily the wanted class, which implements the function!

Replace  super(self.__class__, self) with super(__class__, self) and you are right within a method definition in Python 3, because Python 3 provides the magic cell variable __class__ for the implementing class.

And simply super() with zero arguments is already the shortcut for super(__class__, self)  in Python 3. See PEP3135.

Python 2 neither knows __class__ nor the zero-argument shortcut super().

Body:
I am trying to understand when and how to use super() in Python correctly (either 2.7.x or 3.x)

on >>> help(super) the interpreter tells me how to call it:

class super(object)
 |  super(type) -> unbound super object
 |  super(type, obj) -> bound super object; requires isinstance(obj, type)
 |  super(type, type2) -> bound super object; requires issubclass(type2, type)

I understand that in Python3.x it's now possible to juse use super() within a class definition, but I don't understand why super(obj) is not possible. Or super(self) within a class definition.

I know there must be a reason for it, but I can't find it. To me those lines are equivalent to super(obj.__class__, obj) or super(self.__class__, self) and those would work right?

I would think that just typing super(obj) would be a nice shortcut even in Python 3.x.


问:
Apache Spark Object not Serializable Exception for json parser
I am reading the data[json as String] from kafka queue and tring to parse json as String into case class using liftweb json api.

here is the code Snippet

```<code>val sparkStreamingContext = new StreamingContext(sparkConf, Seconds(5))

    val kafkaParam: Map[String, String] = Map(
      "bootstrap.servers" -> kafkaServer,
      "key.deserializer" -> classOf[StringDeserializer].getCanonicalName,
      "value.deserializer" -> classOf[StringDeserializer].getCanonicalName,
      "zookeeper.connect" -> zookeeperUrl,
      "group.id" -> "demo-group")

    import org.apache.spark.streaming.kafka._
    import net.liftweb.json.{DefaultFormats, Formats}
    import net.liftweb.json._
    val topicSet = Map(kafkaTopic -> 1)
    val streaming = KafkaUtils.createStream[String, String, StringDecoder, StringDecoder](sparkStreamingContext, kafkaParam, topicSet, StorageLevel.MEMORY_AND_DISK)

    streaming.map { case (id, tweet) => implicit val formats: Formats = DefaultFormats
      (id, parse(tweet).extract[Tweet])
    }.print()

    sparkStreamingContext.start()
    sparkStreamingContext.awaitTermination()
</code>```

and i am getting this exception

```<code>Exception in thread "main" org.apache.spark.SparkException: Job aborted due to stage failure: Task 0.0 in stage 1.0 (TID 1) had a not serializable result: net.liftweb.json.DefaultFormats$
Serialization stack:
    - object not serializable (class: net.liftweb.json.DefaultFormats$, value: net.liftweb.json.DefaultFormats$@74a2fec)
    - field (class: Tweet, name: formats, type: interface net.liftweb.json.Formats)
    - object (class Tweet, Tweet(Akash24,Adele))
    - field (class: scala.Tuple2, name: _2, type: class java.lang.Object)
    - object (class scala.Tuple2, (1,Tweet(Akash24,Adele)))
    - element of array (index: 0)
    - array (class [Lscala.Tuple2;, size 11)
</code>```

Can anyone help me fix this problem
Any Help will be appreciate
Thanks

答:
From the logs it looks like a simple exception of Class not Serializable. to correct is use following code:

```<code>sparkConf.registerKryoClasses(Array(classOf[DefaultFormats]))

val sparkStreamingContext = new StreamingContext(sparkConf, Seconds(5))

val kafkaParam: Map[String, String] = Map(
  "bootstrap.servers" -> kafkaServer,
  "key.deserializer" -> classOf[StringDeserializer].getCanonicalName,
  "value.deserializer" -> classOf[StringDeserializer].getCanonicalName,
  "zookeeper.connect" -> zookeeperUrl,
  "group.id" -> "demo-group")

import org.apache.spark.streaming.kafka._
import net.liftweb.json.{DefaultFormats, Formats}
import net.liftweb.json._
val topicSet = Map(kafkaTopic -> 1)
val streaming = KafkaUtils.createStream[String, String, StringDecoder, StringDecoder](sparkStreamingContext, kafkaParam, topicSet, StorageLevel.MEMORY_AND_DISK)

streaming.map { case (id, tweet) => implicit val formats: Formats = DefaultFormats
  (id, parse(tweet).extract[Tweet])
}.print()

sparkStreamingContext.start()
sparkStreamingContext.awaitTermination()
</code>```

It will make the DefaultFormats class serializable and Spark master will able to send implicit val formats to all worker nodes.

Body:
I am reading the data[json as String] from kafka queue and tring to parse json as String into case class using liftweb json api.

here is the code Snippet

val sparkStreamingContext = new StreamingContext(sparkConf, Seconds(5))

    val kafkaParam: Map[String, String] = Map(
      "bootstrap.servers" -> kafkaServer,
      "key.deserializer" -> classOf[StringDeserializer].getCanonicalName,
      "value.deserializer" -> classOf[StringDeserializer].getCanonicalName,
      "zookeeper.connect" -> zookeeperUrl,
      "group.id" -> "demo-group")

    import org.apache.spark.streaming.kafka._
    import net.liftweb.json.{DefaultFormats, Formats}
    import net.liftweb.json._
    val topicSet = Map(kafkaTopic -> 1)
    val streaming = KafkaUtils.createStream[String, String, StringDecoder, StringDecoder](sparkStreamingContext, kafkaParam, topicSet, StorageLevel.MEMORY_AND_DISK)

    streaming.map { case (id, tweet) => implicit val formats: Formats = DefaultFormats
      (id, parse(tweet).extract[Tweet])
    }.print()

    sparkStreamingContext.start()
    sparkStreamingContext.awaitTermination()

and i am getting this exception

Exception in thread "main" org.apache.spark.SparkException: Job aborted due to stage failure: Task 0.0 in stage 1.0 (TID 1) had a not serializable result: net.liftweb.json.DefaultFormats$
Serialization stack:
    - object not serializable (class: net.liftweb.json.DefaultFormats$, value: net.liftweb.json.DefaultFormats$@74a2fec)
    - field (class: Tweet, name: formats, type: interface net.liftweb.json.Formats)
    - object (class Tweet, Tweet(Akash24,Adele))
    - field (class: scala.Tuple2, name: _2, type: class java.lang.Object)
    - object (class scala.Tuple2, (1,Tweet(Akash24,Adele)))
    - element of array (index: 0)
    - array (class [Lscala.Tuple2;, size 11)

Can anyone help me fix this problem
Any Help will be appreciate
Thanks

Body:
From the logs it looks like a simple exception of Class not Serializable. to correct is use following code:

sparkConf.registerKryoClasses(Array(classOf[DefaultFormats]))

val sparkStreamingContext = new StreamingContext(sparkConf, Seconds(5))

val kafkaParam: Map[String, String] = Map(
  "bootstrap.servers" -> kafkaServer,
  "key.deserializer" -> classOf[StringDeserializer].getCanonicalName,
  "value.deserializer" -> classOf[StringDeserializer].getCanonicalName,
  "zookeeper.connect" -> zookeeperUrl,
  "group.id" -> "demo-group")

import org.apache.spark.streaming.kafka._
import net.liftweb.json.{DefaultFormats, Formats}
import net.liftweb.json._
val topicSet = Map(kafkaTopic -> 1)
val streaming = KafkaUtils.createStream[String, String, StringDecoder, StringDecoder](sparkStreamingContext, kafkaParam, topicSet, StorageLevel.MEMORY_AND_DISK)

streaming.map { case (id, tweet) => implicit val formats: Formats = DefaultFormats
  (id, parse(tweet).extract[Tweet])
}.print()

sparkStreamingContext.start()
sparkStreamingContext.awaitTermination()

It will make the DefaultFormats class serializable and Spark master will able to send implicit val formats to all worker nodes.


问:
Bugs in Excel's ActiveX combo boxes?
I have noticed that I get all sorts of annoying errors when:

I have ActiveX comboboxes on a worksheet (not an excel form)

The comboboxes have event code linked to them (eg, onchange events)

I use their listfillrange or linkedcell properties (clearing these properties seems to alleviate a lot of problems)

(Not sure if this is connected) but there is data validation on the targeted linkedcell.

I program a fairly complex excel application that does a ton of event handling and uses a lot of controls.  Over the months, I have been trying to deal with a variety of bugs dealing with those combo boxes.   I can't recall all the details of each instance now, but these bugs tend to involve pointing the listfillrange and linkedcell properties at named ranges, and often have to do with the combo box events triggering at inappropriate times (such as when application.enableevents = false).  These problems seemed to grow bigger in Excel 2007, so that I had to give up on these combo boxes entirely (I now use combo boxes contained in user forms, rather than directly on the sheets).

Has anyone else seen similar problems?  If so, was there a graceful solution?  I have looked around with Google and so far haven't spotted anyone with similar issues.

Some of the symptoms I end up seeing are:

Excel crashing when I start up (involves combobox_onchange, listfillrange->named range on another different sheet, and workbook_open interactions).  (note, I also had some data validation on the the linked cells in case a user edited them directly.)

Excel rendering bugs (usually when the combo box changes, some cells from another sheet get randomly drawn over the top of the current sheet)   Sometimes it involves the screen flashing entirely to another sheet for a moment.

Excel losing its mind (or rather, the call stack) (related to the first bullet point).  Sometimes when a function modifies a property of the comboboxes, the combobox onchange event fires, but it never returns control to the function that caused the change in the first place.  The combobox_onchange events are triggered even when application.enableevents = false.

Events firing when they shouldn't (I posted another question on stack overflow related to this).

At this point, I am fairly convinced that ActiveX comboboxes are evil incarnate and not worth the trouble.  I have switched to including these comboboxes inside a userform module instead.  I would rather inconvenience users with popup forms than random visual artifacts and crashing (with data loss).

答:
My active-x combo box works fine when my Dell is docked but resizes to a larger font each time it is clicked when the Dell is undocked - very strange.  I added resizing code which works when undocked, but both .height and .scaleheight fail when docked and when triggered programmatically (even stranger).

```<code>        Sheet2.Shapes("cb_SelectSKU").Select
        Selection.ShapeRange.Height = 40
        Selection.ShapeRange.ScaleHeight 0.8, msoFalse, msoScaleFromTopLeft
</code>```

I then added my own enableevents-like switch so that the resizing only occurs when a user selects a combobox value, not when anything is affected while a macro is running.

```<code>Select Case strHoldEvents
    Case Is = "N"                                                   'Combobox resizing fails with error when triggered programatically (from SaveData)

        Call ShowLoadShts

        Sheet2.Shapes("cb_SelectSKU").Select
        Selection.ShapeRange.Height = 40
        Selection.ShapeRange.ScaleHeight 0.8, msoFalse, msoScaleFromTopLeft

    Case Else
End Select
</code>```

Finally that seems to work, whether docked or undocked, whether triggered by the user or during a procedure.  We'll see if it holds...

ContentLicense: CC BY-SA 2.5

Title: Bugs in Excel's ActiveX combo boxes?

Body:
My active-x combo box works fine when my Dell is docked but resizes to a larger font each time it is clicked when the Dell is undocked - very strange.  I added resizing code which works when undocked, but both .height and .scaleheight fail when docked and when triggered programmatically (even stranger).

        Sheet2.Shapes("cb_SelectSKU").Select
        Selection.ShapeRange.Height = 40
        Selection.ShapeRange.ScaleHeight 0.8, msoFalse, msoScaleFromTopLeft

I then added my own enableevents-like switch so that the resizing only occurs when a user selects a combobox value, not when anything is affected while a macro is running.

Select Case strHoldEvents
    Case Is = "N"                                                   'Combobox resizing fails with error when triggered programatically (from SaveData)

        Call ShowLoadShts

        Sheet2.Shapes("cb_SelectSKU").Select
        Selection.ShapeRange.Height = 40
        Selection.ShapeRange.ScaleHeight 0.8, msoFalse, msoScaleFromTopLeft

    Case Else
End Select

Finally that seems to work, whether docked or undocked, whether triggered by the user or during a procedure.  We'll see if it holds...


答:
The problem is that 20160403 looks like an integer. You could try either:

```<code>'2016-04-03'
</code>```

or

```<code>cast('20160403' as date)
</code>```

Without more information it is impossible to check this myself.

Title: Error: INT is incompatible with DATE while passing date argument

Body:
I am getting below error while passing date as parameter to stored procedure

Operand type clash: INT is incompatible with DATE

Tried with 2017-04-03 and '2017-04-03'.Still not working

Example:
exec > 20160403

Procedure defined as :

@stlddate date
...
...

Please help to resolve it.

Body:
The problem is that 20160403 looks like an integer. You could try either:

'2016-04-03'

or

cast('20160403' as date)

Without more information it is impossible to check this myself.


问:
Laravel Multiple orderBy Group Views by Day
I'm using OctoberCMS based on Laravel and Twig.

I'm trying to sort a list of images from the database using orderBy.

I need to display the images grouped by date (desc), then ordered by views (desc) within that date.

I read here to use multiple orderBy passes.

Database Records

```<code>name     | created_at          | views
---------------------------------------
image 01 | 2017-03-27 07:08:31 | 3
image 02 | 2017-03-27 01:19:44 | 25
image 03 | 2017-03-25 01:43:06 | 9
image 04 | 2017-03-25 04:19:43 | 1
image 05 | 2017-03-25 15:19:43 | 12
image 06 | 2017-03-22 03:07:06 | 4
image 07 | 2017-03-22 08:10:07 | 16
image 08 | 2017-03-21 09:04:29 | 39
image 09 | 2017-03-20 07:38:31 | 5
image 10 | 2017-03-20 05:32:24 | 28
</code>```

Laravel

orderBy

Successfully orders by Date created_at, but ignores ordering by views. May be because of time.

```<code>$this->page["scopeGallery"] = Gallery::orderBy('created_at', 'desc')
                                      ->orderBy('views', 'desc')
                                      ->get();
</code>```

groupBy

Returns null.

```<code>$this->page["scopeGallery"] = Gallery::select(\DB::raw('DATE(created_at) as day'))
                                      ->groupBy('day')
                                      ->orderBy('views', 'desc')
                                      ->get();
</code>```

Twig

```<code>{% for image in this.page.scopeGallery %}
    image.name
{% endfor %}
</code>```

Result I'm looking for

```<code>name     | created_at | views
------------------------------
image 02 | 2017-03-27 | 25
image 01 | 2017-03-27 | 3

image 05 | 2017-03-25 | 12
image 03 | 2017-03-25 | 9
image 04 | 2017-03-25 | 1

image 07 | 2017-03-22 | 16
image 06 | 2017-03-22 | 4

image 08 | 2017-03-21 | 39

image 10 | 2017-03-20 | 28
image 09 | 2017-03-20 | 5
</code>```

答:
I had to do it like this, and include any other columns I need in the select.

```<code>$this->page["scopeGallery"] = Gallery::select([
                                        'name',
                                        \DB::raw('DATE(created_at) as day')
                                      ])
                                      ->orderBy('day', 'desc')
                                      ->orderBy('views', 'desc')
                                      ->get();
}
</code>```

Body:
I'm using OctoberCMS based on Laravel and Twig.

I'm trying to sort a list of images from the database using orderBy.

I need to display the images grouped by date (desc), then ordered by views (desc) within that date.

I read here to use multiple orderBy passes.

Database Records

name     | created_at          | views
---------------------------------------
image 01 | 2017-03-27 07:08:31 | 3
image 02 | 2017-03-27 01:19:44 | 25
image 03 | 2017-03-25 01:43:06 | 9
image 04 | 2017-03-25 04:19:43 | 1
image 05 | 2017-03-25 15:19:43 | 12
image 06 | 2017-03-22 03:07:06 | 4
image 07 | 2017-03-22 08:10:07 | 16
image 08 | 2017-03-21 09:04:29 | 39
image 09 | 2017-03-20 07:38:31 | 5
image 10 | 2017-03-20 05:32:24 | 28

Laravel

orderBy

Successfully orders by Date created_at, but ignores ordering by views. May be because of time.

$this->page["scopeGallery"] = Gallery::orderBy('created_at', 'desc')
                                      ->orderBy('views', 'desc')
                                      ->get();

groupBy

Returns null.

$this->page["scopeGallery"] = Gallery::select(\DB::raw('DATE(created_at) as day'))
                                      ->groupBy('day')
                                      ->orderBy('views', 'desc')
                                      ->get();

Twig

{% for image in this.page.scopeGallery %}
    image.name
{% endfor %}

Result I'm looking for

name     | created_at | views
------------------------------
image 02 | 2017-03-27 | 25
image 01 | 2017-03-27 | 3

image 05 | 2017-03-25 | 12
image 03 | 2017-03-25 | 9
image 04 | 2017-03-25 | 1

image 07 | 2017-03-22 | 16
image 06 | 2017-03-22 | 4

image 08 | 2017-03-21 | 39

image 10 | 2017-03-20 | 28
image 09 | 2017-03-20 | 5

Body:
I had to do it like this, and include any other columns I need in the select.

$this->page["scopeGallery"] = Gallery::select([
                                        'name',
                                        \DB::raw('DATE(created_at) as day')
                                      ])
                                      ->orderBy('day', 'desc')
                                      ->orderBy('views', 'desc')
                                      ->get();
}


问:
Rails belongs_to association with multiple foreign keys
I'm trying to figure out a way to define a belongs_to association where the target record can be found by one of 4 different columns. The setup:

User

```<code>class User < ActiveRecord::Base
  has_many :managerships, foreign_key: :employee_id
  has_many :managers, through: :managerships
end
</code>```

Managership

```<code>class Managership < ActiveRecord::Base
  belongs_to :employee, class_name: 'User'
  belongs_to :manager # <-- ideas?
end
</code>```

The managerships table has  4 columns manager_id, manager_custom_id, manager_email, manager_saml_id that we can use to look up the user's managers. For every Managership, only one of these columns is ever present.

I'm looking for a way to be able to call user.managers (a manager is a User) so that it returns all users where managerships.manager_id = users.id OR managerships.manager_custom_id = users.custom_id OR managerships.manager_email = users.email OR managerships.manager_saml_id = users.saml_id

Many thanks for any ideas!

答:
Although, I would doubt that 4 foreign keys for one relation is a good idea at all, one way to get managers from User is to use method instead of scope. However you won't be able to use #joins, if you do so.

```<code>class User
  def managers
   self.class.joins(:managerships).where('managerships.manager_id = ? OR managerships.manager_custom_id = ? OR managerships.manager_email = ? OR managerships.manager_saml_id', id, custom_id, emd, saml_id)
  end
end
</code>```

in Managership you can do similar thing, declare #manger instead of belongs_to :manager

Body:
I'm trying to figure out a way to define a belongs_to association where the target record can be found by one of 4 different columns. The setup:

User

class User < ActiveRecord::Base
  has_many :managerships, foreign_key: :employee_id
  has_many :managers, through: :managerships
end

Managership

class Managership < ActiveRecord::Base
  belongs_to :employee, class_name: 'User'
  belongs_to :manager # <-- ideas?
end

The managerships table has  4 columns manager_id, manager_custom_id, manager_email, manager_saml_id that we can use to look up the user's managers. For every Managership, only one of these columns is ever present.

I'm looking for a way to be able to call user.managers (a manager is a User) so that it returns all users where managerships.manager_id = users.id OR managerships.manager_custom_id = users.custom_id OR managerships.manager_email = users.email OR managerships.manager_saml_id = users.saml_id

Many thanks for any ideas!

Body:
Although, I would doubt that 4 foreign keys for one relation is a good idea at all, one way to get managers from User is to use method instead of scope. However you won't be able to use #joins, if you do so.

class User
  def managers
   self.class.joins(:managerships).where('managerships.manager_id = ? OR managerships.manager_custom_id = ? OR managerships.manager_email = ? OR managerships.manager_saml_id', id, custom_id, emd, saml_id)
  end
end

in Managership you can do similar thing, declare #manger instead of belongs_to :manager


问:
Select one row from one table and multiple rows from other table
I asked a little ago, but I find my question so bad, that it actually didn't help me do what I wanted, so I deleted it and tried again.

I have a table in my database called 'game' with the columns: k1, k1r, k2, k2r, k3, k3r, grp and week. The week-column is automatically inserted with the week of the year and the others are user-inputs from a betting game I made.

Then I have a table called 'matches' with the columns: match1, match2, match3, grp, week. Again, same procedure with the week-column. The other 4 I fill out with the matches we should bet on. The 'grp' column in both is filled by me with 'BS' and 'VF'.

I then have a query:

```<code>SELECT *
FROM game
WHERE week = '.$week.' AND grp = 'bs';
</code>```

$week is already set as $week = Date('W');

It outputs a table, where I write the matches in 3 columns and then echoes the users bets in the rows under the matches. But instead of me changing the php-script every time there are new matches, I would like it to take them from the table 'matches'. In that way, I also keep the old matches in the database.

So, now to my question :)

What I would like to do is something like:

```<code>'SELECT * FROM game WHERE week = '.$week.' AND grp = 'bs'
       JOIN * FROM matches WHERE week = '.$week.' AND grp = 'bs';
</code>```

but as you probably now, that won't work :/

In my other question I forgot to mention the 'grp' column and couldn't figure out how to insert it.

To echo it I used:

```<code>    while ($row = mysqli_fetch_array($query)) {

$no = 1;

$amount = $row['amount'] == 0 ? '' : number_format($row['amount']);
echo '<tr>
<td><strong>'.$row['name'].'</strong></td>

<td>'.$row['k1']."<br />".$row['k1r'].'</td>

<td>'.$row['k2']."<br />".$row['k2r'].'</td>

<td>'.$row['k3']."<br />".$row['k3r'].'</td> }
</code>```

but I would like an outcome like this:

```<code>|       |Match1    |Match2    |Match3    |
|User1  |2-0       |2-1       |2-2       |
|User2  |1-1       |2-2       |1-2       |
</code>```

And so on ... where the 'Matches' are selected from the 'matches'-table and the bets are selected from the 'game'-table. So I just need the one row from 'Matches' as the headline and then loop through the rows in 'Game'.

The creates are:

```<code>CREATE TABLE `game`
(
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `uid` int(11) DEFAULT NULL,
    `user` varchar(20) COLLATE utf8_danish_ci DEFAULT NULL,
    `name` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `k1` varchar(1) COLLATE utf8_danish_ci DEFAULT NULL,
    `k1r` varchar(10) COLLATE utf8_danish_ci DEFAULT NULL,
    `k2` varchar(1) COLLATE utf8_danish_ci DEFAULT NULL,
    `k2r` varchar(10) COLLATE utf8_danish_ci DEFAULT NULL,
    `k3` varchar(1) COLLATE utf8_danish_ci DEFAULT NULL,
    `k3r` varchar(10) COLLATE utf8_danish_ci DEFAULT NULL,
    `week` int(2) DEFAULT NULL,
    `grp` varchar(11) COLLATE utf8_danish_ci DEFAULT NULL,

    PRIMARY KEY (`id`),
    UNIQUE KEY `unique_index` (`uid`,`week`,`grp`)
) ENGINE=MyISAM AUTO_INCREMENT=32 DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci
</code>```

And:

```<code>CREATE TABLE `udvalgte_kampe`
(
    `hold1` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `hold2` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `hold3` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `hold4` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `hold5` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `hold6` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `week` int(2) DEFAULT NULL,
    `grp` varchar(11) COLLATE utf8_danish_ci DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci
</code>```

But what should I do then?

答:
Be aware for sql injection using $var and  you can avoid string concatenation using proper quotes.

your second query   the sintax for join is
is wrong  youn should use this sintax

```<code>"SELECT * FROM game
JOIN matches on game.week  = matches.week
where WHERE game.week = '$week' AND game.grp = 'bs'";
</code>```

and not

```<code>'SELECT * FROM game WHERE week = '.$week.' AND grp = 'bs'
   JOIN * FROM matches WHERE week = '.$week.' AND grp = 'bs';
</code>```

Body:
I asked a little ago, but I find my question so bad, that it actually didn't help me do what I wanted, so I deleted it and tried again.

I have a table in my database called 'game' with the columns: k1, k1r, k2, k2r, k3, k3r, grp and week. The week-column is automatically inserted with the week of the year and the others are user-inputs from a betting game I made.

Then I have a table called 'matches' with the columns: match1, match2, match3, grp, week. Again, same procedure with the week-column. The other 4 I fill out with the matches we should bet on. The 'grp' column in both is filled by me with 'BS' and 'VF'.

I then have a query:

SELECT *
FROM game
WHERE week = '.$week.' AND grp = 'bs';

$week is already set as $week = Date('W');

It outputs a table, where I write the matches in 3 columns and then echoes the users bets in the rows under the matches. But instead of me changing the php-script every time there are new matches, I would like it to take them from the table 'matches'. In that way, I also keep the old matches in the database.

So, now to my question :)

What I would like to do is something like:

'SELECT * FROM game WHERE week = '.$week.' AND grp = 'bs'
       JOIN * FROM matches WHERE week = '.$week.' AND grp = 'bs';

but as you probably now, that won't work :/

In my other question I forgot to mention the 'grp' column and couldn't figure out how to insert it.

To echo it I used:

    while ($row = mysqli_fetch_array($query)) {

$no = 1;

$amount = $row['amount'] == 0 ? '' : number_format($row['amount']);
echo '

'.$row['name'].'

'.$row['k1']."
".$row['k1r'].'

'.$row['k2']."
".$row['k2r'].'

'.$row['k3']."
".$row['k3r'].'	 }

but I would like an outcome like this:

|       |Match1    |Match2    |Match3    |
|User1  |2-0       |2-1       |2-2       |
|User2  |1-1       |2-2       |1-2       |

And so on ... where the 'Matches' are selected from the 'matches'-table and the bets are selected from the 'game'-table. So I just need the one row from 'Matches' as the headline and then loop through the rows in 'Game'.

The creates are:

CREATE TABLE `game`
(
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `uid` int(11) DEFAULT NULL,
    `user` varchar(20) COLLATE utf8_danish_ci DEFAULT NULL,
    `name` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `k1` varchar(1) COLLATE utf8_danish_ci DEFAULT NULL,
    `k1r` varchar(10) COLLATE utf8_danish_ci DEFAULT NULL,
    `k2` varchar(1) COLLATE utf8_danish_ci DEFAULT NULL,
    `k2r` varchar(10) COLLATE utf8_danish_ci DEFAULT NULL,
    `k3` varchar(1) COLLATE utf8_danish_ci DEFAULT NULL,
    `k3r` varchar(10) COLLATE utf8_danish_ci DEFAULT NULL,
    `week` int(2) DEFAULT NULL,
    `grp` varchar(11) COLLATE utf8_danish_ci DEFAULT NULL,

    PRIMARY KEY (`id`),
    UNIQUE KEY `unique_index` (`uid`,`week`,`grp`)
) ENGINE=MyISAM AUTO_INCREMENT=32 DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci

And:

CREATE TABLE `udvalgte_kampe`
(
    `hold1` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `hold2` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `hold3` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `hold4` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `hold5` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `hold6` varchar(50) COLLATE utf8_danish_ci DEFAULT NULL,
    `week` int(2) DEFAULT NULL,
    `grp` varchar(11) COLLATE utf8_danish_ci DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci

But what should I do then?

Body:
Be aware for sql injection using $var and  you can avoid string concatenation using proper quotes.

your second query   the sintax for join is
is wrong  youn should use this sintax

"SELECT * FROM game
JOIN matches on game.week  = matches.week
where WHERE game.week = '$week' AND game.grp = 'bs'";

and not

'SELECT * FROM game WHERE week = '.$week.' AND grp = 'bs'
   JOIN * FROM matches WHERE week = '.$week.' AND grp = 'bs';


问:
How can I put validation in the getter and setter methods in C#?
In C#, I can have a property without having the need to declare a private variable.
My VB6 code that looked like this

```<code>'local variable(s) to hold property value(s)
Private mvarPhoneNumber As String 'local copy
Public Property Let PhoneNumber(ByVal vData As String)
'used when assigning a value to the property, on the left side of an assignment.
'Syntax: X.PhoneNumber = 5
    mvarPhoneNumber = vData
End Property

Public Property Get PhoneNumber() As String
'used when retrieving value of a property, on the right side of an assignment.
'Syntax: Debug.Print X.PhoneNumber
    PhoneNumber = mvarPhoneNumber
End Property
</code>```

can now look like this.

```<code>public string PhoneNumber{get;set;}
</code>```

How can I put validation in the getter and setter methods in C#?
I tried adding a validation like this.

```<code>public string PhoneNumber
        {
            get
            {
                return PhoneNumber;
            }
            set
            {
                if (value.Length <= 30)
                {
                    PhoneNumber = value;
                }
                else
                {
                    PhoneNumber = "EXCEEDS LENGTH";
                }
            }
        }
</code>```

The get part of this code won't compile.
Do I need to revert to using a private variable?

答:
I would do something like this as to avoid a NullReferenceException as well as shorten the overall code.

```<code>public string PhoneNumber
{
    get { return _phoneNumber; }
    set
    {
        var v = value ?? string.Empty;
        _phoneNumber = v.Length <= 30 ? v : "EXCEEDS LENGTH";
    }
}
private string _phoneNumber;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In C#, I can have a property without having the need to declare a private variable.
My VB6 code that looked like this

'local variable(s) to hold property value(s)
Private mvarPhoneNumber As String 'local copy
Public Property Let PhoneNumber(ByVal vData As String)
'used when assigning a value to the property, on the left side of an assignment.
'Syntax: X.PhoneNumber = 5
    mvarPhoneNumber = vData
End Property

Public Property Get PhoneNumber() As String
'used when retrieving value of a property, on the right side of an assignment.
'Syntax: Debug.Print X.PhoneNumber
    PhoneNumber = mvarPhoneNumber
End Property

can now look like this.

public string PhoneNumber{get;set;}

How can I put validation in the getter and setter methods in C#?
I tried adding a validation like this.

public string PhoneNumber
        {
            get
            {
                return PhoneNumber;
            }
            set
            {
                if (value.Length <= 30)
                {
                    PhoneNumber = value;
                }
                else
                {
                    PhoneNumber = "EXCEEDS LENGTH";
                }
            }
        }

The get part of this code won't compile.
Do I need to revert to using a private variable?

Body:
I would do something like this as to avoid a NullReferenceException as well as shorten the overall code.

public string PhoneNumber
{
    get { return _phoneNumber; }
    set
    {
        var v = value ?? string.Empty;
        _phoneNumber = v.Length <= 30 ? v : "EXCEEDS LENGTH";
    }
}
private string _phoneNumber;


问:
why do reverted files show up as changes in the next patchset?
I Made a commit to gerrit .There was a couple of files with no changes apart from white space. Using eclipse I replaced the current version of the file(one with extra unwanted whitespaces ) with the previous version(a version authored by someone else with no extra whitespaces).I then made a few more changes to the code based on comments. So now I'm at the stage where I'm ready to commit again and upload a new patchset for review. However the files I replaced with the previous version are showing up in the staging area a changed files. Is this correct behaviour ?  I am a new user of git / gerrit but this seems odd.</p>

答: Yes, this is correct. They're showing in the staging area as changed files compared to the version with the whitespaces. When you commit the changes (don't forget to use "git commit --amend", this is very important) and execute a "git diff" against the previous commit (the one you have based your change) these files won't show anymore.</p>


问:
C - Install GTK on Windows without hassle?
I'm trying to install GTK+ on Windows but every tutorial says to download 7 different programs, etc. I just want one library that I include in my folder just like SDL has. How to do this?</p>

答:
If you want to use GTK+ for development purposes, please use MSYS2. After you downloaded and installed the MSYS2 bundle, use:

```<code>pacman -S mingw-w64-x86_64-gtk3
</code>```

to install the 64bit version of GTK+ 3.

MSYS also includes packages for the GTK+ language bindings for Python, C++, and others. Additionally, it includes packages for tools like Glade (UI design tool) and DevHelp (offline documentation).

Windows users should not download or build GTK+ directly; application developers should bundle the version of GTK+ used to build the application binary in either a self-extracting zip file, or by using an installer.

Body:
If you want to use GTK+ for development purposes, please use MSYS2. After you downloaded and installed the MSYS2 bundle, use:

pacman -S mingw-w64-x86_64-gtk3

to install the 64bit version of GTK+ 3.

MSYS also includes packages for the GTK+ language bindings for Python, C++, and others. Additionally, it includes packages for tools like Glade (UI design tool) and DevHelp (offline documentation).

Windows users should not download or build GTK+ directly; application developers should bundle the version of GTK+ used to build the application binary in either a self-extracting zip file, or by using an installer.


问:
Suite class not running second test class in espresso using junit4 android
I have write my test cases using espresso and ui automation in android. Now when I run my two different classes of test cases.It always gives error

java.lang.RuntimeException: No activities found. Did you forget to launch the activity by calling getActivity() or startActivitySync or similar?

and does not run MainActivity2Test class. I am not able to understand what I am doing wrong. Search regarding this error also but not able to find any solution. Please help me.

AllTestsSuite.java

```<code>@RunWith(Suite.class)
@Suite.SuiteClasses ({
        MainActivityTest.class,
        MainActivity2Test.class,

})
public class AllTestsSuite {

}
</code>```

MainActivity.java

```<code>@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
   UiDevice device;

    @Rule
    public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule(MainActivity.class, true, false);

   @Test
    public void test1_doLogin(){
        device = UiDevice.getInstance(getInstrumentation());
        device.pressHome();
        device.wait(hasObject(desc("Apps")), 3000);
        UiObject2 appsButton = device.findObject(desc("Apps"));
        appsButton.click();
        UiObject2 appsButton1 = device.findObject(desc("MyApp"));
        appsButton1.click();
test2_emaillPass();
}
 @Test
    public void test2_emaillPass(){
}

}
</code>```

MainActivity2Test.java

```<code>@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(AndroidJUnit4.class)
public class MainActivity2Test {
     UiDevice device;
    @Rule
    public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule(MainActivity.class, true, false);

    @Test
    public  void test3_productFamily(){
       onView(withId(R.id.list)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
       test4_Product();

    }
    @Test
    public  void test4_Product() {
        device = UiDevice.getInstance(getInstrumentation());
        onView(withId(R.id.list)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
        device.wait(hasObject(By.text("First product")), 4000);
        test5_Detail();
    }
</code>```

答:
This line is your problem:

```<code>@Rule
public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule(MainActivity.class, true, false);
</code>```

The last false parameter states if the activity should be launched when the test starts, see the method signature:

```<code>public ActivityTestRule(Class<T> activityClass, boolean initialTouchMode,
        boolean launchActivity)
</code>```

So you either change that last flag to true or you manually launch your activity in each test like this:

```<code>mActivityRule.launchActivity(null);
</code>```

Body:
I have write my test cases using espresso and ui automation in android. Now when I run my two different classes of test cases.It always gives error

java.lang.RuntimeException: No activities found. Did you forget to launch the activity by calling getActivity() or startActivitySync or similar?

and does not run MainActivity2Test class. I am not able to understand what I am doing wrong. Search regarding this error also but not able to find any solution. Please help me.

AllTestsSuite.java

@RunWith(Suite.class)
@Suite.SuiteClasses ({
        MainActivityTest.class,
        MainActivity2Test.class,

})
public class AllTestsSuite {

}

MainActivity.java

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
   UiDevice device;

    @Rule
    public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule(MainActivity.class, true, false);

   @Test
    public void test1_doLogin(){
        device = UiDevice.getInstance(getInstrumentation());
        device.pressHome();
        device.wait(hasObject(desc("Apps")), 3000);
        UiObject2 appsButton = device.findObject(desc("Apps"));
        appsButton.click();
        UiObject2 appsButton1 = device.findObject(desc("MyApp"));
        appsButton1.click();
test2_emaillPass();
}
 @Test
    public void test2_emaillPass(){
}

}

MainActivity2Test.java

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(AndroidJUnit4.class)
public class MainActivity2Test {
     UiDevice device;
    @Rule
    public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule(MainActivity.class, true, false);

    @Test
    public  void test3_productFamily(){
       onView(withId(R.id.list)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
       test4_Product();

    }
    @Test
    public  void test4_Product() {
        device = UiDevice.getInstance(getInstrumentation());
        onView(withId(R.id.list)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
        device.wait(hasObject(By.text("First product")), 4000);
        test5_Detail();
    }

Body:
This line is your problem:

@Rule
public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule(MainActivity.class, true, false);

The last false parameter states if the activity should be launched when the test starts, see the method signature:

public ActivityTestRule(Class<T> activityClass, boolean initialTouchMode,
        boolean launchActivity)

So you either change that last flag to true or you manually launch your activity in each test like this:

mActivityRule.launchActivity(null);


问:
How to find all rows with background-color yellow using jquery?
I would like to find all rows with attribute background-color=rgb(255, 255, 0).
Pressing on the button 'Search' should do this. I don't understand why this is not working. Nothing is found. Code for searching:

```<code>$("#btnSearch").click(function(){
  var rows = $("#tbl1 tr[style='background-color:rgb(255, 255, 0)']");
})
</code>```

Whole example is here

答:
The clean approach would be to use a class instead of inline styles.

$("#btnSearch").click(function() {

  console.log($('#tbl1 tr.yellow'))
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.yellow {
  background-color: rgb(255, 255, 0);
}</code>```

      #
      Ime izdelka
      Opisni REF
      LOT/serijska/EDI
      Stanje (REF)
      Stanje (LOT)
      Privzeta skupina

      1
      Kortikalni 2.0/14mm (zlati)
      401.364
      8036572
      6
      3
      Stopalo - SYNTHES

      2
      Kortikalni 2.0/14mm (zlati)
      401.364
      8327937
      6
      1
      Stopalo - SYNTHES

      3
      Kortikalni 2.0/14mm (zlati)
      401.364
      9572333
      6
      2
      Stopalo - SYNTHES

<button id="btnSearch">Search</button>```

Body:
I would like to find all rows with attribute background-color=rgb(255, 255, 0).
Pressing on the button 'Search' should do this. I don't understand why this is not working. Nothing is found. Code for searching:

$("#btnSearch").click(function(){
  var rows = $("#tbl1 tr[style='background-color:rgb(255, 255, 0)']");
})

Whole example is here

Body:
The clean approach would be to use a class instead of inline styles.

$("#btnSearch").click(function() {

  console.log($('#tbl1 tr.yellow'))
})

.yellow {
  background-color: rgb(255, 255, 0);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='tbl1' class="table table-hover table-bordered">
  <thead>
    <tr>
      <th>#</th>
      <th>Ime izdelka</th>
      <th>Opisni REF</th>
      <th>LOT/serijska/EDI</th>
      <th>Stanje (REF)</th>
      <th>Stanje (LOT)</th>
      <th>Privzeta skupina</th>
    </tr>
  </thead>
  <tfoot>

  </tfoot>
  <tbody>
    <tr class="yellow">
      <td data-id="iROW_NUMBER" style="background-color: rgb(255, 255, 0);">1</td>
      <td data-id="cPROD_NME" style="background-color: rgb(255, 255, 0);">Kortikalni 2.0/14mm (zlati)</td>
      <td data-id="cPROD_DCD" style="background-color: rgb(255, 255, 0);">401.364</td>
      <td data-id="cPRSE_DCD" style="background-color: rgb(255, 255, 0);">8036572</td>
      <td data-id="iPROD_QUA_QUA" style="background-color: rgb(255, 255, 0);">6</td>
      <td data-id="cPRSS_QUA_QUA" style="background-color: rgb(255, 255, 0);">3</td>
      <td data-id="cPRGR_NME" style="background-color: rgb(255, 255, 0);">Stopalo - SYNTHES</td>
    </tr>
    <tr class="yellow">
      <td data-id="iROW_NUMBER" style="background-color: rgb(255, 255, 0);">2</td>
      <td data-id="cPROD_NME" style="background-color: rgb(255, 255, 0);">Kortikalni 2.0/14mm (zlati)</td>
      <td data-id="cPROD_DCD" style="background-color: rgb(255, 255, 0);">401.364</td>
      <td data-id="cPRSE_DCD" style="background-color: rgb(255, 255, 0);">8327937</td>
      <td data-id="iPROD_QUA_QUA" style="background-color: rgb(255, 255, 0);">6</td>
      <td data-id="cPRSS_QUA_QUA" style="background-color: rgb(255, 255, 0);">1</td>
      <td data-id="cPRGR_NME" style="background-color: rgb(255, 255, 0);">Stopalo - SYNTHES</td>
    </tr>
    <tr>
      <td data-id="iROW_NUMBER">3</td>
      <td data-id="cPROD_NME">Kortikalni 2.0/14mm (zlati)</td>
      <td data-id="cPROD_DCD">401.364</td>
      <td data-id="cPRSE_DCD">9572333</td>
      <td data-id="iPROD_QUA_QUA">6</td>
      <td data-id="cPRSS_QUA_QUA">2</td>
      <td data-id="cPRGR_NME">Stopalo - SYNTHES</td>
    </tr>
  </tbody>
</table>

<br/>
<br/>
<button id="btnSearch">Search</button>


问:
Add and show list product in cart codeigniter
I have a problem when I add some products to cart, but then when I want to fetch contents of the cart I find it is empty.

this is my controller :

```<code>public function add_to_cart(){

    $insert_data = array(
     'id' => $this->input->post('id'),
     'name' => $this->input->post('name'),
     'price' => $this->input->post('price'),
     'qty' => $this->input->post('qty') );

     // This function add items into cart.
    $this->cart->insert($insert_data);

}
</code>```

and this is my form to add new product to cart :

```<code><div class="button-group">
                  <form method="POST" action="<?php echo base_url().'add_to_cart'; ?>">
                  <div style="display:none">
                  <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash();?>" />
                  </div>
                  <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
                    <input type="number" name="qty" id="<?php echo $ligneBase->id;?>">
                    <input type="hidden" name="name" value="<?php echo $ligneBase->name;?>">
                    <input type="hidden"  name="price"  value="<?php echo $ligneBase->price;?>">
                    <input type="hidden"  name="id"  value="<?php echo $ligneBase->id;?>">
                      <input class="add_cart" type="submit" value="Add to cart">
                      <div class="add-to-links">
                  </form>
                </div>
</code>```

and this is my cart in header.php :

```<code><table class="table">
                <tbody>
                <div id="text">
                  <?php $cart_check = $this->cart->contents();

                  // If cart is empty, this will show below message.
                  if(empty($cart_check)) {
                  echo '<h4 align="center">No Product in cart, To add products to your shopping cart click on "Add to Cart" Button</h4>';
                  } ?>
                </div>

                  <?php
                     $cart = $this->cart->contents();
                     foreach($cart as $indice => $ligneBase){
                  ?>
                  <tr>
                    <td class="text-center"><a href="product.html"><img class="img-thumbnail" title="Xitefun Causal Wear Fancy Shoes" alt="Xitefun Causal Wear Fancy Shoes" src="image/product/sony_vaio_1-50x50.jpg"></a></td>
                    <td class="text-left"><a href="product.html"><?php echo $ligneBase->id;?></a></td>
                    <td class="text-right">x 1</td>
                    <td class="text-right"><?php echo $ligneBase->name;?> </td>
                    <td class="text-center"><button class="btn btn-danger btn-xs remove" title="Remove" onClick="" type="button"><i class="fa fa-times"></i></button></td>
                  </tr>

                <?php
                  }
                ?>

                </tbody>
              </table>
</code>```

答:
Can I suggest a bit improvements in your code structure. You need to use a model for db interactions

Step-1. Controller Function

```<code>public function cart()
{
    $data['cart_items']=$this->cart_model->getCartItems();
    if($_POST)
    {
        // Perform Validation
        if($this->form_validation->run()==false)
        {
            $data['errors']=validation_errors();
            $this->load->view('cart_view',$data);
        }
        else
        {
            $row=$this->cart_model->insertToCart($this->security->xss_clean($_POST));
            if($row)
            {
                $data['success']='Item Added';
                $this->load->view('cart_view',$data);
            }
            else
            {
                $data['error']='Item Could not be Added';
                $this->load->view('cart_view',$data);
            }
        }
    }
    else
    {
        $this->load->view('cart_view',$data);
    }

}
</code>```

Step-2. Model Functions

```<code>public function getCartItems()
{
    $sql='create query';
    return $this->db->query($sql)->result_array();
}

public function insertToCart($data)
{
    $item=array(
        'field' => $data['index']
    );
    $this->db->insert('cart',$item);
    return $this->db->insert_id();
}
</code>```

Step-3. View

```<code><div class="button-group">
     <form method="POST" action="">
       <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash();?>" />
       <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
       <input type="number" name="qty" id="<?php echo $ligneBase->id;?>">
       <input type="hidden" name="name" value="<?php echo $ligneBase->name;?>">
       <input type="hidden"  name="price"  value="<?php echo $ligneBase->price;?>">
       <input type="hidden"  name="id"  value="<?php echo $ligneBase->id;?>">
       <input class="add_cart" type="submit" value="Add to cart">
       <div class="add-to-links">
      </form>
 </div>
</code>```

Body:
I have a problem when I add some products to cart, but then when I want to fetch contents of the cart I find it is empty.

this is my controller :

public function add_to_cart(){

    $insert_data = array(
     'id' => $this->input->post('id'),
     'name' => $this->input->post('name'),
     'price' => $this->input->post('price'),
     'qty' => $this->input->post('qty') );

     // This function add items into cart.
    $this->cart->insert($insert_data);

}

and this is my form to add new product to cart :

                  <form method="POST" action="<?php echo base_url().'add_to_cart'; ?>">

                  <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash();?>" />

                  <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
                    <input type="number" name="qty" id="<?php echo $ligneBase->id;?>">
                    <input type="hidden" name="name" value="<?php echo $ligneBase->name;?>">
                    <input type="hidden"  name="price"  value="<?php echo $ligneBase->price;?>">
                    <input type="hidden"  name="id"  value="<?php echo $ligneBase->id;?>">
                      <input class="add_cart" type="submit" value="Add to cart">

                  </form>

and this is my cart in header.php :

                  <?php $cart_check = $this->cart->contents();

                  // If cart is empty, this will show below message.
                  if(empty($cart_check)) {
                  echo '
No Product in cart, To add products to your shopping cart click on "Add to Cart" Button
';
                  } ?>

                  <?php
                     $cart = $this->cart->contents();
                     foreach($cart as $indice => $ligneBase){
                  ?>

                    <?php echo $ligneBase->id;?>
                    x 1
                    <?php echo $ligneBase->name;?>
                    <button class="btn btn-danger btn-xs remove" title="Remove" onClick="" type="button"></button>

                <?php
                  }
                ?>

Body:
Can I suggest a bit improvements in your code structure. You need to use a model for db interactions

Step-1. Controller Function

public function cart()
{
    $data['cart_items']=$this->cart_model->getCartItems();
    if($_POST)
    {
        // Perform Validation
        if($this->form_validation->run()==false)
        {
            $data['errors']=validation_errors();
            $this->load->view('cart_view',$data);
        }
        else
        {
            $row=$this->cart_model->insertToCart($this->security->xss_clean($_POST));
            if($row)
            {
                $data['success']='Item Added';
                $this->load->view('cart_view',$data);
            }
            else
            {
                $data['error']='Item Could not be Added';
                $this->load->view('cart_view',$data);
            }
        }
    }
    else
    {
        $this->load->view('cart_view',$data);
    }

}

Step-2. Model Functions

public function getCartItems()
{
    $sql='create query';
    return $this->db->query($sql)->result_array();
}

public function insertToCart($data)
{
    $item=array(
        'field' => $data['index']
    );
    $this->db->insert('cart',$item);
    return $this->db->insert_id();
}

Step-3. View

<div class="button-group">
     <form method="POST" action="">
       <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash();?>" />
       <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
       <input type="number" name="qty" id="<?php echo $ligneBase->id;?>">
       <input type="hidden" name="name" value="<?php echo $ligneBase->name;?>">
       <input type="hidden"  name="price"  value="<?php echo $ligneBase->price;?>">
       <input type="hidden"  name="id"  value="<?php echo $ligneBase->id;?>">
       <input class="add_cart" type="submit" value="Add to cart">
       <div class="add-to-links">
      </form>
 </div>


问:
"Operation must use an updateable query" error in MS Access
I am getting an error message: "Operation must use an updateable query" when I try to run my SQL. From my understanding, this happens when joins are used in update/delete queries in MS Access. However, I'm a little confused because I have another query almost identical in my database which works fine.

This is my troublesome query:

```<code>UPDATE [GS] INNER JOIN [Views] ON
    ([Views].Hostname = [GS].Hostname)
    AND ([GS].APPID = [Views].APPID)
    SET
        [GS].APPID = [Views].APPID,
        [GS].[Name] = [Views].[Name],
        [GS].Hostname = [Views].Hostname,
        [GS].[Date] = [Views].[Date],
        [GS].[Unit] = [Views].[Unit],
        [GS].[Owner] = [Views].[Owner];
</code>```

As I said before, I am confused because I have another query similar to this, which runs perfectly. This is that query:

```<code>UPDATE [Views] INNER JOIN [GS] ON
[Views].APPID = [GS].APPID
SET
    [GS].APPID = [Views].APPID,
    [GS].[Name] = [Views].[Name],
    [GS].[Criticial?] = [Views].[Criticial?],
    [GS].[Unit] = [Views].[Unit],
    [GS].[Owner] = [Views].[Owner];
</code>```

What is wrong with my first query? Why does the second query work when the first doesn't?

答: I was accessing the database using UNC path and occasionally this exception was thrown. When I replaced the computer name with IP address, the problem was suddenly resolved.</p>

Body:
I am getting an error message: "Operation must use an updateable query" when I try to run my SQL. From my understanding, this happens when joins are used in update/delete queries in MS Access. However, I'm a little confused because I have another query almost identical in my database which works fine.

This is my troublesome query:

UPDATE [GS] INNER JOIN [Views] ON
    ([Views].Hostname = [GS].Hostname)
    AND ([GS].APPID = [Views].APPID)
    SET
        [GS].APPID = [Views].APPID,
        [GS].[Name] = [Views].[Name],
        [GS].Hostname = [Views].Hostname,
        [GS].[Date] = [Views].[Date],
        [GS].[Unit] = [Views].[Unit],
        [GS].[Owner] = [Views].[Owner];

As I said before, I am confused because I have another query similar to this, which runs perfectly. This is that query:

UPDATE [Views] INNER JOIN [GS] ON
[Views].APPID = [GS].APPID
SET
    [GS].APPID = [Views].APPID,
    [GS].[Name] = [Views].[Name],
    [GS].[Criticial?] = [Views].[Criticial?],
    [GS].[Unit] = [Views].[Unit],
    [GS].[Owner] = [Views].[Owner];

What is wrong with my first query? Why does the second query work when the first doesn't?


问:
What is the proper Lua pattern for quoted text?
I've been playing with this for an hour or tow and have found myself at a road block with the Lua pattern matching utilities.  I am attempting to match all quoted text in a string and replace it if needed.

The pattern I have come up with so far is: (\?[\"\'])(.-)%1

This works in some cases but, not all cases:

```<code>Working: "This \"is a\" string of \"text to\" test with"

Not Working: "T\\\"his \"is\' a\" string\" of\' text\" to \"test\" wit\\\"h"
</code>```

In the not working example I would like it to match to (I made a function that gets the matches I desire, I'm just looking for a pattern to use with gsub and curious if a lua pattern can do this):

```<code> string
 a" string" of
is' a" string" of' text
test
his "is' a" string" of' text" to "test" wit
</code>```

I'm going to continue to use my function instead for the time being, but am curious if there is a pattern I could/should be using and i'm just missing something with patterns.

(a few edits b/c I forgot about stackoverflows formating)
(another edit to make a non-html example since it was leading to assumptions that I was attempting to parse html)

答: you should NOT be trying to parse HTML with regular expressions, HTML and XML are NOT regular languages and can not be successfully manipulated with regular expressions. You should use a dedicated HTML parser. Here are lots of explanations why.

Body:
I've been playing with this for an hour or tow and have found myself at a road block with the Lua pattern matching utilities.  I am attempting to match all quoted text in a string and replace it if needed.

The pattern I have come up with so far is: (\?[\"\'])(.-)%1

This works in some cases but, not all cases:

Working: "This \"is a\" string of \"text to\" test with"

Not Working: "T\\\"his \"is\' a\" string\" of\' text\" to \"test\" wit\\\"h"

In the not working example I would like it to match to (I made a function that gets the matches I desire, I'm just looking for a pattern to use with gsub and curious if a lua pattern can do this):

 string
 a" string" of
is' a" string" of' text
test
his "is' a" string" of' text" to "test" wit

I'm going to continue to use my function instead for the time being, but am curious if there is a pattern I could/should be using and i'm just missing something with patterns.

(a few edits b/c I forgot about stackoverflows formating)
(another edit to make a non-html example since it was leading to assumptions that I was attempting to parse html)