问:
Match charactes and whitespaces, but not numbers
I am trying to create a regex that will match characters, whitespaces, but not numbers.

So hello 123 will not match, but hell o will.

I tried this:

```<code>[^\d\w]
</code>```

but, I cannot find a way to add whitespaces here. I have to use \w, because my strings can contain Unicode characters.

答:
You can use a lookahead:

```<code>(?=^\D+$)[\w\s]+
</code>```

In Python:

```<code>import re

strings = ['hello 123', 'hell o']

rx = re.compile(r'(?=^\D+$)[\w\s]+')

new_strings = [string for string in strings if rx.match(string)]
print(new_strings)
# ['hell o']
</code>```

Body:
I am trying to create a regex that will match characters, whitespaces, but not numbers.

So hello 123 will not match, but hell o will.

I tried this:

[^\d\w]

but, I cannot find a way to add whitespaces here. I have to use \w, because my strings can contain Unicode characters.

Body:
You can use a lookahead:

(?=^\D+$)[\w\s]+

In Python:

import re

strings = ['hello 123', 'hell o']

rx = re.compile(r'(?=^\D+$)[\w\s]+')

new_strings = [string for string in strings if rx.match(string)]
print(new_strings)
# ['hell o']


来源: stackexchange

问:
jquery's mouseover/out function only works after click-event in Firefox
When creating a mouseover/out action on an span in my html it appeared that there is no interaction with the link, up until I first click the element; after which the over/out events are almost simultanuously fired.

The simple javascript works both in Chrome and FirefoxDeveloperEdition; but the new quantum release displays this strange  behaviour.

Anybody else experiencing this?

```<code>$(".item")
.mouseover(function(ev){
    console.log('over');
  })
.mouseout(function(ev) {
    console.log('out');
})
.click(function (ev) {
    console.log('click');
})

<span class="item">click me</span>
</code>```

答:
Found the issue. Thanks for thinking along, your remark @delinear set me on the right path.

I was working in the responsive mode of the browser... apparently it then doesn't fire the mouseover/mouseout events :(

ContentLicense: CC BY-SA 3.0

Body:
When creating a mouseover/out action on an span in my html it appeared that there is no interaction with the link, up until I first click the element; after which the over/out events are almost simultanuously fired.

The simple javascript works both in Chrome and FirefoxDeveloperEdition; but the new quantum release displays this strange  behaviour.

Anybody else experiencing this?

$(".item")
.mouseover(function(ev){
    console.log('over');
  })
.mouseout(function(ev) {
    console.log('out');
})
.click(function (ev) {
    console.log('click');
})

click me


问:
Cassandra : Required RAM Space
I have a two node Cassandra (3.10) cluster. I have migrated some data. Data size is 1.4 TB according to nodetool in each node.
I tried to check RAM size required by Cassandra instance-

```<code>ps -aux | grep cassandra
</code>```

I got :

```<code>root      2510  124 80.2 1515965216 26435808 pts/0 SLl 10:36 138:10 java -Xloggc:/opt/cassandra/logs/gc.log ...... /*/*.jar org.apache.cassandra.service.CassandraDaemon
</code>```

here we can see that Cassandra is taking nearly 26.5 GB space in RAM, and I observe that this size is continuously increasing.

I want to know is it a normal behavior of Cassandra?

答:
So this is less a cassandra behavior and more a how java works. In your cassandra-env.sh file you can modify the starting and maximum memory values for cassandra.

-Xms<Value> Specifies how much memory cassandra starts with

-Xmx<Value> Specifies how much the heap size can grow until.

A common practice with cassandra is to initialize the process with -Xms and -Xmx being the same.  This removes the overhead of the server having to expand heapspace and allows it to be controlled so issues like what you're having don't occur.

As an aside, consider using G1GC instead of CMS for garbage collection if you're going to exceed 12GB.

Title: Cassandra : Required RAM Space

Body:
I have a two node Cassandra (3.10) cluster. I have migrated some data. Data size is 1.4 TB according to nodetool in each node.
I tried to check RAM size required by Cassandra instance-

ps -aux | grep cassandra

I got :

root      2510  124 80.2 1515965216 26435808 pts/0 SLl 10:36 138:10 java -Xloggc:/opt/cassandra/logs/gc.log ...... /*/*.jar org.apache.cassandra.service.CassandraDaemon

here we can see that Cassandra is taking nearly 26.5 GB space in RAM, and I observe that this size is continuously increasing.

I want to know is it a normal behavior of Cassandra?


问:
what is wso2 identity
Can someone explain, what is wso2 identity and using ?

i not found a explain in the web,

only:

WSO2 Identity Server enables enterprise architects and developers to improve customer experience by reducing identity provisioning time, guaranteeing secure online interactions, and delivering a reduced single sign-on environment. The WSO2 Identity Server decreases identity management and entitlement management administration burden by including role base access control (RBAC) convention, fine-grained policy based access control, and SSO bridging.

答: it's an identity management server , a simple example of wso2 identity is oAuth Identity System</p>

Title: what is wso2 identity


问:
R: divide variable in dataframe by specific value from list or vector
I'm a newb at R, so forgive my ignorance.

I have a dataframe that consists of two variables: Location and response. I have another dataframe that consists of sampling effort at each location. I need to divide the response by the sampling effort using the location as the identifier. I know there is probably an easy solution, but I'm striking out finding it. I would appreciate any help.

```<code>Example:
Dataframe 1

Location Response

Loc1     25

Loc2     63

Loc3     5.63

Dataframe2

Location Sampling effort

Loc1     2

Loc2     6.5

Loc3     3
</code>```

答:
You can merge them using merge() and then just divide two columns:

```<code>df3 <- merge(df1, df2)
df3$solution <- df3$Response / df3$Sampling_effort
df3
 # Location Response Sampling_effort  solution
 # 1   Loc1    25.00          2.0    12.500000
 # 2   Loc2    63.00          6.5     9.692308
 # 3   Loc3     5.63          3.0     1.876667
</code>```

I used the data:

```<code>df1 <- structure(list(Location = structure(1:3, .Label = c("Loc1", "Loc2",
         "Loc3"), class = "factor"), Response = c(25, 63, 5.63)), .Names = c("Location",
         "Response"), class = "data.frame", row.names = c(NA, -3L))

df2 <- structure(list(Location = structure(1:3, .Label = c("Loc1", "Loc2",
           "Loc3"), class = "factor"), Sampling_effort = c(2, 6.5, 3)), .Names = c("Location",
           "Sampling_effort"), class = "data.frame", row.names = c(NA, -3L))
</code>```

Body:
I'm a newb at R, so forgive my ignorance.

I have a dataframe that consists of two variables: Location and response. I have another dataframe that consists of sampling effort at each location. I need to divide the response by the sampling effort using the location as the identifier. I know there is probably an easy solution, but I'm striking out finding it. I would appreciate any help.

Example:
Dataframe 1

Location Response

Loc1     25

Loc2     63

Loc3     5.63

Dataframe2

Location Sampling effort

Loc1     2

Loc2     6.5

Loc3     3

Body:
You can merge them using merge() and then just divide two columns:

df3 <- merge(df1, df2)
df3$solution <- df3$Response / df3$Sampling_effort
df3
 # Location Response Sampling_effort  solution
 # 1   Loc1    25.00          2.0    12.500000
 # 2   Loc2    63.00          6.5     9.692308
 # 3   Loc3     5.63          3.0     1.876667

I used the data:

df1 <- structure(list(Location = structure(1:3, .Label = c("Loc1", "Loc2",
         "Loc3"), class = "factor"), Response = c(25, 63, 5.63)), .Names = c("Location",
         "Response"), class = "data.frame", row.names = c(NA, -3L))

df2 <- structure(list(Location = structure(1:3, .Label = c("Loc1", "Loc2",
           "Loc3"), class = "factor"), Sampling_effort = c(2, 6.5, 3)), .Names = c("Location",
           "Sampling_effort"), class = "data.frame", row.names = c(NA, -3L))


问:
onLocationChanged() never called
I am writing a code that brings current location but it is not giving me the location because it never calls onLocationChanged() .Is there any way to find the location.

mobileLocation is coming 0 for this case, so the execution goes to the else block.

My code is

```<code>public class FindLocation {
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
private String provider;

public FindLocation(Context ctx){
    locManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
    locListener = new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status,
                Bundle extras) {
        }
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onProviderDisabled(String provider) {
        }
        @Override
        public void onLocationChanged(Location location) {
            System.out.println("mobile location is in listener="+location);
            mobileLocation = location;
        }
    };
    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener);
    if (mobileLocation != null) {
        locManager.removeUpdates(locListener);
        String londitude = "Londitude: " + mobileLocation.getLongitude();
        String latitude = "Latitude: " + mobileLocation.getLatitude();
        String altitiude = "Altitiude: " + mobileLocation.getAltitude();
        String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
        String time = "Time: " + mobileLocation.getTime();
        Toast.makeText(ctx, "Latitude is = "+latitude +"Longitude is ="+londitude, Toast.LENGTH_LONG).show();
    } else {
        System.out.println("in find location 4");
        Toast.makeText(ctx, "Sorry location is not determined", Toast.LENGTH_LONG).show();
    }
}
   }
</code>```

答:
In my case the app was not asking for permissions. Although I have added the permissions in menifest file. So I was not able to allow my app to access the location.

As a fix, I manually went to: Settings->Permissions->Your location and enabled the location permission for my under-development app. And that fixed my problem.

I assume that this issue is only when the app is installed through Android Studio. I hope it will not occur when the app is installed from Google Play.

Title: onLocationChanged() never called

Body:
I am writing a code that brings current location but it is not giving me the location because it never calls onLocationChanged() .Is there any way to find the location.

mobileLocation is coming 0 for this case, so the execution goes to the else block.

My code is

public class FindLocation {
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
private String provider;

public FindLocation(Context ctx){
    locManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
    locListener = new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status,
                Bundle extras) {
        }
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onProviderDisabled(String provider) {
        }
        @Override
        public void onLocationChanged(Location location) {
            System.out.println("mobile location is in listener="+location);
            mobileLocation = location;
        }
    };
    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener);
    if (mobileLocation != null) {
        locManager.removeUpdates(locListener);
        String londitude = "Londitude: " + mobileLocation.getLongitude();
        String latitude = "Latitude: " + mobileLocation.getLatitude();
        String altitiude = "Altitiude: " + mobileLocation.getAltitude();
        String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
        String time = "Time: " + mobileLocation.getTime();
        Toast.makeText(ctx, "Latitude is = "+latitude +"Longitude is ="+londitude, Toast.LENGTH_LONG).show();
    } else {
        System.out.println("in find location 4");
        Toast.makeText(ctx, "Sorry location is not determined", Toast.LENGTH_LONG).show();
    }
}
   }


问:
String Benchmarks in C# - Refactoring for Speed/Maintainability
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code).  I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with.  As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.

```<code>private static string MakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += System.Convert.ToString(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += System.Convert.ToString(ca[i]);
            }
            return result;
        }

static string SplitCamelCase(string str)
    {
        string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
        string result = String.Join(" ", temp);
        return result;
    }
</code>```

The first function MakeNiceString() is the function I found in some code I was updating at work.  The purpose of the function is to translate ThisIsAString to This Is A String.  It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.

I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.

Well, here are the results:

With 10 Iterations:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```

However, it changes drastically over the longhaul:

With 10,000 Iterations:

```
MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks
```

Refactoring MakeNiceString()

The process of refactoring MakeNiceString() started with simply removing the conversions that were taking place.  Doing that yielded the following results:

```
MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486
```

Here's the code after Refactor #1:

```<code>private static string ImprovedMakeNiceString(string str)
        { //Removed Convert.ToString()
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += ca[0];
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += ca[i];
            }
            return result;
        }
</code>```

Refactor#2 - Use StringBuilder

My second task was to use StringBuilder instead of String.  Since String is immutable, unnecessary copies were being created throughout the loop.  The benchmark for using that is below, as is the code:

```<code>static string RefactoredMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
            int i = 0;
            sb.Append(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    sb.Append(" ");
                }
                sb.Append(ca[i]);
            }
            return sb.ToString();
        }
</code>```

This results in the following Benchmark:

```
MakeNiceString Took:           124497 Ticks   //Original
SplitCamelCase Took:           464459 Ticks   //Regex
ImprovedMakeNiceString Took:   117369 Ticks   //Remove Conversion
RefactoredMakeNiceString Took:  38542 Ticks   //Using StringBuilder
```

Changing the for loop to a foreach loop resulted in the following benchmark result:

```<code>static string RefactoredForEachMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
            sb1.Append(ca[0]);
            foreach (char c in ca)
            {
                if (!(char.IsLower(c)))
                {
                    sb1.Append(" ");
                }
                sb1.Append(c);
            }
            return sb1.ToString();
        }
</code>```

```
RefactoredForEachMakeNiceString    Took:  45163 Ticks
```

As you can see, maintenance-wise, the foreach loop will be the easiest to maintain and have the 'cleanest' look.  It is slightly slower than the for loop, but infinitely easier to follow.

Alternate Refactor: Use Compiled Regex

I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster.  What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:

```<code>static void runTest5()
        {
            Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
            for (int i = 0; i < 10000; i++)
            {
                CompiledRegex(rg, myString);
            }
        }
 static string CompiledRegex(Regex regex, string str)
    {
        string result = null;
        Regex rg1 = regex;
        string[] temp = rg1.Split(str);
        result = String.Join(" ", temp);
        return result;
    }
</code>```

Final Benchmark Results:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```0

Or, if you prefer milliseconds:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```1

So the percentage gains are:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```2

(Please check my math)

In the end, I'm going to replace what's there with the RefactoredForEachMakeNiceString() and while I'm at it, I'm going to rename it to something useful, like SplitStringOnUpperCase.

Benchmark Test:

To benchmark, I simply invoke a new Stopwatch for each method call:

```<code>       string myString = "ThisIsAUpperCaseString";
       Stopwatch sw = new Stopwatch();
       sw.Start();
       runTest();
       sw.Stop();

     static void runTest()
        {

            for (int i = 0; i < 10000; i++)
            {
                MakeNiceString(myString);
            }

        }
</code>```

Questions

What causes these functions to be so different 'over the long haul', and

How can I improve this function
a) to be more maintainable or
b) to run faster?

How would I do memory benchmarks on these to see which used less memory?

Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.

NB: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code as is.  I'm well aware you can remove the System.Convert.ToString() in the first method, and I did just that.  If anyone is aware of any implications of removing the System.Convert.ToString(), that would also be helpful to know.

答: Use a StringBuilder instead of concatenation. Each concatenation is creating a new string instance and throwing away the old.

OwnerDisplayName: Gortok

ContentLicense: CC BY-SA 2.5

Body:
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code).  I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with.  As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.

private static string MakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += System.Convert.ToString(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += System.Convert.ToString(ca[i]);
            }
            return result;
        }

static string SplitCamelCase(string str)
    {
        string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
        string result = String.Join(" ", temp);
        return result;
    }

The first function MakeNiceString() is the function I found in some code I was updating at work.  The purpose of the function is to translate ThisIsAString to This Is A String.  It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.

I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.

Well, here are the results:

With 10 Iterations:

MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks

However, it changes drastically over the longhaul:

With 10,000 Iterations:

MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks

Refactoring MakeNiceString()

The process of refactoring MakeNiceString() started with simply removing the conversions that were taking place.  Doing that yielded the following results:

MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486

Here's the code after Refactor #1:

private static string ImprovedMakeNiceString(string str)
        { //Removed Convert.ToString()
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += ca[0];
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += ca[i];
            }
            return result;
        }

Refactor#2 - Use StringBuilder

My second task was to use StringBuilder instead of String.  Since String is immutable, unnecessary copies were being created throughout the loop.  The benchmark for using that is below, as is the code:

static string RefactoredMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
            int i = 0;
            sb.Append(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    sb.Append(" ");
                }
                sb.Append(ca[i]);
            }
            return sb.ToString();
        }

This results in the following Benchmark:

MakeNiceString Took:           124497 Ticks   //Original
SplitCamelCase Took:           464459 Ticks   //Regex
ImprovedMakeNiceString Took:   117369 Ticks   //Remove Conversion
RefactoredMakeNiceString Took:  38542 Ticks   //Using StringBuilder

Changing the for loop to a foreach loop resulted in the following benchmark result:

static string RefactoredForEachMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
            sb1.Append(ca[0]);
            foreach (char c in ca)
            {
                if (!(char.IsLower(c)))
                {
                    sb1.Append(" ");
                }
                sb1.Append(c);
            }
            return sb1.ToString();
        }

RefactoredForEachMakeNiceString    Took:  45163 Ticks

As you can see, maintenance-wise, the foreach loop will be the easiest to maintain and have the 'cleanest' look.  It is slightly slower than the for loop, but infinitely easier to follow.

Alternate Refactor: Use Compiled Regex

I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster.  What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:

static void runTest5()
        {
            Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
            for (int i = 0; i < 10000; i++)
            {
                CompiledRegex(rg, myString);
            }
        }
 static string CompiledRegex(Regex regex, string str)
    {
        string result = null;
        Regex rg1 = regex;
        string[] temp = rg1.Split(str);
        result = String.Join(" ", temp);
        return result;
    }

Final Benchmark Results:

MakeNiceString Took                   139363 Ticks
SplitCamelCase Took                   489174 Ticks
ImprovedMakeNiceString Took           115478 Ticks
RefactoredMakeNiceString Took          38819 Ticks
RefactoredForEachMakeNiceString Took   44700 Ticks
CompiledRegex Took                    227021 Ticks

Or, if you prefer milliseconds:

MakeNiceString Took                  38 ms
SplitCamelCase Took                 123 ms
ImprovedMakeNiceString Took          33 ms
RefactoredMakeNiceString Took        11 ms
RefactoredForEachMakeNiceString Took 12 ms
CompiledRegex Took                   63 ms

So the percentage gains are:

MakeNiceString                   38 ms   Baseline
SplitCamelCase                  123 ms   223% slower
ImprovedMakeNiceString           33 ms   13.15% faster
RefactoredMakeNiceString         11 ms   71.05% faster
RefactoredForEachMakeNiceString  12 ms   68.42% faster
CompiledRegex                    63 ms   65.79% slower

(Please check my math)

In the end, I'm going to replace what's there with the RefactoredForEachMakeNiceString() and while I'm at it, I'm going to rename it to something useful, like SplitStringOnUpperCase.

Benchmark Test:

To benchmark, I simply invoke a new Stopwatch for each method call:

       string myString = "ThisIsAUpperCaseString";
       Stopwatch sw = new Stopwatch();
       sw.Start();
       runTest();
       sw.Stop();

     static void runTest()
        {

            for (int i = 0; i < 10000; i++)
            {
                MakeNiceString(myString);
            }

        }

Questions

What causes these functions to be so different 'over the long haul', and

How can I improve this function
a) to be more maintainable or
b) to run faster?

How would I do memory benchmarks on these to see which used less memory?

Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.

NB: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code as is.  I'm well aware you can remove the System.Convert.ToString() in the first method, and I did just that.  If anyone is aware of any implications of removing the System.Convert.ToString(), that would also be helpful to know.

LastEditorDisplayName: Gortok

OwnerDisplayName: Kent Boogaart


Title: Python/Pandas - remove not duplicated rows

Body:
I have DataFrame like this:

        product_id          dt  stock_qty
226870     2948259  2017-11-11     17.000
233645     2948259  2017-11-12     17.000
240572     2948260  2017-11-13      5.000
247452     2948260  2017-11-14      5.000
233644     2948260  2017-11-12      5.000
226869     2948260  2017-11-11      5.000
247451     2948262  2017-11-14     -2.000
226868     2948262  2017-11-11     -1.000  <- not duplicated
240571     2948262  2017-11-13     -2.000
240570     2948264  2017-11-13      5.488
233643     2948264  2017-11-12      5.488
244543     2948269  2017-11-11      2.500
247450     2948276  2017-11-14      3.250
226867     2948276  2017-11-11      3.250

I have to remove rows where stock_qty are different but product_id values are the same. So I should get DataFrame like this:

        product_id          dt  stock_qty
226870     2948259  2017-11-11     17.000
233645     2948259  2017-11-12     17.000
240572     2948260  2017-11-13      5.000
247452     2948260  2017-11-14      5.000
233644     2948260  2017-11-12      5.000
226869     2948260  2017-11-11      5.000
240570     2948264  2017-11-13      5.488
233643     2948264  2017-11-12      5.488
244543     2948269  2017-11-11      2.500
247450     2948276  2017-11-14      3.250
226867     2948276  2017-11-11      3.250

Thanks for help!

Body:
You need drop_duplicates for get all product_id values and then exclude them by isin with another condition chained by xor (^):

m1 = df['product_id'].isin(df.drop_duplicates('stock_qty', keep=False)['product_id'])
m2 = df.duplicated('product_id', keep=False)

df = df[m1 ^ m2]
print (df)
        product_id          dt  stock_qty
226870     2948259  2017-11-11     17.000
233645     2948259  2017-11-12     17.000
240572     2948260  2017-11-13      5.000
247452     2948260  2017-11-14      5.000
233644     2948260  2017-11-12      5.000
226869     2948260  2017-11-11      5.000
240570     2948264  2017-11-13      5.488
233643     2948264  2017-11-12      5.488
244543     2948269  2017-11-11      2.500
247450     2948276  2017-11-14      3.250
226867     2948276  2017-11-11      3.250

Detail:

print (m1)
226870    False
233645    False
240572    False
247452    False
233644    False
226869    False
247451     True
226868     True
240571     True
240570    False
233643    False
244543     True
247450    False
226867    False
Name: product_id, dtype: bool

print (m2)
226870     True
233645     True
240572     True
247452     True
233644     True
226869     True
247451     True
226868     True
240571     True
240570     True
233643     True
244543    False
247450     True
226867     True
dtype: bool


问:
How to store and read Digital Certificates in database using C# for email application (mailkit and mimekit)?
I m making an application which requires sending encrypted and digitally signed email for which I want to use S/MIME. I am using the MAILKIT and MIMEKIT API. However, the MIMEKIT requires the certificates to be loaded from a sql database. As shown below

```<code>public MySecureMimeContext()
    : base(OpenDatabase("C:\\wherever\\certdb.sqlite"))
{
}
</code>```

I have got certificates with me (Root  CA and Client Certificates (pfx files), but how can I save and read them from a database ? Or is there an alternative simple approach ?

答:
The DefaultSecureMimeContext that your class presumably inherits from has a number of Import() methods that you can use:

http://www.mimekit.net/docs/html/Overload_MimeKit_Cryptography_DefaultSecureMimeContext_Import.htm

Body:
I m making an application which requires sending encrypted and digitally signed email for which I want to use S/MIME. I am using the MAILKIT and MIMEKIT API. However, the MIMEKIT requires the certificates to be loaded from a sql database. As shown below

public MySecureMimeContext()
    : base(OpenDatabase("C:\\wherever\\certdb.sqlite"))
{
}

I have got certificates with me (Root  CA and Client Certificates (pfx files), but how can I save and read them from a database ? Or is there an alternative simple approach ?


问:
First query slow on Firebird
The first query run on a large dataset on a Firebird database after starting our application is always very slow. Subsequent calls to the same query (it is a stored procedure) are fine. I assume that this is to do with something being loaded into memory but I could do with a explanation of what and whether there is anything that can be done to get around the issue.</p>

答:
You didn't explain which Firebird version you are using but, in version 2.50, there is a bug (CORE 3227 - slow compilation of stored procedures) that can be the cause of your problem. More details:
http://www.firebirdnews.org/?p=5282&utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+FirebirdNews+%28Firebird+News%29 </p>

Title: First query slow on Firebird


问:
GIT: How to include commited and pushed changes from one branch to a brand new branch?
I have a branch(created from master)(branch_a) with several commits and pushes. Now is there a way to include all these changes into a brand new branch(from Master)(branch_b) that I am about to create?

```<code>git checkout master
git checkout -b branch_a
Now in branch_a i do some work(x,y,z)
git add .
git commit -m
git push
</code>```

And now,

```<code>git checkout master
git checkout -b branch_b
Now in branch_b
</code>```

How can I include my work(x,y,z) into the branch_b and then commit and push it ?

Thanks

答:
How can I include my work(x,y,z) into the branch_b and then commit and push it ?

If all you need is get all changes from branch_a and put them on branch_b. You could create the second brach FROM branch_a.

Like:

```<code>git checkout -b branch_b branch_a
</code>```

This will create a brand new branc_b from branch_a and automatically switch to branch_b. Just commit and push later.

Body:
I have a branch(created from master)(branch_a) with several commits and pushes. Now is there a way to include all these changes into a brand new branch(from Master)(branch_b) that I am about to create?

git checkout master
git checkout -b branch_a
Now in branch_a i do some work(x,y,z)
git add .
git commit -m
git push

And now,

git checkout master
git checkout -b branch_b
Now in branch_b

How can I include my work(x,y,z) into the branch_b and then commit and push it ?

Thanks

Body:
How can I include my work(x,y,z) into the branch_b and then commit and push it ?

If all you need is get all changes from branch_a and put them on branch_b. You could create the second brach FROM branch_a.

Like:

git checkout -b branch_b branch_a

This will create a brand new branc_b from branch_a and automatically switch to branch_b. Just commit and push later.


问:
Dijkstra - find destinations within budget
I was given a graph, including a start vertex, other vertices, and edges represent the costs going from one vertex to another. I need to find the set of destination vertices that I can travel to from the start vertex. The budget is a certain amount of dollars and the travel total cost should be within the budget. How can i implement the Dijkstra's algorithm to this problem? I think we usually use Dijkstra to find the shortest path between two fixed vertices before. But I am not sure how to implement Dijkstra on this budget problem. If someone can give some ideas, that really helps!</p>

答:
If you use Dijkstra algorithm, you may end up with the below scenarios:

Assuming budget of 50 and the graph of 4 nodes (start, node 1, node 2, node 3)

Start Node -> node 1 (15) -> node 2 (10): so total cost is 25

Start Node -> node 3 (15): total cost is 15

So now what is your expected result? You should go to node 1 then node 2 and ignore node 3 (since you cannot return back to start then go to node 3, the return will cost 30 too). Or you should go to node 1, back to start, then go to node 3 (total cost of 45, the largest cost you can utilise)

What you need is not the shortest path covering all destinations which is Floyd-Warshall algorithm https://en.wikipedia.org/wiki/Floyd–Warshall_algorithm


问:
Javascript: invoking objects like functions
Can I have a constructor that creates an instance, but when invoked executes a specific function?</p>

```<code>var Foo = function(){
    this.bar= "some variable";

   this.invokeFunction = function(){
        return this.bar;
    }
    return .... // what to do here
};

var foo = new Foo();

return foo;       // return the instance of Foo:  { bar: "some variable" }
return foo.bar; // returns "some variable"
return foo() ;    // returns "some variable"
</code>```

答:
You can fake it with something like this. Foo returns a function which has a __proto__ pointing to its own prototype. The returned function is callable, an instance of Foo and has access to instance properties:

var Foo = function(){
    function inner(){
        console.log("called")
        return "returned"
    }

    inner.__proto__ = Foo.prototype
    inner.bar= "some variable";
    return inner
};

Foo.prototype.someFn = function(){
    console.log("called prototype function")
    return this.bar
}

var foo = new Foo();

console.log(foo instanceof Foo) // it's an instance of Foo
console.log(foo.bar) // still has access to instance variables
console.log(foo())  // callable!
console.log(foo.someFn()) // prototype function with `this````

Body:
Can I have a constructor that creates an instance, but when invoked executes a specific function?

var Foo = function(){
    this.bar= "some variable";

   this.invokeFunction = function(){
        return this.bar;
    }
    return .... // what to do here
};

var foo = new Foo();

return foo;       // return the instance of Foo:  { bar: "some variable" }
return foo.bar; // returns "some variable"
return foo() ;    // returns "some variable"


问:
Java9 packager with jlink compress tags
when we create jlink runtime images we can use tags such as  '--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages' , creating a distribution folder around 45mb.

If we want to use javapackager, for example to create an .DMG file, how can we do a similar compression? since these tags are not avaiable for javapackager. Without them the final bundle is around 100mb, losing a lot the java9 modularization advantages, so my question is if it is possible to use javapackager with JRE runtime images created by jlink.

thanks

答:
Answering my own question, we can just use the combination of two:

For MacOSX example:

1) generate a runtime dist with jlink, this will create a lib folder with around 50mb if you use compress tags.

2) Generate MacOSX.app with javapackager, this .app will come with a runtime lib folder around 98mb.

3) Simple replace them, right click MacOSX.app-> "show package contents", then go to Plugins/Java.runtime/Contents/Home/ and replace lib folder with the one generated by jLink.

This way you have a self-contained Java app with around 50mb instead of 100mb, thanks to beautiful Java9 modules.

Would be cool to do all of this just with javapackager, if it's possible I couldn't find how, I suggest to use something like gradle to execute all this process with 1 command.

Title: Java9 packager with jlink compress tags


问:
How can I see cout output in a non-console application?
It seems rather tedious to output to debug window. Where can I find cout output if I am writing a non-console information ?

Like:

```<code>double i = a / b;
cout << b << endl;//I want to check out whether b is zero. It seems the output cannot be found anywhere.
</code>```

答:
SOLUTION: This answer solves the question and allows you to redirect console output to the Visual Studio Output window.
First we need a class that overrides the default cout string stream:

```<code>class dbg_stream_for_cout
    : public std::stringbuf
{
public:
    ~dbg_stream_for_cout() { sync(); }
    int sync()
    {
        ::OutputDebugStringA(str().c_str());
        str(std::string()); // Clear the string buffer
        return 0;
    }
};
dbg_stream_for_cout g_DebugStreamFor_cout;
</code>```

Then, somewhere you want to "activate" writing to the VS output window:

```<code>std::cout.rdbuf(&g_DebugStreamFor_cout); // Redirect std::cout to OutputDebugString!
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It seems rather tedious to output to debug window. Where can I find cout output if I am writing a non-console information ?

Like:

double i = a / b;
cout << b << endl;//I want to check out whether b is zero. It seems the output cannot be found anywhere.

Body:
SOLUTION: This answer solves the question and allows you to redirect console output to the Visual Studio Output window.
First we need a class that overrides the default cout string stream:

class dbg_stream_for_cout
    : public std::stringbuf
{
public:
    ~dbg_stream_for_cout() { sync(); }
    int sync()
    {
        ::OutputDebugStringA(str().c_str());
        str(std::string()); // Clear the string buffer
        return 0;
    }
};
dbg_stream_for_cout g_DebugStreamFor_cout;

Then, somewhere you want to "activate" writing to the VS output window:

std::cout.rdbuf(&g_DebugStreamFor_cout); // Redirect std::cout to OutputDebugString!


问:
How to print horizontally instead of vertically?
I wrote a script that is supposed to print an answer to a specific input horizontally.

For example if the input is:

```<code>TTACTGGCAT
</code>```

It should print:

```<code>TTACTGGCAT
AATGACCGTA
</code>```

My code:

```<code>x = 0
n = input("Insert DNA seqence: ")
print(n.upper())
while x < len(n):
  if 'T' in n[x]:
    print('A')
  if 'G' in n[x]:
    print('C')
  if 'C' in n[x]:
    print('G')
  if 'A' in n[x]:
    print('T')
  x = x + 1
</code>```

答: You can use the end parameter like print(some_var, end='') to not print ending newline after each call. In your loop you would want to print new line, so just run without the end parameter there. See print documentation.

Body:
I wrote a script that is supposed to print an answer to a specific input horizontally.

For example if the input is:

TTACTGGCAT

It should print:

TTACTGGCAT
AATGACCGTA

My code:

x = 0
n = input("Insert DNA seqence: ")
print(n.upper())
while x < len(n):
  if 'T' in n[x]:
    print('A')
  if 'G' in n[x]:
    print('C')
  if 'C' in n[x]:
    print('G')
  if 'A' in n[x]:
    print('T')
  x = x + 1


问:
Build GMP on 64bit Windows
I have followed the instruction on the "GMP Install Instruction for Windows Platform". I could build a 32bit version of GMP which can be used for Visual Studio.

```<code>./configure --prefix=${gmp-install} --disable-static --enable-shared
make
make install
</code>```

Then I installed mingw_w64 and msys on another machine (which is running 64bit Windows) and rerun the commands.

./configure was run without any problem. However, when I run "make", I got the following.

```<code>m4  -DHAVE_CONFIG_H -D__GMP_WITHIN_GMP -DOPERATION_add_n -DDLL_EXPORT -DPIC add_n.asm >tmp-add_n.s
gcc -std=gnu99 -c -DHAVE_CONFIG_H -I. -I.. -D__GMP_WITHIN_GMP -I.. -DOPERATION_add_n -O2 -pedantic -fomit-frame-pointer -mno-cygwin tmp-add_n.s -DDLL_EXPORT -DPIC -o .libs/add_n.o
tmp-add_n.s: Assembler messages:
tmp-add_n.s:84: Error: operand type mismatch for `push'
tmp-add_n.s:85: Error: operand type mismatch for `push'
tmp-add_n.s:86: Error: operand type mismatch for `push'
tmp-add_n.s:107: Error: operand type mismatch for `jmp'
tmp-add_n.s:114: Error: operand type mismatch for `pop'
tmp-add_n.s:115: Error: operand type mismatch for `pop'
tmp-add_n.s:116: Error: operand type mismatch for `pop'
make[2]: *** [add_n.lo] Error 1
make[2]: Leaving directory `/d/Temp/gmp-5.0.1/mpn'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/d/Temp/gmp-5.0.1'
make: *** [all] Error 2
</code>```

If I used "gmake" instead, the following error was shown.

```<code>m4 gcc  -DHAVE_CONFIG_H -D__GMP_WITHIN_GMP -DOPERATION_add_n -DDLL_EXPORT -DPIC add_n.asm >tmp-add_n.s
m4: gcc: No such file or directory
gmake[2]: *** [add_n.lo] Error 1
gmake[2]: Leaving directory `d:/Temp/gmp-5.0.1/mpn'
gmake[1]: *** [all-recursive] Error 1
gmake[1]: Leaving directory `d:/Temp/gmp-5.0.1'
gmake: *** [all] Error 2
</code>```

I am not familiar with C++ make. Do I need to specify any flag in order to notify mingw_w64 that I am building for 64bit? Thanks.

答:
I have tried the following. The library can be built successfully.</p>

```<code>./configure --prefix=/d/Temp/gmp-5.0.1-install --build=x86_64-w64-mingw32 --host=x86_64-w64-mingw32 --disable-static --enable-shared
</code>```

Title: Build GMP on 64bit Windows

Body:
I have followed the instruction on the "GMP Install Instruction for Windows Platform". I could build a 32bit version of GMP which can be used for Visual Studio.

./configure --prefix=${gmp-install} --disable-static --enable-shared
make
make install

Then I installed mingw_w64 and msys on another machine (which is running 64bit Windows) and rerun the commands.

./configure was run without any problem. However, when I run "make", I got the following.

m4  -DHAVE_CONFIG_H -D__GMP_WITHIN_GMP -DOPERATION_add_n -DDLL_EXPORT -DPIC add_n.asm >tmp-add_n.s
gcc -std=gnu99 -c -DHAVE_CONFIG_H -I. -I.. -D__GMP_WITHIN_GMP -I.. -DOPERATION_add_n -O2 -pedantic -fomit-frame-pointer -mno-cygwin tmp-add_n.s -DDLL_EXPORT -DPIC -o .libs/add_n.o
tmp-add_n.s: Assembler messages:
tmp-add_n.s:84: Error: operand type mismatch for `push'
tmp-add_n.s:85: Error: operand type mismatch for `push'
tmp-add_n.s:86: Error: operand type mismatch for `push'
tmp-add_n.s:107: Error: operand type mismatch for `jmp'
tmp-add_n.s:114: Error: operand type mismatch for `pop'
tmp-add_n.s:115: Error: operand type mismatch for `pop'
tmp-add_n.s:116: Error: operand type mismatch for `pop'
make[2]: *** [add_n.lo] Error 1
make[2]: Leaving directory `/d/Temp/gmp-5.0.1/mpn'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/d/Temp/gmp-5.0.1'
make: *** [all] Error 2

If I used "gmake" instead, the following error was shown.

m4 gcc  -DHAVE_CONFIG_H -D__GMP_WITHIN_GMP -DOPERATION_add_n -DDLL_EXPORT -DPIC add_n.asm >tmp-add_n.s
m4: gcc: No such file or directory
gmake[2]: *** [add_n.lo] Error 1
gmake[2]: Leaving directory `d:/Temp/gmp-5.0.1/mpn'
gmake[1]: *** [all-recursive] Error 1
gmake[1]: Leaving directory `d:/Temp/gmp-5.0.1'
gmake: *** [all] Error 2

I am not familiar with C++ make. Do I need to specify any flag in order to notify mingw_w64 that I am building for 64bit? Thanks.

Body:
I have tried the following. The library can be built successfully.

./configure --prefix=/d/Temp/gmp-5.0.1-install --build=x86_64-w64-mingw32 --host=x86_64-w64-mingw32 --disable-static --enable-shared


问:
pass my php variables to a bootstrap modal not working
in my page

```<code>foreach ($json->items as $sam) {
    $link= $sam->id->videoId;
    echo''.$link.'';
    //its showing last 5 youtube video id ok.. i set every video id witha button for modal

     echo'<button type="button" data-toggle="modal" data-target="#PlayModal" class="btn btn-outline btn-danger">Play</button>';
}
</code>```

but when im trying to open a model by box in new winddow pop up there only show 1st video ID. modal not getting '.$link.' valu in popup window. modal code puting same page blew finish {}

```<code>echo'<div class="modal inmodal" id="PlayModal" tabindex="-1" role="dialog" aria-hidden="true">
          <div class="modal-dialog">
              <div class="modal-content animated bounceInRight">
                  <div class="modal-body">
                      <p>'.$name.'</p>
                      <div class="modal-footer">
                          <button type="button" class="btn btn-outline btn-danger" data-dismiss="modal">Close</button>
                      </div>
                  </div>
              </div>
          </div>
     </div>';
</code>```

答:
According to the code given, even the first video should not play.

it is not printing the value of LINK inside the button, so it will not work.
Unless you have a JAVASCRIPT code observing the click and playing the video on click.

You can create the HTML code first manually containing the 5 video ID, and each video should have a button (according to your description), when clicked it will open the modal.

once that is done, you will be able to use php for each to properly echo the html code.

alternatively, the videos are in HTML list, and javascript will handle the event click, reading the video ID and passing to the player in the modal.

in either case, you need to understand the HTML structure first.

Body:
in my page

foreach ($json->items as $sam) {
    $link= $sam->id->videoId;
    echo''.$link.'';
    //its showing last 5 youtube video id ok.. i set every video id witha button for modal

     echo'<button type="button" data-toggle="modal" data-target="#PlayModal" class="btn btn-outline btn-danger">Play</button>';
}

but when im trying to open a model by box in new winddow pop up there only show 1st video ID. modal not getting '.$link.' valu in popup window. modal code puting same page blew finish {}

echo'

'.$name.'

                          <button type="button" class="btn btn-outline btn-danger" data-dismiss="modal">Close</button>

';


问:
Route to specific tab using anchor in ng-bootstrap
I am trying to create a link which opens a tab from ng-bootstrap.

The tab has a specific id and I am creating the link as follows:

```<code> [routerLink]="['/path/', i.name]" fragment="anchorid"
</code>```

The url is created correctly but the tab is not opened. It always shows the first tab on the page.

I am using hash navigation with Angular 4.

答:
Make sure you are using router outlet to view the next tab.</p>

```<code><router-outlet></router-outlet>
</code>```

Body:
I am trying to create a link which opens a tab from ng-bootstrap.

The tab has a specific id and I am creating the link as follows:

 [routerLink]="['/path/', i.name]" fragment="anchorid"

The url is created correctly but the tab is not opened. It always shows the first tab on the page.

I am using hash navigation with Angular 4.

Body:
Make sure you are using router outlet to view the next tab.

<router-outlet></router-outlet>


问:
Haskell "(.|.)" syntax
What does this syntax mean? (in the context of module declaration)

Example:

```<code>module XMonad (
    module XMonad.Main,
    module XMonad.Core,
    module XMonad.Config,
    module XMonad.Layout,
    module XMonad.ManageHook,
    module XMonad.Operations,
    module Graphics.X11,
    module Graphics.X11.Xlib.Extras,
    (.|.),
    MonadState(..), gets, modify,
    MonadReader(..), asks,
    MonadIO(..)
) where
</code>```

Can't find anything using search engines.

答:
It means "Bitwise or". It is an operator that the XMonad package re-exports. It is originally defined in Data.Bits.

https://hackage.haskell.org/package/xmonad-0.13/docs/XMonad.html#v:.-124-.

```<code>(.|.) :: Bits a => a -> a -> a #

    Bitwise "or"
</code>```

In Haskell, anything defined between ( ... ) is an operator, which is a function that works by default as infix notation.

Title: Haskell "(.|.)" syntax

Body:
What does this syntax mean? (in the context of module declaration)

Example:

module XMonad (
    module XMonad.Main,
    module XMonad.Core,
    module XMonad.Config,
    module XMonad.Layout,
    module XMonad.ManageHook,
    module XMonad.Operations,
    module Graphics.X11,
    module Graphics.X11.Xlib.Extras,
    (.|.),
    MonadState(..), gets, modify,
    MonadReader(..), asks,
    MonadIO(..)
) where

Can't find anything using search engines.

Body:
It means "Bitwise or". It is an operator that the XMonad package re-exports. It is originally defined in Data.Bits.

https://hackage.haskell.org/package/xmonad-0.13/docs/XMonad.html#v:.-124-.

(.|.) :: Bits a => a -> a -> a #

    Bitwise "or"

In Haskell, anything defined between ( ... ) is an operator, which is a function that works by default as infix notation.


问:
Write a const pattern to a file of specific size
I need to write C++ code that will open a binary file and will write 5 MB of '1' in to it.

Currently my code is:

```<code>#define BYTES_BUFFER_SIZE_5MB (1024*1024*5)

static char buffer[BYTES_BUFFER_SIZE_5MB];
memset(buffer, 0xff, BYTES_BUFFER_SIZE_5MB);
ofstream myFile ("data.bin", ios::out | ios::binary);
myFile.write(buffer, BYTES_BUFFER_SIZE_5MB);
</code>```

Is there a memset-like method for writing to a file, so I can avoid having a buffer?

答:
I think we can do this in one line with stream manipulators:

```<code>fout << std::setw(BYTES_BUFFER_SIZE_5MB - 1) << std::setfill(char(0xFF)) << char(0xFF);
</code>```

setw to set the number of bytes to write out

setfill to make it write out 0xFF by default

That way we don't have a buffer involved. The only risk is if you want to write a lot of bytes, you risk overflowing int on your call to setw.

Body:
I need to write C++ code that will open a binary file and will write 5 MB of '1' in to it.

Currently my code is:

#define BYTES_BUFFER_SIZE_5MB (1024*1024*5)

static char buffer[BYTES_BUFFER_SIZE_5MB];
memset(buffer, 0xff, BYTES_BUFFER_SIZE_5MB);
ofstream myFile ("data.bin", ios::out | ios::binary);
myFile.write(buffer, BYTES_BUFFER_SIZE_5MB);

Is there a memset-like method for writing to a file, so I can avoid having a buffer?

Body:
I think we can do this in one line with stream manipulators:

fout << std::setw(BYTES_BUFFER_SIZE_5MB - 1) << std::setfill(char(0xFF)) << char(0xFF);

setw to set the number of bytes to write out

setfill to make it write out 0xFF by default

That way we don't have a buffer involved. The only risk is if you want to write a lot of bytes, you risk overflowing int on your call to setw.


问:
Python: why appending to a list results in same values
This is my code:

```<code>a = []
res = []
for i in range(0, 3):
    a.append(i)
    res.append(a)
print(res)
</code>```

The result is:

```<code>[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
</code>```

But I want the result to be:

```<code>[[0], [0, 1], [0, 1, 2]]
</code>```

I know the solution is using the shallow copy: res.append(a[:]). But can somebody tell me why?

答:
When you append a to the res array, you are appending a pointer to the a variable. Not the 'value' of the a variable. So when you are done, the res array has the 'value' - [a, a, a].

When you shallow copy, you are copying the 'value' of the a variable at that stage of the loop into the res array, giving you a 'value' of - [[0],[0,1],[0,1,2]].

Body:
This is my code:

a = []
res = []
for i in range(0, 3):
    a.append(i)
    res.append(a)
print(res)

The result is:

[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

But I want the result to be:

[[0], [0, 1], [0, 1, 2]]

I know the solution is using the shallow copy: res.append(a[:]). But can somebody tell me why?


问:
Why do these links exceed the width?
How can we explain that these links exceed the 200px width:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo
</div></code>```

whereas, if we add a newline after each , it doesn't:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
</div></code>```

What is the usual good practice to not be trapped in such corner cases?

答:
display:block; will do magic you need

    .small { background-color: red; width: 200px; }
    .tag {
      background-color: rgba(0,0,0,.05);
      /*margin-right: 10px;*/ /* Remove Margin from Right*/
      display:block; /* Line Break in CSS */
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="small">
    2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo
    </div></code>```

Title: Why do these links exceed the width?

Body:
How can we explain that these links exceed the 200px width:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo

whereas, if we add a newline after each , it doesn't:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

2 January 2017
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo

What is the usual good practice to not be trapped in such corner cases?

Body:
display:block; will do magic you need

    .small { background-color: red; width: 200px; }
    .tag {
      background-color: rgba(0,0,0,.05);
      /*margin-right: 10px;*/ /* Remove Margin from Right*/
      display:block; /* Line Break in CSS */
    }

    <div class="small">
    <a class="date" href="blah">2 January 2017</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a><a class="tag" href="blah">#foooooo</a>
    </div>


问:
Odd behaviour of Python tokenizer when parsing integer numbers
I noticed the following fact with CPython3 and Pypy3, contrasting with the behaviour of both CPython2 and Pypy2:

In Python3, it looks like leading zeros when parsing code yield an error except for a very single number which is 0. Thus 00 is valid but not 042.

In Python2, leading zeros are allowed for all integers. Thus 00 and 042 are valid.

Why did Python change its behaviour between both versions?

答:
Python 3 standardized how all integer literals (other than base 10) were defined: 0?dddd..., where ? is a single letter indicating the base, and each d is interpreted as a digit in the appropriate base. 0... was retained as an exception, since 0 is 0 in any base, and was accepted as such before explicit base specifiers were required.

The biggest change related to this is that a number with a leading zero but no explicit base specifier is no longer assumed to be an octal number. Python 2 accepts both 042 and 0o42 as octal representations of decimal 34. (Early in Python's history, there were only three valid literals, with hexadecimal being the only one with a specifier. 0o... and 0b... were both later additions


问:
IOC container on nested view models
I'm developing a WPF application trying to adhere as much as possible to MVVM patterns, including DI and IoC.
The application is structured as "ViewModel first" where the visual hierarchy contains what follows:

```<code> MainView
 |-Login View
 |-Content View
   |-Content A
   |-Content B
   |-Content x
</code>```

Each view is referenced by its VM; "MainViewModel" and "ContentViewModel" expose a property which references the child VM to control the navigation of the inner elements.
That said "Content A", "Content B" and similar items have dependencies on various services which I would like to manage through DI.

I use a UnityContainer and I register all the dependencies in the "OnStartup" but here it comes my question: as I don't want to use a ServiceLocator how can I make the "sub-viewmodels" aware of the container? I'm pretty sure I'm doing something wrong theory-side but I haven't found any reference online.
Each tutorial/example I found online just register the dependencies in the container and then immediately resolve the models.

答:
Since a parent view model has access to the container and is responsible for creating any child view models, you could simply inject the child view models with a reference to the container when you instantiate them in the parent view model:

```<code>this.ChildViewModelProperty = new ChildViewModel(_container);
</code>```

This is a typical example of constructor dependency injection.

Title: IOC container on nested view models

Body:
I'm developing a WPF application trying to adhere as much as possible to MVVM patterns, including DI and IoC.
The application is structured as "ViewModel first" where the visual hierarchy contains what follows:

 MainView
 |-Login View
 |-Content View
   |-Content A
   |-Content B
   |-Content x

Each view is referenced by its VM; "MainViewModel" and "ContentViewModel" expose a property which references the child VM to control the navigation of the inner elements.
That said "Content A", "Content B" and similar items have dependencies on various services which I would like to manage through DI.

I use a UnityContainer and I register all the dependencies in the "OnStartup" but here it comes my question: as I don't want to use a ServiceLocator how can I make the "sub-viewmodels" aware of the container? I'm pretty sure I'm doing something wrong theory-side but I haven't found any reference online.
Each tutorial/example I found online just register the dependencies in the container and then immediately resolve the models.

Body:
Since a parent view model has access to the container and is responsible for creating any child view models, you could simply inject the child view models with a reference to the container when you instantiate them in the parent view model:

this.ChildViewModelProperty = new ChildViewModel(_container);

This is a typical example of constructor dependency injection.


问:
JQuery to add divs to list of images
Hey I have a list of images that I need to wrap with divs so that every three images is in a new div. The first div has to start at the beginning and continue for the next three images before closing and opening the next div. The final HTML should look like this:

```<code><div>
    <img />
    <img />
    <img />
</div>
<div>
    <img />
    <img />
    <img />
</div>
<div>
    <img />
    <img />
    <img />
</div>
</code>```

I know that this should have to do something with the nth child selector but so far I've only been able to select single elements rather then being able to select three at a time.

答:
You could do something like the following:</p>

```<code>var imgListLength = $imageList.length, // assuming $imageList is your jQuery object
    tmpArray = $imageList.toArray(),
    newHtml = '';

for (var i = 0; i < imgListLength; i = i + 3) {
  newHtml += '<div>';
  newHtml += tmpArray[i] + tmpArray[i + 1] + tmpArray[i + 2];
  newHtml += '</div>';
}

$('body').append(newHtml);
</code>```

Title: JQuery to add divs to list of images

Body:
Hey I have a list of images that I need to wrap with divs so that every three images is in a new div. The first div has to start at the beginning and continue for the next three images before closing and opening the next div. The final HTML should look like this:

I know that this should have to do something with the nth child selector but so far I've only been able to select single elements rather then being able to select three at a time.

Body:
You could do something like the following:

var imgListLength = $imageList.length, // assuming $imageList is your jQuery object
    tmpArray = $imageList.toArray(),
    newHtml = '';

for (var i = 0; i < imgListLength; i = i + 3) {
  newHtml += '<div>';
  newHtml += tmpArray[i] + tmpArray[i + 1] + tmpArray[i + 2];
  newHtml += '</div>';
}

$('body').append(newHtml);


问:
Eclipse EMF RAP Target Components
Good day all,

I am attempting to get an Eclipse RAP application running with EMF support. Following the steps from the Eclipse wiki (https://wiki.eclipse.org/RAP/EMF_Integration) as closely as possible (it's dated four years ago), I am putting the following packages into my Target definition:

EMF RAP Target Components

RAP Basic Equinox Target

RAP Runtime

This gives me the following Target definition:

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?pde version="3.8"?>
<target name="SCRAMSTargetDefinition" sequenceNumber="17">
    <locations>
        <location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="planner" includeSource="true" type="InstallableUnit">
            <unit id="org.eclipse.emf.rap.sdk.feature.group" version="2.13.0.v20170609-0928"/>
            <unit id="org.eclipse.rap.equinox.target.feature.feature.group" version="3.2.0.20170613-1148"/>
            <unit id="org.eclipse.rap.feature.feature.group" version="3.2.0.20170609-1144"/>
            <repository location="http://download.eclipse.org/releases/oxygen/"/>
        </location>
    </locations>
</target>
</code>```

The Target will not resolve though, giving me the following dependency errors:

```<code>Problems occurred while resolving the target contents
    Cannot complete the install because one or more required items could not be found.
        Cannot satisfy dependency:
            From: EMF RAP Runtime 2.13.0.v20170609-0928 (org.eclipse.emf.rap.feature.group 2.13.0.v20170609-0928)
            To: org.eclipse.emf.rap.edit.ui.feature.group [2.9.0.v20170609-0928]
        Cannot satisfy dependency:
            From: EMF RAP Target Components  2.13.0.v20170609-0928 (org.eclipse.emf.rap.sdk.feature.group 2.13.v20170609-0928)
            To: org.eclipse.emf.rap.feature.group [2.13.0.v20170609-0928]
        Missing requirement: EMF RAP Edit UI 2.9.0.v20170609-0928 (org.eclipse.emf.rap.edit.ui.feature.group 2.9.0.v20170609-0928) requires 'A.PDE.Target.Platform Cannot be installed into the IDE 0.0.0' but it could not be found
        Software being installed: EMF RAP Target Components 2.13.0.v20170609-0928 (org.eclipse.emf.rap.sdk.feature.group 2.13.0.v20170609-0928)
</code>```

Buried in there is A.PDE.Target.Platform Cannot be installed into the IDE 0.0.0, which would seem to be the core problem - but this is a Target Definition, not the IDE itself, so I'm not understanding why it's complaining in this way.

I have tried including combinations of other EMF packages into the Target Definition, but nothing has helped. Any guidance would be appreciated.

答:
I found the answer in the Eclipse Forums:

When adding the update site to the target definition, the Include required software option has to be disabled. This is equivalent to switching includeMode from planner to slicer. In addition to that, you might want to enable the Include all environments option (set includeAllPlatforms to true).

Please note that these settings have to be the same for all locations (if the target definition includes more than one location / update site).

Title: Eclipse EMF RAP Target Components

Body:
Good day all,

I am attempting to get an Eclipse RAP application running with EMF support. Following the steps from the Eclipse wiki (https://wiki.eclipse.org/RAP/EMF_Integration) as closely as possible (it's dated four years ago), I am putting the following packages into my Target definition:

EMF RAP Target Components

RAP Basic Equinox Target

RAP Runtime

This gives me the following Target definition:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?pde version="3.8"?>
<target name="SCRAMSTargetDefinition" sequenceNumber="17">
    <locations>
        <location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="planner" includeSource="true" type="InstallableUnit">
            <unit id="org.eclipse.emf.rap.sdk.feature.group" version="2.13.0.v20170609-0928"/>
            <unit id="org.eclipse.rap.equinox.target.feature.feature.group" version="3.2.0.20170613-1148"/>
            <unit id="org.eclipse.rap.feature.feature.group" version="3.2.0.20170609-1144"/>
            <repository location="http://download.eclipse.org/releases/oxygen/"/>
        </location>
    </locations>
</target>

The Target will not resolve though, giving me the following dependency errors:

Problems occurred while resolving the target contents
    Cannot complete the install because one or more required items could not be found.
        Cannot satisfy dependency:
            From: EMF RAP Runtime 2.13.0.v20170609-0928 (org.eclipse.emf.rap.feature.group 2.13.0.v20170609-0928)
            To: org.eclipse.emf.rap.edit.ui.feature.group [2.9.0.v20170609-0928]
        Cannot satisfy dependency:
            From: EMF RAP Target Components  2.13.0.v20170609-0928 (org.eclipse.emf.rap.sdk.feature.group 2.13.v20170609-0928)
            To: org.eclipse.emf.rap.feature.group [2.13.0.v20170609-0928]
        Missing requirement: EMF RAP Edit UI 2.9.0.v20170609-0928 (org.eclipse.emf.rap.edit.ui.feature.group 2.9.0.v20170609-0928) requires 'A.PDE.Target.Platform Cannot be installed into the IDE 0.0.0' but it could not be found
        Software being installed: EMF RAP Target Components 2.13.0.v20170609-0928 (org.eclipse.emf.rap.sdk.feature.group 2.13.0.v20170609-0928)

Buried in there is A.PDE.Target.Platform Cannot be installed into the IDE 0.0.0, which would seem to be the core problem - but this is a Target Definition, not the IDE itself, so I'm not understanding why it's complaining in this way.

I have tried including combinations of other EMF packages into the Target Definition, but nothing has helped. Any guidance would be appreciated.


问:
Webfont not working in Chrome extension
I've been following pretty much all tutorials there are to use a webfont in your chrome extension, but none of them have worked for me, it still continues to be the same ugly font.

I have downloaded this font as zip (https://fonts.google.com/specimen/Raleway?selection.family=Raleway) and saved Raleway-Regular.ttf under assets/fonts/

I have also added the file to web_accessible_resources.

```<code>"web_accessible_resources": [
    "assets/fonts/Raleway-Regular.ttf"
]
</code>```

In the style.css I have the following code in the top

```<code>@font-face {
    font-family: 'UniqueNameFont';
    font-style: normal;
    font-weight: 700;
    src: url('chrome-extension://<id_hidden>/assets/fonts/Raleway-Regular.ttf');
}

* {
    font-family: 'UniqueNameFont';
    box-sizing: border-box;
}
</code>```

The path to the file is correct, I've checked. Also, I don't get any errors in the console log.

Now, my extension has a shadow dom, which keeps my extension inside there, I then dynamically add the style.css file and the html. Like this..

```<code>// Add stylesheet
    var link = document.createElement("link")
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = chrome.runtime.getURL('style.css');
    shadow.appendChild(link);

    // Add content to shadow
    page = page.replace(/baseuri/g, extensionOrigin);
    shadow.innerHTML += page;
</code>```

All of the styling works, except for the font face. I'm guessing that it might have something to do with dynamically adding the content, but I find it very weird, since the styling of the elements are fine.

I have also experimented with the @import that Google Fonts provided, and I could see in the Networks tab that it loaded the file, but for some weird reason it doesn't effect anything.

答:
Seems it worked when I used Google Web Font Loader library, it's pretty straight forward.

```<code>var gwebfont = document.createElement("script");
    gwebfont.src = "https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js";

    var callback = function (){
        var s = document.createElement('script');
        s.type = 'text/javascript';
        var code = "WebFont.load({google: { families: ['Open Sans', 'Open Sans:light', 'Open Sans:semi-bold', 'Open Sans:bold'] } });";
        try {
          s.appendChild(document.createTextNode(code));
          shadow.appendChild(s);
        } catch (e) {
          s.text = code;
          shadow.appendChild(s);
        }
    }
    gwebfont.onload = callback;
    shadow.appendChild(gwebfont);
</code>```

And then you simply add the font family in your stylesheet

```<code> * {
    font-family: 'Open Sans', sans-serif;
}
</code>```

Title: Webfont not working in Chrome extension

Body:
I've been following pretty much all tutorials there are to use a webfont in your chrome extension, but none of them have worked for me, it still continues to be the same ugly font.

I have downloaded this font as zip (https://fonts.google.com/specimen/Raleway?selection.family=Raleway) and saved Raleway-Regular.ttf under assets/fonts/

I have also added the file to web_accessible_resources.

"web_accessible_resources": [
    "assets/fonts/Raleway-Regular.ttf"
]

In the style.css I have the following code in the top

@font-face {
    font-family: 'UniqueNameFont';
    font-style: normal;
    font-weight: 700;
    src: url('chrome-extension://<id_hidden>/assets/fonts/Raleway-Regular.ttf');
}

* {
    font-family: 'UniqueNameFont';
    box-sizing: border-box;
}

The path to the file is correct, I've checked. Also, I don't get any errors in the console log.

Now, my extension has a shadow dom, which keeps my extension inside there, I then dynamically add the style.css file and the html. Like this..

// Add stylesheet
    var link = document.createElement("link")
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = chrome.runtime.getURL('style.css');
    shadow.appendChild(link);

    // Add content to shadow
    page = page.replace(/baseuri/g, extensionOrigin);
    shadow.innerHTML += page;

All of the styling works, except for the font face. I'm guessing that it might have something to do with dynamically adding the content, but I find it very weird, since the styling of the elements are fine.

I have also experimented with the @import that Google Fonts provided, and I could see in the Networks tab that it loaded the file, but for some weird reason it doesn't effect anything.

Body:
Seems it worked when I used Google Web Font Loader library, it's pretty straight forward.

var gwebfont = document.createElement("script");
    gwebfont.src = "https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js";

    var callback = function (){
        var s = document.createElement('script');
        s.type = 'text/javascript';
        var code = "WebFont.load({google: { families: ['Open Sans', 'Open Sans:light', 'Open Sans:semi-bold', 'Open Sans:bold'] } });";
        try {
          s.appendChild(document.createTextNode(code));
          shadow.appendChild(s);
        } catch (e) {
          s.text = code;
          shadow.appendChild(s);
        }
    }
    gwebfont.onload = callback;
    shadow.appendChild(gwebfont);

And then you simply add the font family in your stylesheet

 * {
    font-family: 'Open Sans', sans-serif;
}


问:
R: divide variable in dataframe by specific value from list or vector
I'm a newb at R, so forgive my ignorance.

I have a dataframe that consists of two variables: Location and response. I have another dataframe that consists of sampling effort at each location. I need to divide the response by the sampling effort using the location as the identifier. I know there is probably an easy solution, but I'm striking out finding it. I would appreciate any help.

```<code>Example:
Dataframe 1

Location Response

Loc1     25

Loc2     63

Loc3     5.63

Dataframe2

Location Sampling effort

Loc1     2

Loc2     6.5

Loc3     3
</code>```

答:
As your dataframes follow the same order, it should be sufficient to do</p>

```<code>df1[,2]/df2[,2]
</code>```

Body:
I'm a newb at R, so forgive my ignorance.

I have a dataframe that consists of two variables: Location and response. I have another dataframe that consists of sampling effort at each location. I need to divide the response by the sampling effort using the location as the identifier. I know there is probably an easy solution, but I'm striking out finding it. I would appreciate any help.

Example:
Dataframe 1

Location Response

Loc1     25

Loc2     63

Loc3     5.63

Dataframe2

Location Sampling effort

Loc1     2

Loc2     6.5

Loc3     3

Body:
As your dataframes follow the same order, it should be sufficient to do

df1[,2]/df2[,2]


问:
With which apply function can I loop a clustering function over a grouped dataframe?
I have a data frame that contains ETAs for vehicles. The data contains many ETAs for one (actual) arrival, and I want to group the ETAs that should correspond to one arrival together.

My data looks something like this, with cluster as my desired result:

```<code>  vehicle      eta       ...   cluster
 --------- ------------ ----- ---------
  car_1     01-11-2017   ...         1
  car_1     02-11-2017   ...         1
  car_1     15-11-2017   ...         2
  horse_3   05-11-2017   ...         1
  horse_3   12-11-2017   ...         2
  horse_3   13-11-2017   ...         2
</code>```

I've written a custom function that performs this clustering. The input of the function are the rows for one vehicle, and it returns an array with cluster indices. For example, if I pass it rows 1-3 of my example data, it would output c(1,1,2). So now all I need to do is cycle over all the vehicles in the dataset and apply the function, but that's where I'm stuck.

With cluster_etas as my custom clustering function, I know I could do this:

```<code># Initialize an empty column
data$cluster <- 0

# Loop over all vehicles and perform clustering
for (i in unique(data$vehicle)) {
    filter_vector <- data$vehicle == i
    data$cluster[filter_vector] <- cluster_etas(data[filter_vector,])
}
</code>```

But I suspect there is a smarter solution that would look something like this, with an apply-kind of function filling the blanks:

```<code>data$cluster <- _____(data = data, by = vehicle, function = cluster_etas)
</code>```

Is there a function that performs this kind of operation? What would it be?

答:
I have found a working solution for the problem using the ddply function from the plyr package. It did require me to change my custom function - previously, the custom function would take a data frame as its argument and extract the required columns, now it takes those columns as arguments directly (which makes for a more general solution anyway).

```<code>data <- plyr::ddply(data, "vehicle", transform,
                    cluster = cluster_etas(eta, travel_time, ...))
</code>```

Body:
I have a data frame that contains ETAs for vehicles. The data contains many ETAs for one (actual) arrival, and I want to group the ETAs that should correspond to one arrival together.

My data looks something like this, with cluster as my desired result:

  vehicle      eta       ...   cluster
 --------- ------------ ----- ---------
  car_1     01-11-2017   ...         1
  car_1     02-11-2017   ...         1
  car_1     15-11-2017   ...         2
  horse_3   05-11-2017   ...         1
  horse_3   12-11-2017   ...         2
  horse_3   13-11-2017   ...         2

I've written a custom function that performs this clustering. The input of the function are the rows for one vehicle, and it returns an array with cluster indices. For example, if I pass it rows 1-3 of my example data, it would output c(1,1,2). So now all I need to do is cycle over all the vehicles in the dataset and apply the function, but that's where I'm stuck.

With cluster_etas as my custom clustering function, I know I could do this:

# Initialize an empty column
data$cluster <- 0

# Loop over all vehicles and perform clustering
for (i in unique(data$vehicle)) {
    filter_vector <- data$vehicle == i
    data$cluster[filter_vector] <- cluster_etas(data[filter_vector,])
}

But I suspect there is a smarter solution that would look something like this, with an apply-kind of function filling the blanks:

data$cluster <- _____(data = data, by = vehicle, function = cluster_etas)

Is there a function that performs this kind of operation? What would it be?

Body:
I have found a working solution for the problem using the ddply function from the plyr package. It did require me to change my custom function - previously, the custom function would take a data frame as its argument and extract the required columns, now it takes those columns as arguments directly (which makes for a more general solution anyway).

data <- plyr::ddply(data, "vehicle", transform,
                    cluster = cluster_etas(eta, travel_time, ...))


问:
How is it possible that the output of the following code is true?
```<code>this.someService.findDevices()
          .subscribe((segments) => {
            this.segments = Array.from(segments.segments);
            this.packs.forEach((pack) => {
              pack.segments = Array.from(segments.segments);
              pack.segments[0].devices[0].selected = true; //if commented, output is FALSE
              console.log(this.segments[0].devices[0]); // shows TRUE
            });
          });
</code>```

I created a method where I'm trying to add the segments array to each pack in this.packs.
I am creating a new array using Array.from() but for some reason when I set the pack.segments[0].devices[0] to TRUE, this.segments[0].devices[0] is changing to true as well.

Any idea how to solve it?

答: Create a top-level boolean variable inside your function called isSelected and set it appropriately. Then do your loop. If any one item changes switches, isSelected will then be set and return proper boolean value.

Body:
this.someService.findDevices()
          .subscribe((segments) => {
            this.segments = Array.from(segments.segments);
            this.packs.forEach((pack) => {
              pack.segments = Array.from(segments.segments);
              pack.segments[0].devices[0].selected = true; //if commented, output is FALSE
              console.log(this.segments[0].devices[0]); // shows TRUE
            });
          });

I created a method where I'm trying to add the segments array to each pack in this.packs.
I am creating a new array using Array.from() but for some reason when I set the pack.segments[0].devices[0] to TRUE, this.segments[0].devices[0] is changing to true as well.

Any idea how to solve it?


问:
Exclude Path in Azure Cosmos DB
What is the correct JSON to exclude certain keys from an input json to be not indexed by Azure CosmosDB. We are using the CosmosDB in mongodb mode. Was planning to change the index configuration on the Azure Portal after creating the collection.

Sample Input Json being

```<code>{
    "name": "test",
    "age": 1,
    "location": "l1",
    "height":5.7
}
</code>```

If I were to include name and age in the index and remove location and height from the index, what does the includedPaths and excludedPaths look like.

答:
Finally got it to work with the below spec:-</p>

```<code>{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [{
        "path": "/*",
        "indexes": [{
                "kind": "Range",
                "dataType": "Number",
                "precision": -1
            },
            {
                "kind": "Hash",
                "dataType": "String",
                "precision": 3
            }
        ]
    }],
    "excludedPaths": [{
            "path": "/\"location\"/?"
        },
        {
            "path": "/\"height\"/?"
        }
    ]
}
</code>```

Title: Exclude Path in Azure Cosmos DB

Body:
What is the correct JSON to exclude certain keys from an input json to be not indexed by Azure CosmosDB. We are using the CosmosDB in mongodb mode. Was planning to change the index configuration on the Azure Portal after creating the collection.

Sample Input Json being

{
    "name": "test",
    "age": 1,
    "location": "l1",
    "height":5.7
}

If I were to include name and age in the index and remove location and height from the index, what does the includedPaths and excludedPaths look like.

Body:
Finally got it to work with the below spec:-

{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [{
        "path": "/*",
        "indexes": [{
                "kind": "Range",
                "dataType": "Number",
                "precision": -1
            },
            {
                "kind": "Hash",
                "dataType": "String",
                "precision": 3
            }
        ]
    }],
    "excludedPaths": [{
            "path": "/\"location\"/?"
        },
        {
            "path": "/\"height\"/?"
        }
    ]
}


问:
Where are HERE maps docs about layer attributes?
I am experimenting with HERE Maps API. I am requesting Platform Data Extension API and getting a valid response.

The thing is I would like to know what do the values I get mean exactly? For example I can request ADAS_ATTRIB_FC1, is there any documentation telling me what do the slope values, curvature values etc. mean? And for other layer attributes?

Please see an example response for ADAS_ATTRIB request below:

```<code>{
    "Rows": [{
            "LINK_ID": "52795003",
            "HPX": "88135200,3000,9200,4200,2400,900,800,1200",
            "HPY": "487947300,700,2400,1100,700,200,100,-100",
            "HPZ": "48073,-76,-236,-107,-61,-23,-20,-30",
            "SLOPES": "-1866,6,1,33,-26,-31,-26,3837",
            "HEADINGS": "70051,-2011,-2374,6159,7062,8114",
            "CURVATURES": "1182,-1182,0,-14170,-7255,-5046",
            "VERTICAL_FLAGS": "0,0,0,0,0,0",
            "REFNODE_LINKCURVHEADS": "19928834:2225:72335",
            "NREFNODE_LINKCURVHEADS": "708877367:-29444:101120",
            "BUA_ROAD": "1",
            "BUA_ROAD_VERIFIED": "Y"
        }
}
</code>```

I haven't found anything like this in the online documentation (https://developer.here.com/documentation/platform-data/topics/layers-indexes-attributes.html) nor in the pdf documentation.

Since the HERE support doesn't reply at all, I am posting my question here.

Thanks in advance.

答:
Give it a try with PLATFORM EXTENSION REST API with GET request as following:

```<code>http://pde.cit.api.here.com/1/doc/layer.json?region=NA&release=LATEST&layer={name}&app_id={your_id}&app_code={your_code}
</code>```

Try to learn more about resources and indexes in order to retrieve a response you are looking for.
For example to get the whole list of attributes and corresponding layers in EU you can request as follows:

```<code>http://pde.cit.api.here.com/1/doc/attributes.json?region=EU&release=LATEST&app_id={your_id}=&app_code={your_code}
</code>```

Body:
I am experimenting with HERE Maps API. I am requesting Platform Data Extension API and getting a valid response.

The thing is I would like to know what do the values I get mean exactly? For example I can request ADAS_ATTRIB_FC1, is there any documentation telling me what do the slope values, curvature values etc. mean? And for other layer attributes?

Please see an example response for ADAS_ATTRIB request below:

{
    "Rows": [{
            "LINK_ID": "52795003",
            "HPX": "88135200,3000,9200,4200,2400,900,800,1200",
            "HPY": "487947300,700,2400,1100,700,200,100,-100",
            "HPZ": "48073,-76,-236,-107,-61,-23,-20,-30",
            "SLOPES": "-1866,6,1,33,-26,-31,-26,3837",
            "HEADINGS": "70051,-2011,-2374,6159,7062,8114",
            "CURVATURES": "1182,-1182,0,-14170,-7255,-5046",
            "VERTICAL_FLAGS": "0,0,0,0,0,0",
            "REFNODE_LINKCURVHEADS": "19928834:2225:72335",
            "NREFNODE_LINKCURVHEADS": "708877367:-29444:101120",
            "BUA_ROAD": "1",
            "BUA_ROAD_VERIFIED": "Y"
        }
}

I haven't found anything like this in the online documentation (https://developer.here.com/documentation/platform-data/topics/layers-indexes-attributes.html) nor in the pdf documentation.

Since the HERE support doesn't reply at all, I am posting my question here.

Thanks in advance.

Body:
Give it a try with PLATFORM EXTENSION REST API with GET request as following:

http://pde.cit.api.here.com/1/doc/layer.json?region=NA&release=LATEST&layer={name}&app_id={your_id}&app_code={your_code}

Try to learn more about resources and indexes in order to retrieve a response you are looking for.
For example to get the whole list of attributes and corresponding layers in EU you can request as follows:

http://pde.cit.api.here.com/1/doc/attributes.json?region=EU&release=LATEST&app_id={your_id}=&app_code={your_code}


问:
Sparse Scipy/Numpy: an efficient way to implement sum of pairwise mins operation
Computing the sum of pairwise mins between vectors is very popular in natural language processing (NLP) and is used in computing the intersecting histogram kernel [1]. However, in NLP we frequently deal with sparse matrices.

Here is an inefficient way that uses the slow for loops to compute this operation:

```<code>import numpy as np
from scipy.sparse import csr_matrix

# Initialize sparse matrices
A = csr_matrix(np.clip(np.random.randn(100, 64) - 1, 0, np.inf))
B = csr_matrix(np.clip(np.random.randn(64, 100) - 1, 0, np.inf))

# For each row, col vector i,j in A and B respectively
G = np.zeros((100, 100))
for i in range(A.shape[0]):
    for j in range(B.shape[1]):
        G[i, j] = A[i].minimum(B[:,j]).sum()
</code>```

Is there a way to do this without the for loop ?
I wouldn't mind a for loop if it can be compiled such as with using jit in numba.

A fast dense version of this is given here: Numpy: an efficient way to implement sum of pairwise mins operation

Thanks.

[1] http://blog.datadive.net/histogram-intersection-for-change-detection/

答:
Here is an implementation that should be ok efficient, leveraging sparseness as best as it can. There is a loop but only along one dim, so should be not too bad.

```<code>import numpy as np
from scipy.sparse import csr_matrix, csc_matrix

M, N, K = 640, 100, 650

B1 = csr_matrix(np.clip(np.random.randn(N, K) - 1, 0, np.inf))
B2 = csr_matrix(np.clip(np.random.randn(N, K) - 1, 0, np.inf))
B = B1-B2
A1 = csc_matrix(np.clip(np.random.randn(M, N) - 1, 0, np.inf))
A2 = csc_matrix(np.clip(np.random.randn(M, N) - 1, 0, np.inf))
A = A1-A2

result = np.zeros((M, K))
for j in range(N):
    ia = A.indices[A.indptr[j] : A.indptr[j+1]]
    ib = B.indices[B.indptr[j] : B.indptr[j+1]]
    IA, IB = np.ix_(ia, ib)
    da = A.data[A.indptr[j] : A.indptr[j+1]]
    db = B.data[B.indptr[j] : B.indptr[j+1]]
    # both nonzero
    result[IA, IB] += np.minimum.outer(da, db)
    # one negative ...
    am = da<0
    iam, dam = ia[am], da[am]
    bm = db<0
    ibm, dbm = ib[bm], db[bm]
    # ... the other zero
    za = np.ones((M,), dtype=bool)
    za[ia] = False
    zb = np.ones((K,), dtype=bool)
    zb[ib] = False
    IA, IB = np.ix_(iam, zb)
    result[IA, IB] += dam[:, None]
    IA, IB = np.ix_(za, ibm)
    result[IA, IB] += dbm
# compare with dense method
print(np.allclose(result, np.minimum(A.A[..., None], B.A).sum(axis=1)))
</code>```

Prints

```<code>True
</code>```

Body:
Computing the sum of pairwise mins between vectors is very popular in natural language processing (NLP) and is used in computing the intersecting histogram kernel [1]. However, in NLP we frequently deal with sparse matrices.

Here is an inefficient way that uses the slow for loops to compute this operation:

import numpy as np
from scipy.sparse import csr_matrix

# Initialize sparse matrices
A = csr_matrix(np.clip(np.random.randn(100, 64) - 1, 0, np.inf))
B = csr_matrix(np.clip(np.random.randn(64, 100) - 1, 0, np.inf))

# For each row, col vector i,j in A and B respectively
G = np.zeros((100, 100))
for i in range(A.shape[0]):
    for j in range(B.shape[1]):
        G[i, j] = A[i].minimum(B[:,j]).sum()

Is there a way to do this without the for loop ?
I wouldn't mind a for loop if it can be compiled such as with using jit in numba.

A fast dense version of this is given here: Numpy: an efficient way to implement sum of pairwise mins operation

Thanks.

[1] http://blog.datadive.net/histogram-intersection-for-change-detection/

Body:
Here is an implementation that should be ok efficient, leveraging sparseness as best as it can. There is a loop but only along one dim, so should be not too bad.

import numpy as np
from scipy.sparse import csr_matrix, csc_matrix

M, N, K = 640, 100, 650

B1 = csr_matrix(np.clip(np.random.randn(N, K) - 1, 0, np.inf))
B2 = csr_matrix(np.clip(np.random.randn(N, K) - 1, 0, np.inf))
B = B1-B2
A1 = csc_matrix(np.clip(np.random.randn(M, N) - 1, 0, np.inf))
A2 = csc_matrix(np.clip(np.random.randn(M, N) - 1, 0, np.inf))
A = A1-A2

result = np.zeros((M, K))
for j in range(N):
    ia = A.indices[A.indptr[j] : A.indptr[j+1]]
    ib = B.indices[B.indptr[j] : B.indptr[j+1]]
    IA, IB = np.ix_(ia, ib)
    da = A.data[A.indptr[j] : A.indptr[j+1]]
    db = B.data[B.indptr[j] : B.indptr[j+1]]
    # both nonzero
    result[IA, IB] += np.minimum.outer(da, db)
    # one negative ...
    am = da<0
    iam, dam = ia[am], da[am]
    bm = db<0
    ibm, dbm = ib[bm], db[bm]
    # ... the other zero
    za = np.ones((M,), dtype=bool)
    za[ia] = False
    zb = np.ones((K,), dtype=bool)
    zb[ib] = False
    IA, IB = np.ix_(iam, zb)
    result[IA, IB] += dam[:, None]
    IA, IB = np.ix_(za, ibm)
    result[IA, IB] += dbm
# compare with dense method
print(np.allclose(result, np.minimum(A.A[..., None], B.A).sum(axis=1)))

Prints

True