问:
Name of this type of inheritance semantic
```<code>public class _base
{
    protected int x = 5;
    protected int GetX(_base b) { return b.x; }
}

public class _derived : _base
{
    public int Foo()
    {
        var b = new _base();
        //return b.x;  // <-- this would be illegal
        return GetX(b); // <-- This works and does exactly the same as the line above
    }
}
</code>```

(Please don't change code. It is working and shows the problem.)

The error is

```<code>Cannot access protected member '_base.x' via a qualifier of type '_base'; the qualifier must be of type '_derived' (or derived from it)
</code>```

Note that because b is of type _base and we are not in base we cannot access it's protected members. I imagine the reason is because _base might be of some other derived type and hence it is not protecting the code but that's not the point. What I'm doing is creating a work around for the above problem using the extra protected methods. This gives me the behavior I want and the protection I want. I wish there were a keyword that allows this kinda access but there isn't. What I'm interested in is if this "pattern" has a name.

(I'm using protected because internal allows anyone in the same assembly access)

答:
UPDATE: Rewriting this answer since the question has been rewritten.

I'm unaware of any name for the pattern you've illustrated.

As you conjecture, the reason it is illegal to access the field is because we don't know that the instance b is an instance of _derived. "protected" access means that _derived is only allowed to access protected members of instances of _derived; it is not allowed access to protected members of instances of "SomeOtherType" that is also derived from _base.

Now, if the question really is "is there any way to get direct access to the member x from every derived class through any instance?" then yes. You reject the obvious solution of making it internal. (*) There is another way. Do this:

```<code>abstract class B
{
    private B() {}
    private int x;
    private class D1 : B { }
    private class D2 : B { }
    public static B MakeD1() { return new D1(); }
    public static B MakeD2() { return new D2(); }
}
</code>```

Now methods of B and methods of derived classes D1 and D2 are all capable of accessing this.x directly, but methods of no other types are capable of doing so. There are no other derived types other than D1 and D2; there cannot be because the only constructor of B is private. And there cannot be any instances of B that are not D1 or D2 because it is abstract.

(*) Remember, if you make it internal then the only people you have to worry about accessing your member are your coworkers. Putting the smack down on them in code review if they do something abusive to the member is a perfectly acceptable solution around here.

Body:
public class _base
{
    protected int x = 5;
    protected int GetX(_base b) { return b.x; }
}

public class _derived : _base
{
    public int Foo()
    {
        var b = new _base();
        //return b.x;  // <-- this would be illegal
        return GetX(b); // <-- This works and does exactly the same as the line above
    }
}

(Please don't change code. It is working and shows the problem.)

The error is

Cannot access protected member '_base.x' via a qualifier of type '_base'; the qualifier must be of type '_derived' (or derived from it)

Note that because b is of type _base and we are not in base we cannot access it's protected members. I imagine the reason is because _base might be of some other derived type and hence it is not protecting the code but that's not the point. What I'm doing is creating a work around for the above problem using the extra protected methods. This gives me the behavior I want and the protection I want. I wish there were a keyword that allows this kinda access but there isn't. What I'm interested in is if this "pattern" has a name.

(I'm using protected because internal allows anyone in the same assembly access)

Body:
UPDATE: Rewriting this answer since the question has been rewritten.

I'm unaware of any name for the pattern you've illustrated.

As you conjecture, the reason it is illegal to access the field is because we don't know that the instance b is an instance of _derived. "protected" access means that _derived is only allowed to access protected members of instances of _derived; it is not allowed access to protected members of instances of "SomeOtherType" that is also derived from _base.

Now, if the question really is "is there any way to get direct access to the member x from every derived class through any instance?" then yes. You reject the obvious solution of making it internal. (*) There is another way. Do this:

abstract class B
{
    private B() {}
    private int x;
    private class D1 : B { }
    private class D2 : B { }
    public static B MakeD1() { return new D1(); }
    public static B MakeD2() { return new D2(); }
}

Now methods of B and methods of derived classes D1 and D2 are all capable of accessing this.x directly, but methods of no other types are capable of doing so. There are no other derived types other than D1 and D2; there cannot be because the only constructor of B is private. And there cannot be any instances of B that are not D1 or D2 because it is abstract.

(*) Remember, if you make it internal then the only people you have to worry about accessing your member are your coworkers. Putting the smack down on them in code review if they do something abusive to the member is a perfectly acceptable solution around here.


来源: stackexchange

问:
Android Volley slow internet issue
Hi I am using Volley for Networking in Android , Everything is working fine the problem is on Slow Internet Error , where time out happens but request sent to server some time it is getting processed . Can someone help me out , Even i tried increasing timeout but nothing is helpful.</p>

答:
```<code>      @Override
   public void onErrorResponse(VolleyError volleyError) {
   String message = null;
   if (volleyError instanceof NetworkError) {
         message = "Cannot connect to Internet...Please check your connection!";
   } else if (volleyError instanceof ServerError) {
         message = "The server could not be found. Please try again after some time!!";
   } else if (volleyError instanceof AuthFailureError) {
         message = "Cannot connect to Internet...Please check your connection!";
   } else if (volleyError instanceof ParseError) {
         message = "Parsing error! Please try again after some time!!";
   } else if (volleyError instanceof NoConnectionError) {
         message = "Cannot connect to Internet...Please check your connection!";
   } else if (volleyError instanceof TimeoutError) {
         message = "Connection TimeOut! Please check your internet connection.";
   }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android Volley slow internet issue


问:
Access-Control-Allow-Origin contains invalid value
when i send a request in angular 2 using http service ,the browser showing following error.
can any one tell the solution ???

XMLHttpRequest cannot load http://192.168.1.59:1340/User/add. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains the invalid value ''. Origin 'http://192.168.1.59:8083' is therefore not allowed access.

答:
You need to enable cors in the config/cors.js file

```<code>allRoutes: false, // Change to true if you want to enable cors in all routes.

origin: 'https://myapp.com,https://auth.myapp.com' // use * for any origin.
</code>```

If you want to enable cors only for a particular route, in config/routes.js

```<code>'get /foo/bar': {
    controller: 'FooController',
    action: 'bar',
    cors: true
  },
</code>```

Body:
You need to enable cors in the config/cors.js file

allRoutes: false, // Change to true if you want to enable cors in all routes.

origin: 'https://myapp.com,https://auth.myapp.com' // use * for any origin.

If you want to enable cors only for a particular route, in config/routes.js

'get /foo/bar': {
    controller: 'FooController',
    action: 'bar',
    cors: true
  },


问:
Write a MySQL query to find the all the names which contain the word or a part of a word DAVID, sort the result in the order of similarity
Example: David, Davi, Dav, Da, D (Names containing the word David, later names containing Davi and so on from employee table with name as a column name)</p>

答:
I guess the only way you can do is:

SELECT Name FROM Employee WHERE NAME LIKE "%DAVID%" OR %DAVI%" OR "%DAV%" OR "%DA%" OR "%D%" ORDER BY Name;


问:
Objective C Create 2D array of unknown size and access it
I am still new to objective C. I would like to create a 2D array of unknown size such that i can access it and add values. I come from a C++ background and looking at tutorial point and examples such as Declaring and Initializing 2D array of unknown size in C it seems there is a similarity in creation of a 2D array between C++ and Objective C.

I have implemented the following example and i get an error:

Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'**

I am not sure what is causing the error, i would be grateful for assistance in solving this error and understanding it.

```<code>-(NSMutableArray *)categoryCk
{
    if (!_categoryCk)
    {
        _categoryCk = [[NSMutableArray alloc] init];
    }
    return _categoryCk;
}
-(NSMutableArray *)subcategoryCv
{
    if (!_subcategoryCv)
    {
        _subcategoryCv = [[NSMutableArray alloc] init];
    }
    return _subcategoryCv;
}

-(NSMutableArray *)subcategoryCk
{
    if (!_subcategoryCk)
    {
         _subcategoryCk = [[NSMutableArray alloc] init];
    }
    return _subcategoryCk;
}
-(NSMutableArray *)outcomeCv
{
    if (!_outcomeCv)
    {
        _outcomeCv = [[NSMutableArray alloc] init];
    }
    return _outcomeCv;
}

-(NSMutableArray *)outcomeCk
{
    if (!_outcomeCk)
    {
        _outcomeCk = [[NSMutableArray alloc] init];
    }
    return _outcomeCk;
}
</code>```

Then the loops to create the arrays:

```<code>if([categories count]>0){

    for (int i =0; i < categories.count; i++)

    {
        NSArray* subCategories= [categories[i] objectForKey: @"subCategories"];

        NSDictionary *categoryItems = [categories objectAtIndex:i];
        NSString *category = [categoryItems objectForKey:@"cv"];
        NSLog(@"%@",category);
        [self.categoryCv addObject:category];
        NSString *categoryNum = [categoryItems objectForKey:@"ck"];
        [self.categoryCk addObject:categoryNum];

        if ([subCategories count] > 0){

        for (int j = 0; j < subCategories.count; j++) {

            if (self.subcategoryCv.count <= i) {
                [self.subcategoryCv addObject:[[NSMutableArray alloc] init]];
            }

            if ([self.subcategoryCv[i] count] <= j) {
                [self.subcategoryCv[i] addObject:[[NSMutableArray alloc] init]];
            }
            if (self.subcategoryCk.count <= i) {
                [self.subcategoryCk addObject:[[NSMutableArray alloc] init]];
            }

            if ([self.subcategoryCk[i] count] <= j) {
                [self.subcategoryCk[i] addObject:[[NSMutableArray alloc] init]];
            }

            NSDictionary *subcategoryItems = [subCategories objectAtIndex:j];
            NSString *subCategoryCv = [subcategoryItems objectForKey:@"cv"];
            [self.subcategoryCv[i][j] addObject:subCategoryCv];
            NSString *subCatNum = [subcategoryItems objectForKey:@"ck"];
            [self.subcategoryCk[i][j] addObject:subCatNum];

            NSArray* outcome =[[subCategories objectAtIndex:j] objectForKey:@"outcomes"];

            if ([outcome count] > 0) {

            for (int k = 0; k < outcome.count; k++) {

                if (self.outcomeCv.count <= j) {
                    [self.outcomeCv addObject:[[NSMutableArray alloc] init]];
                }

                if ([self.outcomeCv[j] count] <= k) {
                    [self.outcomeCv[j] addObject:[[NSMutableArray alloc] init]];
                }

                if (self.outcomeCk.count <= j) {
                    [self.outcomeCk addObject:[[NSMutableArray alloc] init]];
                }

                if ([self.outcomeCk[j] count] <= k) {
                    [self.outcomeCk[j] addObject:[[NSMutableArray alloc] init]];
                }

                NSDictionary *outComeItems = [outcome objectAtIndex:k];
                NSString *outcomeCategoryCV = [outComeItems objectForKey:@"cv"];
                //NSLog(@"%@",outcomeCatCV);
                [self.outcomeCv[j][k] addObject:outcomeCategoryCV];
                NSString *outCatNum = [outComeItems objectForKey:@"ck"];
                [self.outcomeCk[j][k] addObject:outCatNum];

            }
            }else{

            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                               message:@"Error loading data from service : Empty Outcomes data"
                                                                        preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                                      handler:^(UIAlertAction * action) {}];

            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];

            }
        }
        } else{

            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                           message:@"Error loading data from service : Empty Sub-Categories data"
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                                  handler:^(UIAlertAction * action) {}];

            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }

}else{

    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                   message:@"Error loading data from service : Empty Categories data"
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {}];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];

}
</code>```

This is how i try to access the array :

```<code> cell.textLabel.text = [self.outcomeCv[categoryIndex][subcategoryIndex] objectAtIndex:indexPath.row] ;
</code>```

答:
When you call subcategoryCv[i][j], you have to make sure that

subcategoryCv.count > i && subcategoryCv[i].count > j

if not, you will got crash in you question.

To prevent it, you need to add a new NSMutableArray to subcategoryCv when subcategoryCv.count <= i and add a new NSMutableArray to subcategoryCv[i] when subcategoryCv[i].count <= j.

It's same with another 2D array. For example with subcategoryCv

```<code>if (self.subcategoryCv.count <= i) {
  [self.subcategoryCv addObject:[[NSMutableArray alloc] init]];
}

if ([self.subcategoryCv[i] count] <= j) {
  [self.subcategoryCv[i] addObject:[[NSMutableArray alloc] init]];
}

NSDictionary *subcategoryItems = [subCategories objectAtIndex:j];
NSString *subCategoryCv = [subcategoryItems objectForKey:@"cv"];
[self.subcategoryCv[i][j] addObject:subCategoryCv];
NSString *subCatNum = [subcategoryItems objectForKey:@"ck"];
[self.subcategoryCk[i][j] addObject:subCatNum];
</code>```

Body:
I am still new to objective C. I would like to create a 2D array of unknown size such that i can access it and add values. I come from a C++ background and looking at tutorial point and examples such as Declaring and Initializing 2D array of unknown size in C it seems there is a similarity in creation of a 2D array between C++ and Objective C.

I have implemented the following example and i get an error:

Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'**

I am not sure what is causing the error, i would be grateful for assistance in solving this error and understanding it.

-(NSMutableArray *)categoryCk
{
    if (!_categoryCk)
    {
        _categoryCk = [[NSMutableArray alloc] init];
    }
    return _categoryCk;
}
-(NSMutableArray *)subcategoryCv
{
    if (!_subcategoryCv)
    {
        _subcategoryCv = [[NSMutableArray alloc] init];
    }
    return _subcategoryCv;
}

-(NSMutableArray *)subcategoryCk
{
    if (!_subcategoryCk)
    {
         _subcategoryCk = [[NSMutableArray alloc] init];
    }
    return _subcategoryCk;
}
-(NSMutableArray *)outcomeCv
{
    if (!_outcomeCv)
    {
        _outcomeCv = [[NSMutableArray alloc] init];
    }
    return _outcomeCv;
}

-(NSMutableArray *)outcomeCk
{
    if (!_outcomeCk)
    {
        _outcomeCk = [[NSMutableArray alloc] init];
    }
    return _outcomeCk;
}

Then the loops to create the arrays:

if([categories count]>0){

    for (int i =0; i < categories.count; i++)

    {
        NSArray* subCategories= [categories[i] objectForKey: @"subCategories"];

        NSDictionary *categoryItems = [categories objectAtIndex:i];
        NSString *category = [categoryItems objectForKey:@"cv"];
        NSLog(@"%@",category);
        [self.categoryCv addObject:category];
        NSString *categoryNum = [categoryItems objectForKey:@"ck"];
        [self.categoryCk addObject:categoryNum];

        if ([subCategories count] > 0){

        for (int j = 0; j < subCategories.count; j++) {

            if (self.subcategoryCv.count <= i) {
                [self.subcategoryCv addObject:[[NSMutableArray alloc] init]];
            }

            if ([self.subcategoryCv[i] count] <= j) {
                [self.subcategoryCv[i] addObject:[[NSMutableArray alloc] init]];
            }
            if (self.subcategoryCk.count <= i) {
                [self.subcategoryCk addObject:[[NSMutableArray alloc] init]];
            }

            if ([self.subcategoryCk[i] count] <= j) {
                [self.subcategoryCk[i] addObject:[[NSMutableArray alloc] init]];
            }

            NSDictionary *subcategoryItems = [subCategories objectAtIndex:j];
            NSString *subCategoryCv = [subcategoryItems objectForKey:@"cv"];
            [self.subcategoryCv[i][j] addObject:subCategoryCv];
            NSString *subCatNum = [subcategoryItems objectForKey:@"ck"];
            [self.subcategoryCk[i][j] addObject:subCatNum];

            NSArray* outcome =[[subCategories objectAtIndex:j] objectForKey:@"outcomes"];

            if ([outcome count] > 0) {

            for (int k = 0; k < outcome.count; k++) {

                if (self.outcomeCv.count <= j) {
                    [self.outcomeCv addObject:[[NSMutableArray alloc] init]];
                }

                if ([self.outcomeCv[j] count] <= k) {
                    [self.outcomeCv[j] addObject:[[NSMutableArray alloc] init]];
                }

                if (self.outcomeCk.count <= j) {
                    [self.outcomeCk addObject:[[NSMutableArray alloc] init]];
                }

                if ([self.outcomeCk[j] count] <= k) {
                    [self.outcomeCk[j] addObject:[[NSMutableArray alloc] init]];
                }

                NSDictionary *outComeItems = [outcome objectAtIndex:k];
                NSString *outcomeCategoryCV = [outComeItems objectForKey:@"cv"];
                //NSLog(@"%@",outcomeCatCV);
                [self.outcomeCv[j][k] addObject:outcomeCategoryCV];
                NSString *outCatNum = [outComeItems objectForKey:@"ck"];
                [self.outcomeCk[j][k] addObject:outCatNum];

            }
            }else{

            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                               message:@"Error loading data from service : Empty Outcomes data"
                                                                        preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                                      handler:^(UIAlertAction * action) {}];

            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];

            }
        }
        } else{

            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                           message:@"Error loading data from service : Empty Sub-Categories data"
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                                  handler:^(UIAlertAction * action) {}];

            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }

}else{

    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                   message:@"Error loading data from service : Empty Categories data"
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {}];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];

}

This is how i try to access the array :

 cell.textLabel.text = [self.outcomeCv[categoryIndex][subcategoryIndex] objectAtIndex:indexPath.row] ;

Body:
When you call subcategoryCv[i][j], you have to make sure that

subcategoryCv.count > i && subcategoryCv[i].count > j

if not, you will got crash in you question.

To prevent it, you need to add a new NSMutableArray to subcategoryCv when subcategoryCv.count <= i and add a new NSMutableArray to subcategoryCv[i] when subcategoryCv[i].count <= j.

It's same with another 2D array. For example with subcategoryCv

if (self.subcategoryCv.count <= i) {
  [self.subcategoryCv addObject:[[NSMutableArray alloc] init]];
}

if ([self.subcategoryCv[i] count] <= j) {
  [self.subcategoryCv[i] addObject:[[NSMutableArray alloc] init]];
}

NSDictionary *subcategoryItems = [subCategories objectAtIndex:j];
NSString *subCategoryCv = [subcategoryItems objectForKey:@"cv"];
[self.subcategoryCv[i][j] addObject:subCategoryCv];
NSString *subCatNum = [subcategoryItems objectForKey:@"ck"];
[self.subcategoryCk[i][j] addObject:subCatNum];


问:
update validation In laravel with unique check in multiple tables
In laravel with unique check in multiple tables, I do this for create new field:

```<code> //store function

'slug' => 'required|unique:articles,slug|unique:zones,slug
</code>```

It works well.

but what can I do for update?

I test this:

```<code>public function update(request $request, Sight $sight)
     {
       $validator = Validator::make($request->all(), [
         'slug' => 'unique:articles,slug,'.$sight->id.'|unique:zones,slug,'.$sight->id.'
</code>```

But it allowed duplicate slug.

答:
According to the docs, the way to do this is:</p>

```<code>$validator = Validator::make($request->all(), [
     'slug' => [
         Rule::unique('articles')->ignore($sight->id, "slug"),
         Rule::unique('zones')->ignore($sight->id, "slug")
      ]
]);
</code>```

Body:
In laravel with unique check in multiple tables, I do this for create new field:

 //store function

'slug' => 'required|unique:articles,slug|unique:zones,slug

It works well.

but what can I do for update?

I test this:

public function update(request $request, Sight $sight)
     {
       $validator = Validator::make($request->all(), [
         'slug' => 'unique:articles,slug,'.$sight->id.'|unique:zones,slug,'.$sight->id.'

But it allowed duplicate slug.

Body:
According to the docs, the way to do this is:

$validator = Validator::make($request->all(), [
     'slug' => [
         Rule::unique('articles')->ignore($sight->id, "slug"),
         Rule::unique('zones')->ignore($sight->id, "slug")
      ]
]);


问:
How to update variable every full hour without refresh page by user?
Controller:

```<code>$number = rand(1, 100);
</code>```

View:

```<code><div id="lucky">
   Your lucky number: <?php echo $number ?>.
</div>
</code>```

How can I update the value for $number every hour without manually refreshing the page? I can use setInterval from JavaScript/jQuery, but I would like do it exactly at full hour (0:00, 1:00, 2:00 etc...). What is the best way to do this? I can use PHP, CRON, JS and JS frameworks...

答:
Here you go with a solution

var d = new Date();

var firstTrigger = 60000* (60 - d.getMinutes());

// This is for 1st Time Trigger
setTimeout(function(){
  console.log("1st time trigger", rand(1, 100));

  // This is continuous trigger every full hour
  setInterval(function(){
    console.log("Continuous trigger every hour", rand(1, 100));
  }, 3600000);
}, firstTrigger);```

In your case, instead of console.log you will trigger your code.

Hope this will help you.

Body:
Controller:

$number = rand(1, 100);

View:

   Your lucky number: <?php echo $number ?>.

How can I update the value for $number every hour without manually refreshing the page? I can use setInterval from JavaScript/jQuery, but I would like do it exactly at full hour (0:00, 1:00, 2:00 etc...). What is the best way to do this? I can use PHP, CRON, JS and JS frameworks...

Body:
Here you go with a solution

var d = new Date();

var firstTrigger = 60000* (60 - d.getMinutes());

// This is for 1st Time Trigger
setTimeout(function(){
  console.log("1st time trigger", rand(1, 100));

  // This is continuous trigger every full hour
  setInterval(function(){
    console.log("Continuous trigger every hour", rand(1, 100));
  }, 3600000);
}, firstTrigger);

In your case, instead of console.log you will trigger your code.

Hope this will help you.


问:
Creating a marimekko chart using Highcharts
I have a requirement to create a marmimekko chart using Highcharts (no other library).

A simple version of this type of chart can be found in the question - Highcharts Marimekko chart refresh

However, my requirement is more complex and I need to have a stacked-column like marimekko chart (similar to what fusion provides - http://www.fusioncharts.com/charts/marimekko-charts/).

The area chart approach may not be the best for this. Other options that I looked into include setting the pointWidth of the series (this doesn't help since I want different column widths for different points of the same series).

A partial implementation from Highcharts that I came across - http://highcharts.uservoice.com/forums/55896-general/suggestions/2303560-multi-dimensional-column-charts

Any ideas, suggestions or examples on how I can create such marimekko charts using Highcharts?

答:
I have build something similar. See here: http://jsfiddle.net/06jpczo9/4/

Main gist is this:

```<code>Highcharts.chart('container', {

    chart: {
        type: 'variwide'
    },

    title: {
        text: 'Verdeling DBCs type per specialist'
    },

    xAxis: {
        type: 'category',
    },

    yAxis: {
        max: 100,
    },

    legend: {
        enabled: true,
        reversed: true
    },
    plotOptions: {
        variwide: {
            stacking: 'normal',}},
    ...
</code>```

And then just add some series.

Body:
I have build something similar. See here: http://jsfiddle.net/06jpczo9/4/

Main gist is this:

Highcharts.chart('container', {

    chart: {
        type: 'variwide'
    },

    title: {
        text: 'Verdeling DBCs type per specialist'
    },

    xAxis: {
        type: 'category',
    },

    yAxis: {
        max: 100,
    },

    legend: {
        enabled: true,
        reversed: true
    },
    plotOptions: {
        variwide: {
            stacking: 'normal',}},
    ...

And then just add some series.


问:
python socket program : Cannot assign requested address
```<code>>> server.bind(('192.168.38.23',80))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 99] Cannot assign requested address
</code>```

Why is it not assigning this address?

答:
It's usually because you don't have permissions to do that. Usually ports below 1024 are restricted to root on Linux machines (privileged ports). For further context you can search for privileged ports or read questions like this.

I guess it works, if you change your line to:

```<code>server.bind(('192.168.38.23',8080))
</code>```

Body:
>> server.bind(('192.168.38.23',80))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 99] Cannot assign requested address

Why is it not assigning this address?

Body:
It's usually because you don't have permissions to do that. Usually ports below 1024 are restricted to root on Linux machines (privileged ports). For further context you can search for privileged ports or read questions like this.

I guess it works, if you change your line to:

server.bind(('192.168.38.23',8080))


问:
Constant 'soda1' inferred to have type '()', which may be unexpected
Just a small simple code. It does run, and prints out the right results, but I am getting the error: Constant 'soda1' inferred to have type '()', which may be unexpected. Not sure how to fix it.
Trying to code a simple program to output the price of a liter of soda. </p>

```<code>func sodaoffer(type: String, price: Double, size: Double, amount: Double = 1) {
    let priceL = price / (size * amount)
    print("\(type) costs \(priceL) per liter")
}

let soda1 = sodaoffer(type: "Cola", price: 15, size: 1.5)
let soda2 = sodaoffer(type: "Fanta", price: 50, size: 0.5, amount: 4)
let soda3 = sodaoffer(type: "Faxe Kondi", price: 25, size: 2)
</code>```

答:
You are assigning a function that returns () or Void (this means nothing) to a variable.

Try to return something:

```<code>func makeSodaOfferString(type: String, price: Double, size: Double, amount: Double = 1) -> String {
    let priceL = price / (size * amount)
    return "\(type) costs \(priceL) per liter)"
}

let sodaOffer1 = makeSodaOfferString(type: "Cola", price: 15, size: 1.5)
let sodaOffer2 = makeSodaOfferString(type: "Fanta", price: 50, size: 0.5, amount: 4)
let sodaOffer3 = makeSodaOfferString(type: "Faxe Kondi", price: 25, size: 2)

print(sodaOffer1)
print(sodaOffer2)
print(sodaOffer3)
</code>```

Body:
Just a small simple code. It does run, and prints out the right results, but I am getting the error: Constant 'soda1' inferred to have type '()', which may be unexpected. Not sure how to fix it.
Trying to code a simple program to output the price of a liter of soda.

func sodaoffer(type: String, price: Double, size: Double, amount: Double = 1) {
    let priceL = price / (size * amount)
    print("\(type) costs \(priceL) per liter")
}

let soda1 = sodaoffer(type: "Cola", price: 15, size: 1.5)
let soda2 = sodaoffer(type: "Fanta", price: 50, size: 0.5, amount: 4)
let soda3 = sodaoffer(type: "Faxe Kondi", price: 25, size: 2)

Body:
You are assigning a function that returns () or Void (this means nothing) to a variable.

Try to return something:

func makeSodaOfferString(type: String, price: Double, size: Double, amount: Double = 1) -> String {
    let priceL = price / (size * amount)
    return "\(type) costs \(priceL) per liter)"
}

let sodaOffer1 = makeSodaOfferString(type: "Cola", price: 15, size: 1.5)
let sodaOffer2 = makeSodaOfferString(type: "Fanta", price: 50, size: 0.5, amount: 4)
let sodaOffer3 = makeSodaOfferString(type: "Faxe Kondi", price: 25, size: 2)

print(sodaOffer1)
print(sodaOffer2)
print(sodaOffer3)


问:
Multitype stl map
Recently I have started using this JSON library. It has a nice method that allows to get any kind of data and the value will be cast automatically on return, eg:

When using the following JSON:

```<code>{
  "name": "Stackoverflow",
  "integer": 1234,
  "precise": 21.24
}
</code>```

We can get different return types using this method:

```<code>json config = json::parse(buf);

std::cout << typeid(config.value("integer", 0)).name() << std::endl; // Return: integer
std::cout << typeid(config.value("name", "Default Name")).name() << std::endl; // Return: stl basic string
std::cout << typeid(config.value("precise", 0.0)).name() << std::endl; // Return: double
</code>```

As you can see, it's automatically casting a valid data types for our keys.

Now, I would like to store these different type values in a std::map container. However, stl map do support only one data type:

```<code>enum TestEnum {
   TEST_MY_INTEGER_VALUE,
   TEST_NAME_OF_SOMETHING,
   TEST_PRECISE_VALUE,
}

std::map<TestEnum, (what I'm supposed to write here?)> values;
</code>```

I did my research on this and it turns out that I could achieve this using Boost.Variant class, however my project is very small and I'd rather not use any frameworks for it. Only the pure C++11 methods.

So, how could I store different return types that are being returned by the value() method into the map container?

答:
If you able to use C++17, than you can use std::variant.

If using C++17 is impossible for you, than it is possible to use any small library instead Boost, for example this implementation of std::variant for C++11/C++14.

And you can implement your own class type with same functionality of std::variant, but I strongly do not recommend it, because it is difficult to provide exception safety and another non-obviously cases.

For your simple case with only several types (int, string, bool, float) you could implement a several types JsonInt, JsonString and inherite it from common abstract class JsonType.

Title: Multitype stl map

Body:
Recently I have started using this JSON library. It has a nice method that allows to get any kind of data and the value will be cast automatically on return, eg:

When using the following JSON:

{
  "name": "Stackoverflow",
  "integer": 1234,
  "precise": 21.24
}

We can get different return types using this method:

json config = json::parse(buf);

std::cout << typeid(config.value("integer", 0)).name() << std::endl; // Return: integer
std::cout << typeid(config.value("name", "Default Name")).name() << std::endl; // Return: stl basic string
std::cout << typeid(config.value("precise", 0.0)).name() << std::endl; // Return: double

As you can see, it's automatically casting a valid data types for our keys.

Now, I would like to store these different type values in a std::map container. However, stl map do support only one data type:

enum TestEnum {
   TEST_MY_INTEGER_VALUE,
   TEST_NAME_OF_SOMETHING,
   TEST_PRECISE_VALUE,
}

std::map<TestEnum, (what I'm supposed to write here?)> values;

I did my research on this and it turns out that I could achieve this using Boost.Variant class, however my project is very small and I'd rather not use any frameworks for it. Only the pure C++11 methods.

So, how could I store different return types that are being returned by the value() method into the map container?


问:
Same workbook in two windows; Sub changes which tab is viewed
I have a workbook that uses a macro to add extra lines, as the workbook has to be heavily locked down to protect it from users. I'm using Excel 2010.

However, if I have two windows open looking at different sheets of the workbook, running the macro makes both windows shift to the sheet in which I added the lines(s), which is disruptive to workflow.

My guess is that this is down to using .PasteSpecial but I am unsure of how else to do it, as the lines to be added include formatting and formulae so .value = .value won't work.

The sub is called from one of four other subs; one to add a single row, one to add multiple rows,  one to add a special header row, and one that adds costs rows (done by sending a negative number of rows). The code is:

```<code>Sub InsertAnyRows(NumRows As Integer)

    Dim thisWS As Worksheet
    Set thisWS = ActiveSheet
    If Not (InRange(ActiveCell, thisWS.Range("QuoteLines")) Or InRange(ActiveCell, thisWS.Range("LabourLines")) Or InRange(ActiveCell, thisWS.Range("OptionsLines"))) Then Exit Sub

    Application.ScreenUpdating = False
    Application.CutCopyMode = False

    Dim RowLoc As Range
    Set RowLoc = thisWS.Cells(Selection.Rows(1).Row, 1)

    Select Case NumRows

        Case Is < 0 ' must be inserting costs rows
            NumRows = NumRows * -1
            RowLoc.Resize(NumRows).Offset(1, 0).EntireRow.Insert
            thisWS.Range("CostsBlankRow").Copy
            RowLoc.Resize(NumRows).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

        Case 0 ' must be inserting a header row
            RowLoc.Offset(1, 0).EntireRow.Insert
            thisWS.Range("TabHeaderRow").Copy
            RowLoc.Offset(1, 0).PasteSpecial Paste:=xlPasteAll

        Case Else ' must be inserting normal rows
            RowLoc.Resize(NumRows).Offset(1, 0).EntireRow.Insert
            thisWS.Range("TabBlankRow").Copy
            RowLoc.Resize(NumRows).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

    End Select

    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub
</code>```

答:
This is what I came up with, so that it'll deal with an arbitrary number of open windows; it also reselects whatever the selection was before running the macro (which looks neater to me). Thank you for the pointers!</p>

```<code>Sub InsertAnyRows(NumRows As Integer)

    Dim thisWS As Worksheet
    Set thisWS = ActiveSheet
    If Not (InRange(ActiveCell, thisWS.Range("QuoteLines")) Or InRange(ActiveCell, thisWS.Range("LabourLines")) Or InRange(ActiveCell, thisWS.Range("OptionsLines"))) Then Exit Sub

    Application.ScreenUpdating = False
    Application.CutCopyMode = False

    Dim NumWindows As Integer
    NumWindows = ThisWorkbook.Windows.Count

    If NumWindows > 1 Then

        Dim Windows() As Window
        Dim WindowsSheets() As Worksheet

        ReDim Windows(NumWindows)
        ReDim WindowsSheets(NumWindows)

        Dim i As Integer

        For i = 1 To NumWindows
            Set Windows(i) = ThisWorkbook.Windows(i)
            Set WindowsSheets(i) = Windows(i).ActiveSheet
        Next i

    End If

    Dim RowLoc As Range, EndLoc As Range, SelRange As Range
    Set SelRange = Selection
    Set RowLoc = thisWS.Cells(Selection.Rows(1).Row, 1)

    Select Case NumRows

        Case Is < 0 ' must be inserting costs rows
            NumRows = NumRows * -1
            RowLoc.Resize(NumRows).Offset(1, 0).EntireRow.Insert
            thisWS.Range("CostsBlankRow").Copy
            RowLoc.Resize(NumRows).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

        Case 0 ' must be inserting a header row
            RowLoc.Offset(1, 0).EntireRow.Insert
            thisWS.Range("TabHeaderRow").Copy
            RowLoc.Offset(1, 0).PasteSpecial Paste:=xlPasteAll

        Case Else ' must be inserting normal rows
            RowLoc.Resize(NumRows).Offset(1, 0).EntireRow.Insert
            thisWS.Range("TabBlankRow").Copy
            RowLoc.Resize(NumRows).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

    End Select

    SelRange.Select

    If NumWindows > 1 Then

        For i = NumWindows To 1 Step -1
            Windows(i).Activate
            WindowsSheets(i).Activate
        Next i

    End If

    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub
</code>```

Body:
I have a workbook that uses a macro to add extra lines, as the workbook has to be heavily locked down to protect it from users. I'm using Excel 2010.

However, if I have two windows open looking at different sheets of the workbook, running the macro makes both windows shift to the sheet in which I added the lines(s), which is disruptive to workflow.

My guess is that this is down to using .PasteSpecial but I am unsure of how else to do it, as the lines to be added include formatting and formulae so .value = .value won't work.

The sub is called from one of four other subs; one to add a single row, one to add multiple rows,  one to add a special header row, and one that adds costs rows (done by sending a negative number of rows). The code is:

Sub InsertAnyRows(NumRows As Integer)

    Dim thisWS As Worksheet
    Set thisWS = ActiveSheet
    If Not (InRange(ActiveCell, thisWS.Range("QuoteLines")) Or InRange(ActiveCell, thisWS.Range("LabourLines")) Or InRange(ActiveCell, thisWS.Range("OptionsLines"))) Then Exit Sub

    Application.ScreenUpdating = False
    Application.CutCopyMode = False

    Dim RowLoc As Range
    Set RowLoc = thisWS.Cells(Selection.Rows(1).Row, 1)

    Select Case NumRows

        Case Is < 0 ' must be inserting costs rows
            NumRows = NumRows * -1
            RowLoc.Resize(NumRows).Offset(1, 0).EntireRow.Insert
            thisWS.Range("CostsBlankRow").Copy
            RowLoc.Resize(NumRows).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

        Case 0 ' must be inserting a header row
            RowLoc.Offset(1, 0).EntireRow.Insert
            thisWS.Range("TabHeaderRow").Copy
            RowLoc.Offset(1, 0).PasteSpecial Paste:=xlPasteAll

        Case Else ' must be inserting normal rows
            RowLoc.Resize(NumRows).Offset(1, 0).EntireRow.Insert
            thisWS.Range("TabBlankRow").Copy
            RowLoc.Resize(NumRows).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

    End Select

    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub

Body:
This is what I came up with, so that it'll deal with an arbitrary number of open windows; it also reselects whatever the selection was before running the macro (which looks neater to me). Thank you for the pointers!

Sub InsertAnyRows(NumRows As Integer)

    Dim thisWS As Worksheet
    Set thisWS = ActiveSheet
    If Not (InRange(ActiveCell, thisWS.Range("QuoteLines")) Or InRange(ActiveCell, thisWS.Range("LabourLines")) Or InRange(ActiveCell, thisWS.Range("OptionsLines"))) Then Exit Sub

    Application.ScreenUpdating = False
    Application.CutCopyMode = False

    Dim NumWindows As Integer
    NumWindows = ThisWorkbook.Windows.Count

    If NumWindows > 1 Then

        Dim Windows() As Window
        Dim WindowsSheets() As Worksheet

        ReDim Windows(NumWindows)
        ReDim WindowsSheets(NumWindows)

        Dim i As Integer

        For i = 1 To NumWindows
            Set Windows(i) = ThisWorkbook.Windows(i)
            Set WindowsSheets(i) = Windows(i).ActiveSheet
        Next i

    End If

    Dim RowLoc As Range, EndLoc As Range, SelRange As Range
    Set SelRange = Selection
    Set RowLoc = thisWS.Cells(Selection.Rows(1).Row, 1)

    Select Case NumRows

        Case Is < 0 ' must be inserting costs rows
            NumRows = NumRows * -1
            RowLoc.Resize(NumRows).Offset(1, 0).EntireRow.Insert
            thisWS.Range("CostsBlankRow").Copy
            RowLoc.Resize(NumRows).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

        Case 0 ' must be inserting a header row
            RowLoc.Offset(1, 0).EntireRow.Insert
            thisWS.Range("TabHeaderRow").Copy
            RowLoc.Offset(1, 0).PasteSpecial Paste:=xlPasteAll

        Case Else ' must be inserting normal rows
            RowLoc.Resize(NumRows).Offset(1, 0).EntireRow.Insert
            thisWS.Range("TabBlankRow").Copy
            RowLoc.Resize(NumRows).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

    End Select

    SelRange.Select

    If NumWindows > 1 Then

        For i = NumWindows To 1 Step -1
            Windows(i).Activate
            WindowsSheets(i).Activate
        Next i

    End If

    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub


问:
unable to retrieve $_POST variable in php
After searching a lot and working endlessly on this problem I decided to post here.
I am passing a formdata with a filename variable to php using ajax. I then try to access the variable name so I can pass it to a second php that loads the name into the database. I am unable to pass or echo the data in php though. Can anyone help?

My javascript

```<code>function uploadFile() {
  var input = document.getElementById("picture");
  file = input.files[0];
  newFileName = elementHandle[9].val() + elementHandle[10].val() + elementHandle[11].val();
  console.log(newFileName);
  if (file != undefined) {
    formData = new FormData();

    if (!!file.type.match(/image.*/)) {
      formData.append("newFileName1", newFileName);
      $.ajax({
        url: "upload_file.php",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function(data) {}
      });
    } else {
      alert('Not a valid image!');
    }
  } else {
    alert('Input something!');
  }
}
</code>```

My php

```<code><?php
    $dir = "im_ges/";
    $file_name = $dir. $_REQUEST["newFileName1"].".jpg";
    echo $file_name;
    move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_POST ['newFileName1'].".jpg");
?>
</code>```

答:
If you get the file name in your custom php controller the you can use

```<code>$target_dir = "uploads/";

$filename = "phonenumber.png";//Set here the new file name which you passed through ajax

$target_file = $target_dir .$filename;
 // test here the file is moved or  not,
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// if moved the file then update db with the $filename write code here
then update db with the $filename
}
</code>```

or i changed the some code in above mentioed and add a text filed to enter a phone number and the selected file moved to the taget with the value enterd in the
text field with name phone can you check is it usefull for you .

form.html

```<code><html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'post',
            url: 'post.php',
            data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
            contentType: false,       // The content type used when sending data to the server.
            cache: false,             // To unable request pages to be cached
            processData:false,        // To send DOMDocument or non processed data file it is set to false
            success: function (responce) {
             alert(responce);
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form  action="" method="post" enctype="multipart/form-data"><form id="uploadimage" action="" method="post" enctype="multipart/form-data">
      <input name="name" value="First Name"><br>
      <input name="phone" value=""><br> <!-- new field -->
      <input name="file" type ="file" ><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>
</code>```

post.php

```<code>    <?php
    echo "Name Value : ".$_POST["name"]."\n\n";
    echo "\n File Details\n";
    print_r($_FILES);

    $target_dir = "uploads/";

    $uploadOk = 1;
    $filename = $_FILES['image']['name'];

    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    $target_file = $target_dir . $_POST["phone"].$ext; // here we change the file name before uploads
             // test here the file is moved or  not,
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// if moved the file then update db with the $filename write code here
        }
    ?>
</code>```

create a folder in the root with name "uploads" and give full permison

Body:
After searching a lot and working endlessly on this problem I decided to post here.
I am passing a formdata with a filename variable to php using ajax. I then try to access the variable name so I can pass it to a second php that loads the name into the database. I am unable to pass or echo the data in php though. Can anyone help?

My javascript

function uploadFile() {
  var input = document.getElementById("picture");
  file = input.files[0];
  newFileName = elementHandle[9].val() + elementHandle[10].val() + elementHandle[11].val();
  console.log(newFileName);
  if (file != undefined) {
    formData = new FormData();

    if (!!file.type.match(/image.*/)) {
      formData.append("newFileName1", newFileName);
      $.ajax({
        url: "upload_file.php",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function(data) {}
      });
    } else {
      alert('Not a valid image!');
    }
  } else {
    alert('Input something!');
  }
}

My php

<?php
    $dir = "im_ges/";
    $file_name = $dir. $_REQUEST["newFileName1"].".jpg";
    echo $file_name;
    move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_POST ['newFileName1'].".jpg");
?>

Body:
If you get the file name in your custom php controller the you can use

$target_dir = "uploads/";

$filename = "phonenumber.png";//Set here the new file name which you passed through ajax

$target_file = $target_dir .$filename;
 // test here the file is moved or  not,
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// if moved the file then update db with the $filename write code here
then update db with the $filename
}

or i changed the some code in above mentioed and add a text filed to enter a phone number and the selected file moved to the taget with the value enterd in the
text field with name phone can you check is it usefull for you .

form.html

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'post',
            url: 'post.php',
            data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
            contentType: false,       // The content type used when sending data to the server.
            cache: false,             // To unable request pages to be cached
            processData:false,        // To send DOMDocument or non processed data file it is set to false
            success: function (responce) {
             alert(responce);
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form  action="" method="post" enctype="multipart/form-data"><form id="uploadimage" action="" method="post" enctype="multipart/form-data">
      <input name="name" value="First Name"><br>
      <input name="phone" value=""><br> <!-- new field -->
      <input name="file" type ="file" ><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

post.php

    <?php
    echo "Name Value : ".$_POST["name"]."\n\n";
    echo "\n File Details\n";
    print_r($_FILES);

    $target_dir = "uploads/";

    $uploadOk = 1;
    $filename = $_FILES['image']['name'];

    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    $target_file = $target_dir . $_POST["phone"].$ext; // here we change the file name before uploads
             // test here the file is moved or  not,
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// if moved the file then update db with the $filename write code here
        }
    ?>

create a folder in the root with name "uploads" and give full permison


问:
What are some best practices for optimizing multiple column LIKE SQL queries?
I have a search query that I'm inheriting and attempting to optimize. I am curious to hear if anyone has any best practices and recommendations for such.  The production server is still SQL Server 2000 also.

The query is an advanced customer search stored procedure that accepts 5 different search criteria parameters (i.e. first name, last name, address, phone, etc.) to search a multi-million record table.  There are indexes on all joined columns and columns in the WHERE clause.  In addition, the initial query dumps the records into a table variable for paging capacity.

```<code>INSERT INTO   @tempCustTable (CustomerID, FirstName, LastName, City, StateProvince, Zip, PhoneNumber)
SELECT  DISTINCT cu.CustomerID, cu.FirstName, cu.LastName, a.City,
a.StateProvince, a.Zip, p.PhoneNumber
FROM Customer cu WITH(NOLOCK)
LEFT OUTER JOIN Address a WITH(NOLOCK) ON cu.CustomerID = a.CustomerID
LEFT OUTER JOIN Phone p WITH(NOLOCK) ON cu.CustomerID = p.CustomerID
WHERE  (cu.LastName = @LastName OR cu.LastName LIKE @LastName + '%')
AND (@FirstName IS NULL OR cu.FirstName = @FirstName OR cu.FirstName LIKE @FirstName + '%')
AND (@StateProvince = '' OR a.StateProvince LIKE @StateProvince)
AND (@City = '' OR a.City LIKE @City + '%')
AND (@Zip = '' OR a.Zip = @Zip OR a.Zip LIKE @Zip + '%')
ORDER BY cu.LastName, cu.FirstName
</code>```

Does anyone have any recommendations on how I could improve the performance of the query?

答:
isn't this whole line

```<code>AND (@Zip = '' OR a.Zip = @Zip OR a.Zip LIKE @Zip + '%')
</code>```

the same as this

```<code>AND (a.Zip LIKE @Zip + '%')
</code>```

for sure

```<code>AND (a.Zip LIKE @Zip + '%')
</code>```

it is the same as

```<code>a.Zip = @Zip OR a.Zip LIKE @Zip + '%'
</code>```

OwnerDisplayName: JamesEggers

ContentLicense: CC BY-SA 2.5

Body:
I have a search query that I'm inheriting and attempting to optimize. I am curious to hear if anyone has any best practices and recommendations for such.  The production server is still SQL Server 2000 also.

The query is an advanced customer search stored procedure that accepts 5 different search criteria parameters (i.e. first name, last name, address, phone, etc.) to search a multi-million record table.  There are indexes on all joined columns and columns in the WHERE clause.  In addition, the initial query dumps the records into a table variable for paging capacity.

INSERT INTO   @tempCustTable (CustomerID, FirstName, LastName, City, StateProvince, Zip, PhoneNumber)
SELECT  DISTINCT cu.CustomerID, cu.FirstName, cu.LastName, a.City,
a.StateProvince, a.Zip, p.PhoneNumber
FROM Customer cu WITH(NOLOCK)
LEFT OUTER JOIN Address a WITH(NOLOCK) ON cu.CustomerID = a.CustomerID
LEFT OUTER JOIN Phone p WITH(NOLOCK) ON cu.CustomerID = p.CustomerID
WHERE  (cu.LastName = @LastName OR cu.LastName LIKE @LastName + '%')
AND (@FirstName IS NULL OR cu.FirstName = @FirstName OR cu.FirstName LIKE @FirstName + '%')
AND (@StateProvince = '' OR a.StateProvince LIKE @StateProvince)
AND (@City = '' OR a.City LIKE @City + '%')
AND (@Zip = '' OR a.Zip = @Zip OR a.Zip LIKE @Zip + '%')
ORDER BY cu.LastName, cu.FirstName

Does anyone have any recommendations on how I could improve the performance of the query?

Body:
isn't this whole line

AND (@Zip = '' OR a.Zip = @Zip OR a.Zip LIKE @Zip + '%')

the same as this

AND (a.Zip LIKE @Zip + '%')

for sure

AND (a.Zip LIKE @Zip + '%')

it is the same as

a.Zip = @Zip OR a.Zip LIKE @Zip + '%'

OwnerDisplayName: SQLMenace


问:
Loading a native library in an Android JUnit test
I've generated a native library using ndk-build which I'm able to load and use with in my Android application. However, I want to write some tests against this part of my app.

When calling the native function in my tests, I recieve this exception message:

```<code>java.lang.UnsatisfiedLinkError: no process in java.library.path
</code>```

...where process is my native library to import, named libprocess.so.

I'm using Roboelectric for my tests, and running this particular one with the RobolectricTestRunner, if it makes a difference.

How can I get my test project to 'see' the native library?

Edit:
I'm loading the library in my app like so:

```<code>static {
    System.loadLibrary("process");
}
public static native int[] process(double[][] data);
</code>```

calling Process.process(array) works fine in the app (the library is loaded), but fails when run from the tests with the exception given above.

Edit 2:
If I set -Djava.library.path="<the directory of libprocess.so>" as a VM argument, then:

```<code>System.out.println(System.getProperty("java.library.path"));
</code>```

does show the path I set, but I still get the same exception. I'm setting the directory as:

```<code><project-name>/libs/x86
</code>```

...but as an absolute path.

答:
For anyone still looking, blork had the right idea - you need to compile your native libraries for your 'native' platform (Windows, Linux, Mac). The Android NDK builds libraries for the Android platform (.so files - might also work on Linux), and this is why there are no issues running in Activity Test Cases (because it loads up an Android instance).

To get the low-level, hella fast JUnit tests running, you need to support your JVM. On Windows, this might be building DLLs, on Apple, it's building dylibs (assuming shared libraries).

I've just completed a sample in my android-ndk-swig-example repo (https://github.com/sureshjoshi/android-ndk-swig-example/issues/9).

Basically, in my CMakeLists, I added an Apple caveat:

```<code># Need to create the .dylib and .jnilib files in order to run JUnit tests
if (APPLE)
    # Ensure jni.h is found
    find_package(JNI REQUIRED)
    include_directories(${JAVA_INCLUDE_PATH})
</code>```

And then I make sure Gradle runs for unit tests, but using the Mac build system (not NDK).

```<code>def osxDir = projectDir.absolutePath + '/.externalNativeBuild/cmake/debug/osx/'

task createBuildDir() {
    def folder = new File(osxDir)
    if (!folder.exists()) {
        folder.mkdirs()
    }
}

task runCMake(type: Exec) {
    dependsOn createBuildDir
    workingDir osxDir // Jump to future build directory
    commandLine '/usr/local/bin/cmake' // Path from HomeBrew installation
    args '../../../../' // Relative path for out-of-source builds
}

task runMake(type: Exec) {
    dependsOn runCMake
    workingDir osxDir
    commandLine 'make'
}

 project.afterEvaluate {
    // Not sure how much of a hack this is - but it allows CMake/SWIG to run before Android Studio
    // complains about missing generated files
    // TODO: Probably need a release hook too?
    javaPreCompileDebug.dependsOn externalNativeBuildDebug
    if (org.gradle.internal.os.OperatingSystem.current().isMacOsX()) {
        javaPreCompileDebugAndroidTest.dependsOn runMake
    }
 }
</code>```

CAVEAT TIME!!!

When you use this method, you're technically not testing the NDK-generated libs. You're testing the same code, but compiled using a different compiler (msvc, xcode, gcc, clang, whatever you use on the host).

What this means practically, is that most of the test results will be valid - except when you run into problems caused by each compiler's quirks, or STL implementations, etc... This isn't as bad as it was 10+ years ago, but you can't say with 100% certainty that the results of JUnit testing with host libs is identical to the Android libs. You can say that it's reasonably close, though.

Then again, unless you're running your native unit tests using the Android NDK for each supported architecture, you also can't say anything about certainty either... So take what you will from it.

An overkill approach (but really cool if automated) would be to write your native unit tests however you do them (Google Test, Catch, etc), then compile and run your native libs and unit tests with the Android NDK per each architecture. This provides your C/C++ coverage across your potential target architectures.

From here, you could use the aforementioned host libs with JUnit to rapidly unit test your JNI layer interacting with your native lib. In your CI system, you should still probably run these same unit tests - but as Android Instrumentation tests (or something else that runs an emulated Android environment).

As with everything, wherever you have an interface, you can create mocks - but at some point, you'll need system/functional/integration tests too.

Update:

More comprehensive explanation of above in a blog article (http://www.sureshjoshi.com/mobile/android-junit-native-libraries/)

Body:
I've generated a native library using ndk-build which I'm able to load and use with in my Android application. However, I want to write some tests against this part of my app.

When calling the native function in my tests, I recieve this exception message:

java.lang.UnsatisfiedLinkError: no process in java.library.path

...where process is my native library to import, named libprocess.so.

I'm using Roboelectric for my tests, and running this particular one with the RobolectricTestRunner, if it makes a difference.

How can I get my test project to 'see' the native library?

Edit:
I'm loading the library in my app like so:

static {
    System.loadLibrary("process");
}
public static native int[] process(double[][] data);

calling Process.process(array) works fine in the app (the library is loaded), but fails when run from the tests with the exception given above.

Edit 2:
If I set -Djava.library.path="<the directory of libprocess.so>" as a VM argument, then:

System.out.println(System.getProperty("java.library.path"));

does show the path I set, but I still get the same exception. I'm setting the directory as:

<project-name>/libs/x86

...but as an absolute path.

Body:
For anyone still looking, blork had the right idea - you need to compile your native libraries for your 'native' platform (Windows, Linux, Mac). The Android NDK builds libraries for the Android platform (.so files - might also work on Linux), and this is why there are no issues running in Activity Test Cases (because it loads up an Android instance).

To get the low-level, hella fast JUnit tests running, you need to support your JVM. On Windows, this might be building DLLs, on Apple, it's building dylibs (assuming shared libraries).

I've just completed a sample in my android-ndk-swig-example repo (https://github.com/sureshjoshi/android-ndk-swig-example/issues/9).

Basically, in my CMakeLists, I added an Apple caveat:

# Need to create the .dylib and .jnilib files in order to run JUnit tests
if (APPLE)
    # Ensure jni.h is found
    find_package(JNI REQUIRED)
    include_directories(${JAVA_INCLUDE_PATH})

And then I make sure Gradle runs for unit tests, but using the Mac build system (not NDK).

def osxDir = projectDir.absolutePath + '/.externalNativeBuild/cmake/debug/osx/'

task createBuildDir() {
    def folder = new File(osxDir)
    if (!folder.exists()) {
        folder.mkdirs()
    }
}

task runCMake(type: Exec) {
    dependsOn createBuildDir
    workingDir osxDir // Jump to future build directory
    commandLine '/usr/local/bin/cmake' // Path from HomeBrew installation
    args '../../../../' // Relative path for out-of-source builds
}

task runMake(type: Exec) {
    dependsOn runCMake
    workingDir osxDir
    commandLine 'make'
}

 project.afterEvaluate {
    // Not sure how much of a hack this is - but it allows CMake/SWIG to run before Android Studio
    // complains about missing generated files
    // TODO: Probably need a release hook too?
    javaPreCompileDebug.dependsOn externalNativeBuildDebug
    if (org.gradle.internal.os.OperatingSystem.current().isMacOsX()) {
        javaPreCompileDebugAndroidTest.dependsOn runMake
    }
 }

CAVEAT TIME!!!

When you use this method, you're technically not testing the NDK-generated libs. You're testing the same code, but compiled using a different compiler (msvc, xcode, gcc, clang, whatever you use on the host).

What this means practically, is that most of the test results will be valid - except when you run into problems caused by each compiler's quirks, or STL implementations, etc... This isn't as bad as it was 10+ years ago, but you can't say with 100% certainty that the results of JUnit testing with host libs is identical to the Android libs. You can say that it's reasonably close, though.

Then again, unless you're running your native unit tests using the Android NDK for each supported architecture, you also can't say anything about certainty either... So take what you will from it.

An overkill approach (but really cool if automated) would be to write your native unit tests however you do them (Google Test, Catch, etc), then compile and run your native libs and unit tests with the Android NDK per each architecture. This provides your C/C++ coverage across your potential target architectures.

From here, you could use the aforementioned host libs with JUnit to rapidly unit test your JNI layer interacting with your native lib. In your CI system, you should still probably run these same unit tests - but as Android Instrumentation tests (or something else that runs an emulated Android environment).

As with everything, wherever you have an interface, you can create mocks - but at some point, you'll need system/functional/integration tests too.

Update:

More comprehensive explanation of above in a blog article (http://www.sureshjoshi.com/mobile/android-junit-native-libraries/)


问:
Actionscript - Obtain the name of the current function
I want to get the name of a function from inside that function. e.g.:

```<code>function blah() {
    //I want to get the string "blah" here, from the function's name
}
</code>```

Or at least the Function object?

答:
I just did it with a stack trace, which is what the Flash Player debugger shows when an unhandled error is thrown.  Here's my implementation:

```<code>function blah()
{
    var e:Error = new Error();
    var s:String = e.getStackTrace();
    var functionName:String = s.slice(s.indexOf('/')+1, s.indexOf('('));
    trace(functionName); //blah
}
</code>```

You'll probably need to make the parsing of the string a bit fancier, if you want to make this a separate function.  But the function name is definitely in the stack trace.

Edit: Important Caveat

The AS3 Lang Ref says that the getStackTrace method only works in the Debugger versions of Flash Player/AIR, and will return null otherwise.  So this is definitely not a deployable solution.  Sorry.

Body:
I want to get the name of a function from inside that function. e.g.:

function blah() {
    //I want to get the string "blah" here, from the function's name
}

Or at least the Function object?

Body:
I just did it with a stack trace, which is what the Flash Player debugger shows when an unhandled error is thrown.  Here's my implementation:

function blah()
{
    var e:Error = new Error();
    var s:String = e.getStackTrace();
    var functionName:String = s.slice(s.indexOf('/')+1, s.indexOf('('));
    trace(functionName); //blah
}

You'll probably need to make the parsing of the string a bit fancier, if you want to make this a separate function.  But the function name is definitely in the stack trace.

Edit: Important Caveat

The AS3 Lang Ref says that the getStackTrace method only works in the Debugger versions of Flash Player/AIR, and will return null otherwise.  So this is definitely not a deployable solution.  Sorry.


问:
How to search phone numbers, ignoring dashes, bracets and spaces in MySql or PostgreSql?
In database(users table) I have phone numbers in this format:

```<code>(619) 745-0863
(619) 745-0864
(619) 745-0865
</code>```

I want to search by phone numbers, ignoring spaces, dashes and bracket, this means if I search by this "6197450863" I want in results first row which have this phone number "(619) 745-0863".

I have code that works :

```<code>SELECT * FROM users where
REPLACE(REPLACE(REPLACE(REPLACE(phone, '-', ''), ')', ''), '(', ''), ' ', '')
LIKE '6197450863'
</code>```

But this is slow and awkward. Is there any way to do this better ? I currently use MySQL but I will switch to PostgreSQL if there is a better way.

I know that I can achieve this with search engines like Elastic Search and I know that someone will tell me use Elastic Search even I say explicitly that this question is about how to achieve this with mysql or postgreSql :)
If there is no better way, just say so, don't tell use Elastic search or something similar.

This question is actually about how to use full text search in RDBMS instead of replacing text.

答:
In Postgres probably the most efficient way would be to use translate().

```<code>with users(phone) as (
values
    ('(619) 745-0863'),
    ('(619) 745-0864'),
    ('(619) 745-0865')
)
select *
from users
where translate(phone, '() -', '') = '6197450863'

     phone
----------------
 (619) 745-0863
(1 row)
</code>```

Body:
In database(users table) I have phone numbers in this format:

(619) 745-0863
(619) 745-0864
(619) 745-0865

I want to search by phone numbers, ignoring spaces, dashes and bracket, this means if I search by this "6197450863" I want in results first row which have this phone number "(619) 745-0863".

I have code that works :

SELECT * FROM users where
REPLACE(REPLACE(REPLACE(REPLACE(phone, '-', ''), ')', ''), '(', ''), ' ', '')
LIKE '6197450863'

But this is slow and awkward. Is there any way to do this better ? I currently use MySQL but I will switch to PostgreSQL if there is a better way.

I know that I can achieve this with search engines like Elastic Search and I know that someone will tell me use Elastic Search even I say explicitly that this question is about how to achieve this with mysql or postgreSql :)
If there is no better way, just say so, don't tell use Elastic search or something similar.

This question is actually about how to use full text search in RDBMS instead of replacing text.

Body:
In Postgres probably the most efficient way would be to use translate().

with users(phone) as (
values
    ('(619) 745-0863'),
    ('(619) 745-0864'),
    ('(619) 745-0865')
)
select *
from users
where translate(phone, '() -', '') = '6197450863'

     phone
----------------
 (619) 745-0863
(1 row)


问:
Alarm everyday at 5AM morning
I am working on an android application where I need to trigger an alarm every morning at 5 am. I have already used the concept of Intent(below is the code) and putting AlarmManager in the Service. But I didnt get the problem solution from both implementations. I am just looking for a perfect solution for this. If I add a reminder to the calendar for 1 month once the application is opened for the first time I guess that might work. But if there is any better solution for this, then please provide. It should trigger an alarm at 5 AM every day no matter what. How can I achieve this?

```<code>alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent alarmIntent = new Intent(this, MyStartServiceReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 5);
        calendar.set(Calendar.MINUTE, 5);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM, Calendar.AM);
        if (System.currentTimeMillis() > calendar.getTimeInMillis()) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        alarmManager.cancel(pendingIntent);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
</code>```

答:
you need to implement services:
https://developer.android.com/guide/components/services.html

Moreover, you may find many tutorials on implementing services in app

Title: Alarm everyday at 5AM morning

Body:
I am working on an android application where I need to trigger an alarm every morning at 5 am. I have already used the concept of Intent(below is the code) and putting AlarmManager in the Service. But I didnt get the problem solution from both implementations. I am just looking for a perfect solution for this. If I add a reminder to the calendar for 1 month once the application is opened for the first time I guess that might work. But if there is any better solution for this, then please provide. It should trigger an alarm at 5 AM every day no matter what. How can I achieve this?

alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent alarmIntent = new Intent(this, MyStartServiceReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 5);
        calendar.set(Calendar.MINUTE, 5);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM, Calendar.AM);
        if (System.currentTimeMillis() > calendar.getTimeInMillis()) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        alarmManager.cancel(pendingIntent);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);


问:
How to set .apk file name and package in build.gradle? Android Gradle plugin 3.0
According to my CI requirements I'm trying to achieve two things:

set apk file name in format: .apk

set folder for generated .apk file: app/build/outputs/apk/myBuild.apk

I used android gradle plugin 2.3 and got following script to manage task above (it worked correctly for gradle plugin 2.3):

```<code>applicationVariants.all {
        variant ->
            variant.outputs.each { output ->
                output.outputFile = new File(
                        output.outputFile.parent,
                        variant.productFlavors.get(0).name + variant.buildType.name + ".apk")
            }
</code>```

Now I got the following code (according to latest updates in android gradle plugin 3.0):

```<code>applicationVariants.all { variant ->
        variant.outputs.all { output ->
            logger.debug("fileNameParent", output.outputFile.parent)
            outputFileName = new File(
                    "apk/",
                    outputFileName.replace(".apk", "MyBuild.apk"))
        }
</code>```

And got following structure (see picture):

P.S. I read Android Gradle Plugin migration guide, but it doesn't help me to achieve my goal :(

答:
this is the correct code:

```<code>applicationVariants.all { variant ->
    variant.outputs.all{
        outputFileName = outputFileName.replace("app-${variant.buildType.name}.apk", ${variant.productFlavors.get(0).name} + "-" + ${variant.buildType.name} + ".apk")
    }
}
</code>```

please keep in mind that you have to put this code in build.gradle app file on android{ } section, and not on android{ buildTypes{ debug/release{ }}} sections

This will return for:

debug build:

app-debug.apk >> YOUR_PRODUCT_NAME-debug.apk

release build:

app-release.apk >> YOUR_PRODUCT_NAME-release.apk

don't use outputFileName = new File() or you have the problem of variant API manipulation

Body:
According to my CI requirements I'm trying to achieve two things:

set apk file name in format: .apk

set folder for generated .apk file: app/build/outputs/apk/myBuild.apk

I used android gradle plugin 2.3 and got following script to manage task above (it worked correctly for gradle plugin 2.3):

applicationVariants.all {
        variant ->
            variant.outputs.each { output ->
                output.outputFile = new File(
                        output.outputFile.parent,
                        variant.productFlavors.get(0).name + variant.buildType.name + ".apk")
            }

Now I got the following code (according to latest updates in android gradle plugin 3.0):

applicationVariants.all { variant ->
        variant.outputs.all { output ->
            logger.debug("fileNameParent", output.outputFile.parent)
            outputFileName = new File(
                    "apk/",
                    outputFileName.replace(".apk", "MyBuild.apk"))
        }

And got following structure (see picture):

P.S. I read Android Gradle Plugin migration guide, but it doesn't help me to achieve my goal :(

Body:
this is the correct code:

applicationVariants.all { variant ->
    variant.outputs.all{
        outputFileName = outputFileName.replace("app-${variant.buildType.name}.apk", ${variant.productFlavors.get(0).name} + "-" + ${variant.buildType.name} + ".apk")
    }
}

please keep in mind that you have to put this code in build.gradle app file on android{ } section, and not on android{ buildTypes{ debug/release{ }}} sections

This will return for:

debug build:

app-debug.apk >> YOUR_PRODUCT_NAME-debug.apk

release build:

app-release.apk >> YOUR_PRODUCT_NAME-release.apk

don't use outputFileName = new File() or you have the problem of variant API manipulation


答:
You need an additional LEFT JOIN in order to eliminate redundant records:

```<code>SELECT a.[date], a.Item, a.Location, a.qty,
       b.[date] LastChange, b.qty LastQty
FROM t AS a
LEFT JOIN t AS b
   ON a.Item = b.Item AND a.location = b.location AND b.date < a.date AND a.qty != b.qty
LEFT JOIN t AS c
   ON c.Item = b.Item AND c.location = b.location AND c.date < b.date
WHERE
    a.[date] = '2017-11-16' AND c.Item IS NULL
</code>```

Using

```<code>LEFT JOIN t AS c
   ON c.Item = b.Item AND c.location = b.location AND c.date < b.date
</code>```

combined with

```<code>WHERE
    ... AND c.Item IS NULL
</code>```

is like saying: get me those b records having no other, c, record with an earlier date.

Demo here

Using FIRST_VALUE window function:

```<code>;WITH CTE AS (
    SELECT [date], [Item], [Location], [Qty],
           FIRST_VALUE([date]) OVER (PARTITION BY [Item], [Location]
                                     ORDER BY [date]) AS LastChange,
           FIRST_VALUE([Qty]) OVER (PARTITION BY [Item], [Location]
                                    ORDER BY [date]) AS LastQty
    FROM t
)
SELECT [date], [Item], [Location], [Qty],
       IIF([Qty] != [LastQty], LastChange, NULL) AS LastChange,
       IIF([Qty] != [LastQty], LastQty, NULL) AS LastQty
FROM CTE
WHERE [date] = '2017-11-16'
</code>```

Demo here

Title: SQL Server: detect inventory changes

Body:
I have a simple inventory table:

IF OBJECT_ID('tempdb.dbo.#t') IS NOT NULL
    DROP TABLE #t
GO

CREATE TABLE #t
(
    [date] DATE,
    Item VARCHAR(1),
    [Location] INT,
    Qty INT
)

INSERT INTO #t ([date], [Item], [Location], [Qty])
VALUES ('2017-11-16', 'A', 1, 5),
       ('2017-11-16', 'B', 1, 5),
       ('2017-11-16', 'B', 2, 10),
       ('2017-11-16', 'A', 3, 1),
       ('2017-11-16', 'C', 3, 2),
       ('2017-11-16', 'A', 4, 20),
       ('2017-11-15', 'A', 1, 5),
       ('2017-11-15', 'B', 1, 5),
       ('2017-11-15', 'B', 2, 10),
       ('2017-11-15', 'A', 3, 1),
       ('2017-11-15', 'C', 3, 8),
       ('2017-11-14', 'A', 1, 10),
       ('2017-11-14', 'B', 1, 1),
       ('2017-11-14', 'B', 2, 10),
       ('2017-11-14', 'A', 3, 1),
       ('2017-11-14', 'C', 3, 8)

I would like to find out the date (in the where clause) and also the difference in quantity of a location-item-level for the past.

Thus the result should be as follows:

+------------+------+----------+-----+------------+---------+
|    Date    | Item | Location | Qty | LastChange | LastQty |
+------------+------+----------+-----+------------+---------+
| 16.11.2017 | A    |        1 |   5 | 14.11.2017 |      10 |
| 16.11.2017 | B    |        1 |   5 | 14.11.2017 |       1 |
| 16.11.2017 | B    |        2 |  10 |            |         |
| 16.11.2017 | A    |        3 |   1 |            |         |
| 16.11.2017 | C    |        3 |   2 | 15.11.2017 |       8 |
| 16.11.2017 | A    |        4 |  20 |            |         |
+------------+------+----------+-----+------------+---------+

Since the inventory table is quite big I would like to avoid windowed-functions if possible.

I have self-joined the inventory table. However, I have problems to find a clause for eliminating the irrelevant data sets.

SELECT
    a.[date],
    a.Item,
    a.Location,
    a.qty,
    b.[date] LastChange,
    b.qty LastQty
FROM
    #t a
LEFT JOIN
    #t b ON a.Item = b.Item
         AND a.location = b.location
         AND b.date < a.date
WHERE
    a.date = '2017-11-16'

Body:
You need an additional LEFT JOIN in order to eliminate redundant records:

SELECT a.[date], a.Item, a.Location, a.qty,
       b.[date] LastChange, b.qty LastQty
FROM t AS a
LEFT JOIN t AS b
   ON a.Item = b.Item AND a.location = b.location AND b.date < a.date AND a.qty != b.qty
LEFT JOIN t AS c
   ON c.Item = b.Item AND c.location = b.location AND c.date < b.date
WHERE
    a.[date] = '2017-11-16' AND c.Item IS NULL

Using

LEFT JOIN t AS c
   ON c.Item = b.Item AND c.location = b.location AND c.date < b.date

combined with

WHERE
    ... AND c.Item IS NULL

is like saying: get me those b records having no other, c, record with an earlier date.

Demo here

Using FIRST_VALUE window function:

;WITH CTE AS (
    SELECT [date], [Item], [Location], [Qty],
           FIRST_VALUE([date]) OVER (PARTITION BY [Item], [Location]
                                     ORDER BY [date]) AS LastChange,
           FIRST_VALUE([Qty]) OVER (PARTITION BY [Item], [Location]
                                    ORDER BY [date]) AS LastQty
    FROM t
)
SELECT [date], [Item], [Location], [Qty],
       IIF([Qty] != [LastQty], LastChange, NULL) AS LastChange,
       IIF([Qty] != [LastQty], LastQty, NULL) AS LastQty
FROM CTE
WHERE [date] = '2017-11-16'

Demo here


问:
PhpStorm Code Style - Automatically remove spaces from around assignment operator, only in default argument values in functions
In trying to respect the coding style used at work, I've configured PhpStorm to respect all the requirements, with the exception of one:

no spaces before and after the assignment operator (=) when it's used for default argument values in functions. So for example it should look like this

```<code>public function sampleMethod($a, $b=null)
</code>```

Ignoring the validity of this rule, I would like to know how I could set this up in PhpStorm's Code Style section (or somewhere else?) so the IDE takes it into account and applies it each time I do a Reformat Code for example.
I've not been able to find a setting for this, unless I apply it to other contexts where the assignment operator is used, which is something I don't want.

答:
you can easily do it in phpstorm by going to

Settings > Editor > Code Style > PHP

and there go to tab

Spaces

and unchek the

Assingment opratores

if you have problem with this let me know

Body:
In trying to respect the coding style used at work, I've configured PhpStorm to respect all the requirements, with the exception of one:

no spaces before and after the assignment operator (=) when it's used for default argument values in functions. So for example it should look like this

public function sampleMethod($a, $b=null)

Ignoring the validity of this rule, I would like to know how I could set this up in PhpStorm's Code Style section (or somewhere else?) so the IDE takes it into account and applies it each time I do a Reformat Code for example.
I've not been able to find a setting for this, unless I apply it to other contexts where the assignment operator is used, which is something I don't want.


问:
Insert a new row into DataTable
I have a datatable filled with staff data like..

```<code>Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Staff 2 - Day 1 - Total
Staff 2 - Day 2 - Total
Staff 2 - Day 3 - Total
Staff 2 - Day 4 - Total
</code>```

I want to modify so that the result would be sth like..

```<code>Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Total   -       - Total Value
Staff 2 - Day 1 - Total
Staff 2 - Day 2 - Total
Staff 2 - Day 3 - Total
Staff 2 - Day 4 - Total
Total   -       - Total Value
</code>```

to be concluded, I need to insert the total row at the end of each staff record.

So, my question is how to insert a row into a datatable? Tkz..

答:
@William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow) OR .Rows.InsertAt(DataRow, Position). The following is a stub code which you can modify as per your convenience.

```<code>//Creating dummy datatable for testing
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col2", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col3", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col4", typeof(String));
dt.Columns.Add(dc);

DataRow dr = dt.NewRow();

dr[0] = "coldata1";
dr[1] = "coldata2";
dr[2] = "coldata3";
dr[3] = "coldata4";

dt.Rows.Add(dr);//this will add the row at the end of the datatable
//OR
int yourPosition = 0;
dt.Rows.InsertAt(dr, yourPosition);
</code>```

Title: Insert a new row into DataTable

Body:
I have a datatable filled with staff data like..

Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Staff 2 - Day 1 - Total
Staff 2 - Day 2 - Total
Staff 2 - Day 3 - Total
Staff 2 - Day 4 - Total

I want to modify so that the result would be sth like..

Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Total   -       - Total Value
Staff 2 - Day 1 - Total
Staff 2 - Day 2 - Total
Staff 2 - Day 3 - Total
Staff 2 - Day 4 - Total
Total   -       - Total Value

to be concluded, I need to insert the total row at the end of each staff record.

So, my question is how to insert a row into a datatable? Tkz..

Body:
@William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow) OR .Rows.InsertAt(DataRow, Position). The following is a stub code which you can modify as per your convenience.

//Creating dummy datatable for testing
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col2", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col3", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col4", typeof(String));
dt.Columns.Add(dc);

DataRow dr = dt.NewRow();

dr[0] = "coldata1";
dr[1] = "coldata2";
dr[2] = "coldata3";
dr[3] = "coldata4";

dt.Rows.Add(dr);//this will add the row at the end of the datatable
//OR
int yourPosition = 0;
dt.Rows.InsertAt(dr, yourPosition);


问:
Most efficient way to find the index of the only '1' bit in a char variable (in C)
This is an interview question:

You are given a char variable named ch, when you know that it represents a number that in its binary form, only one of its eight bits will be equal to '1'. I.E. , the only possible values for ch are: 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80.

Given the variable ch, I need to write the most efficient code to get the index of that '1' bit. For example: if ch == 0x1 -> result is 0. if ch == 0x4 -> result is 2.

The obvious way is to use switch-case, but I need something more efficient.

Is there any bit manipulation you can do here for efficient implementation?

答:
The simplest solution might not be the fastest, but only profiling against other solutions will let you determine that, and only for a given architecture and compiler.

Here is a very simple solution:

```<code>#include <math.h>

int leadingbit(unsigned char c) {
    return log2(c);
}
</code>```

Here is a solution with a lookup table:

```<code>int leadingbit(unsigned char c) {
#define N(x) ((076543210 / (x) / (x) / (x)) & 7)
#define N8(x) N(x), N(x+1), N(x+2), N(x+3), N(x+4), N(x+5), N(x+6), N(x+7)
#define N32(x) N8(x), N8(x+8), N8(x+16), N8(x+24)
    static unsigned char table[256] = {
        N32(0), N32(32), N32(64), N32(96), N32(128), N32(160), N32(192), N32(224),
    };
#undef N
#undef N8
#undef N32
    return table[c];
}
</code>```

Here is one inspired by Matt Timmermans without a memory reference:

```<code>int leadingbit(unsigned char c) {
    int n = c - 1;
    n = ((n & 0xAA) >> 1) + (n & 0x55);  //sums of pairs of bits
    n = ((n & 0xCC) >> 2) + (n & 0x33);  //sums of 4s of bits
    return ((n >> 4) + n) & 7;
}
</code>```

Here is one using the non portable builtin_clz() function (count leading zeroes):

```<code>#include <limits.h>

int leadingbit(unsigned char c) {
    return CHAR_BIT * sizeof(unsigned) - 1 - builtin_clz((unsigned)c);
}
</code>```

Note that all of the above assume that c is a power of 2, the behavior for other values is potentially undefined. You can check that c is a power of 2 with a simple expression:

```<code>if (c && !(c & (c - 1))) {
    /* c is a power of 2 */
}
</code>```

Body:
The simplest solution might not be the fastest, but only profiling against other solutions will let you determine that, and only for a given architecture and compiler.

Here is a very simple solution:

#include <math.h>

int leadingbit(unsigned char c) {
    return log2(c);
}

Here is a solution with a lookup table:

int leadingbit(unsigned char c) {
#define N(x) ((076543210 / (x) / (x) / (x)) & 7)
#define N8(x) N(x), N(x+1), N(x+2), N(x+3), N(x+4), N(x+5), N(x+6), N(x+7)
#define N32(x) N8(x), N8(x+8), N8(x+16), N8(x+24)
    static unsigned char table[256] = {
        N32(0), N32(32), N32(64), N32(96), N32(128), N32(160), N32(192), N32(224),
    };
#undef N
#undef N8
#undef N32
    return table[c];
}

Here is one inspired by Matt Timmermans without a memory reference:

int leadingbit(unsigned char c) {
    int n = c - 1;
    n = ((n & 0xAA) >> 1) + (n & 0x55);  //sums of pairs of bits
    n = ((n & 0xCC) >> 2) + (n & 0x33);  //sums of 4s of bits
    return ((n >> 4) + n) & 7;
}

Here is one using the non portable builtin_clz() function (count leading zeroes):

#include <limits.h>

int leadingbit(unsigned char c) {
    return CHAR_BIT * sizeof(unsigned) - 1 - builtin_clz((unsigned)c);
}

Note that all of the above assume that c is a power of 2, the behavior for other values is potentially undefined. You can check that c is a power of 2 with a simple expression:

if (c && !(c & (c - 1))) {
    /* c is a power of 2 */
}


答:
With PostgreSQL to remove all chars not numbers in a phone number :

```<code>SELECT regexp_replace('(12s3)-456-6356(a+sdk', '[^0-9]', '', 'g');
</code>```

So with your sample :

```<code>SELECT *
  FROM users
 WHERE regexp_replace(phone, '[^0-9]', '', 'g') = '6197450863';
</code>```

Hope this help.

Title: How to search phone numbers, ignoring dashes, bracets and spaces in MySql or PostgreSql?

Body:
With PostgreSQL to remove all chars not numbers in a phone number :

SELECT regexp_replace('(12s3)-456-6356(a+sdk', '[^0-9]', '', 'g');

So with your sample :

SELECT *
  FROM users
 WHERE regexp_replace(phone, '[^0-9]', '', 'g') = '6197450863';

Hope this help.


问:
Removing max and min elements of array from mean calculation
I am hoping to delete the highest number and the lowest number from the array 3*4. Let's say, the data looks like this:

```<code>a=np.array([[1,4,5,10],[2,6,5,0],[3,9,9,0]])
</code>```

so I expected to see the result like this:
    deleted_data=[4,5],[2,5],[3]

Could you advise me how to delete the max and min from each array?

to do so, I did like this (UPDATE):

```<code>#to find out the max / min values:
b = np.max(a,1) #max
c = np.min(a,1) #min

#creating dataset after deleting max & min
d=(a!=b[:,None]) & (a!=c[:,None])
f=[i[j] for i,j in zip(a, d)]

output: [array([8, 7, 7, 9, 9, 8]), array([8, 7, 8, 6, 8, 8]), array([9, 8, 9, 9, 8]), array([6, 7, 7, 6, 6, 7]), array([7, 7, 7, 7, 6])]
</code>```

Now I am not sure how to calculate the mean of the list objects?
I would like to calculate the mean of each array, so I have tried this:

```<code>mean1=f.mean(axis=0)
</code>```

but it did not work.

答:
Another method is to use a Masked Array

```<code>import numpy.ma as ma

mask = np.logical_or(a == a.max(1, keepdims = 1), a == a.min(1, keepdims = 1))
a_masked = ma.masked_array(a, mask = mask)
</code>```

from there if you want an average of the unmasked elements you can just do

```<code>a_masked.mean()
</code>```

Or you could even do the mean of the rows

```<code>a_masked.mean(1).data
</code>```

or columns (strange, but seems to be what you're asking for)

```<code>a_masked.mean(0).data
</code>```

Body:
I am hoping to delete the highest number and the lowest number from the array 3*4. Let's say, the data looks like this:

a=np.array([[1,4,5,10],[2,6,5,0],[3,9,9,0]])

so I expected to see the result like this:
    deleted_data=[4,5],[2,5],[3]

Could you advise me how to delete the max and min from each array?

to do so, I did like this (UPDATE):

#to find out the max / min values:
b = np.max(a,1) #max
c = np.min(a,1) #min

#creating dataset after deleting max & min
d=(a!=b[:,None]) & (a!=c[:,None])
f=[i[j] for i,j in zip(a, d)]

output: [array([8, 7, 7, 9, 9, 8]), array([8, 7, 8, 6, 8, 8]), array([9, 8, 9, 9, 8]), array([6, 7, 7, 6, 6, 7]), array([7, 7, 7, 7, 6])]

Now I am not sure how to calculate the mean of the list objects?
I would like to calculate the mean of each array, so I have tried this:

mean1=f.mean(axis=0)

but it did not work.

Body:
Another method is to use a Masked Array

import numpy.ma as ma

mask = np.logical_or(a == a.max(1, keepdims = 1), a == a.min(1, keepdims = 1))
a_masked = ma.masked_array(a, mask = mask)

from there if you want an average of the unmasked elements you can just do

a_masked.mean()

Or you could even do the mean of the rows

a_masked.mean(1).data

or columns (strange, but seems to be what you're asking for)

a_masked.mean(0).data


问:
Node js, starting Discord.js bot using exec, doesn’t properly run
So let’s say I have 2 files, a.js and b.js, where a.js is a simple node.js script which calls b.js which is a Discord.js bot.

a.js

```<code>const { exec } = require(‘child_process’);
exec(‘node b.js’, (err,stdout,stderr) => {
console.log(‘err: ‘ + err + ‘\n stdout: ‘ + stdout + ‘\n stderr:‘ + stderr);
});
</code>```

b.js

```<code>const Discord = require(‘discord.js’);
const fs = require(‘fs’);
var bot = new Discord.Client();
var token;
fs.readFile(‘token.txt’,(err,data) => {
    if(err){console.log(err); process.exit(0);}
    token = data;
});
bot.on(‘ready’,()=>{console.log(‘ready’);});
bot.on(‘message’, message => {
    if(message.content == ‘ping’){
        message.channel.send(‘pong’);
    }
});
bot.login(token);
</code>```

When I run a.js, the only output is

```<code>err:
stdout:
stderr:
</code>```

a.js then terminates and it appears as if b.js never ran.
I was wondering why this happens and why.
Additionally if anyone is wondering why I am doing this, I have this as apart of a bigger script and I boiled down the problem to this. And the main part is that b.js MUST be run from exec. I am running this in Windows 10 using the most recent version of node, and Discord.js. Thank you

答:
I had another go at this but when through the full discord bot setup...

my a.js looks like this...

```<code>const { spawn } = require('child_process');

const child = spawn('node',['b.js']);

process.stdin.pipe(child.stdin);

child.stdout.on('data', (data) => {
  console.log(`child stdout:\n${data}`);
});

child.stderr.on('data', (data) => {
    console.log(`child stderr:\n${data}`);
});
</code>```

My b.js looks like this...

```<code>const Discord = require('discord.js');
const fs = require('fs');
var bot = new Discord.Client();
var token;
fs.readFile('token.txt', {encoding: 'utf8'}, (err,token) => {
    if(err){console.log(err); process.exit(0);}

    bot.on('ready',()=>{
            console.log('ready');
    });
    bot.on('message', message => {
        if(message.content == 'ping'){
            message.channel.send('pong');
        }
    });

    bot.login(token);
});
</code>```

On b.js, I had to utf8 the file read, and make sure my token.txt file had no trailing, leading white space. Also, i moved the bot login code into the callback of the token file read.

Output example below...

I sent ping through on discord to see if it works, and the bot responded with pong.

Screenshot below.

I hope this code works for you, let me know...

Body:
So let’s say I have 2 files, a.js and b.js, where a.js is a simple node.js script which calls b.js which is a Discord.js bot.

a.js

const { exec } = require(‘child_process’);
exec(‘node b.js’, (err,stdout,stderr) => {
console.log(‘err: ‘ + err + ‘\n stdout: ‘ + stdout + ‘\n stderr:‘ + stderr);
});

b.js

const Discord = require(‘discord.js’);
const fs = require(‘fs’);
var bot = new Discord.Client();
var token;
fs.readFile(‘token.txt’,(err,data) => {
    if(err){console.log(err); process.exit(0);}
    token = data;
});
bot.on(‘ready’,()=>{console.log(‘ready’);});
bot.on(‘message’, message => {
    if(message.content == ‘ping’){
        message.channel.send(‘pong’);
    }
});
bot.login(token);

When I run a.js, the only output is

err:
stdout:
stderr:

a.js then terminates and it appears as if b.js never ran.
I was wondering why this happens and why.
Additionally if anyone is wondering why I am doing this, I have this as apart of a bigger script and I boiled down the problem to this. And the main part is that b.js MUST be run from exec. I am running this in Windows 10 using the most recent version of node, and Discord.js. Thank you

Body:
I had another go at this but when through the full discord bot setup...

my a.js looks like this...

const { spawn } = require('child_process');

const child = spawn('node',['b.js']);

process.stdin.pipe(child.stdin);

child.stdout.on('data', (data) => {
  console.log(`child stdout:\n${data}`);
});

child.stderr.on('data', (data) => {
    console.log(`child stderr:\n${data}`);
});

My b.js looks like this...

const Discord = require('discord.js');
const fs = require('fs');
var bot = new Discord.Client();
var token;
fs.readFile('token.txt', {encoding: 'utf8'}, (err,token) => {
    if(err){console.log(err); process.exit(0);}

    bot.on('ready',()=>{
            console.log('ready');
    });
    bot.on('message', message => {
        if(message.content == 'ping'){
            message.channel.send('pong');
        }
    });

    bot.login(token);
});

On b.js, I had to utf8 the file read, and make sure my token.txt file had no trailing, leading white space. Also, i moved the bot login code into the callback of the token file read.

Output example below...

I sent ping through on discord to see if it works, and the bot responded with pong.

Screenshot below.

I hope this code works for you, let me know...