问:
Generate GUID in Windows with batch file
How can I generate a GUID in a batch file running using the commandline in Windows?</p>

答:
There is no built-in command available that does that. Either write your own, or get an existing one.

A simple program that outputs a GUID to the console could be written using C#:

```<code>class Program
{
    static void Main(string[] args)
    {
        System.Console.WriteLine(System.Guid.NewGuid().ToString());
    }
}
</code>```

Place the above snippet in a file name guidgen.cs and then compile it using the following command line (.NET Framework 2.0 would have to be installed on your system):

```<code>%WINDIR%\Microsoft.NET\Framework\v2.0.50727\csc.exe guidgen.cs
</code>```

This will create an executable named guidgen.exe.

Body:
There is no built-in command available that does that. Either write your own, or get an existing one.

A simple program that outputs a GUID to the console could be written using C#:

class Program
{
    static void Main(string[] args)
    {
        System.Console.WriteLine(System.Guid.NewGuid().ToString());
    }
}

Place the above snippet in a file name guidgen.cs and then compile it using the following command line (.NET Framework 2.0 would have to be installed on your system):

%WINDIR%\Microsoft.NET\Framework\v2.0.50727\csc.exe guidgen.cs

This will create an executable named guidgen.exe.


来源: stackexchange

问:
Singleton pattern by using Unity
Unity allows to create a singleton with:

```<code>this.UnityContainer.RegisterType<MyClass>(new ContainerControlledLifetimeManager());
var instance = this.UnityContainer.Resolve<MyClass>();
</code>```

The access to the MyClass's constructor must be public to allow the container to be able to create a new instance (for another project like a module, ...).

In this case, developers can still create a new instance by using the constructor directly:

```<code>var instance = new MyClass();
</code>```

How do I prevent developers from doing this?

Another way is to create an instance (constructor access of the class is private now - singleton pattern) and register it with unity like below, I lose the dependency property injection, and my workaround is to use the service locator to initialize the dependency properties in the static method Instance:

```<code>this.UnityContainer.RegisterInstance<MyClass>(MyClass.Instance);
</code>```

What is the best way to define the singleton pattern in both cases simultaneous (with and without unity)?

答:
You only have to use the singleton pattern.
An example you can find here: Singleton Pattern</p>

```<code>public class Singleton {
 private Singleton instance = new Singleton();

 private Singleton() {}

 public Singleton getInstance() {
    return instance;
 }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Singleton pattern by using Unity

Body:
Unity allows to create a singleton with:

this.UnityContainer.RegisterType<MyClass>(new ContainerControlledLifetimeManager());
var instance = this.UnityContainer.Resolve<MyClass>();

The access to the MyClass's constructor must be public to allow the container to be able to create a new instance (for another project like a module, ...).

In this case, developers can still create a new instance by using the constructor directly:

var instance = new MyClass();

How do I prevent developers from doing this?

Another way is to create an instance (constructor access of the class is private now - singleton pattern) and register it with unity like below, I lose the dependency property injection, and my workaround is to use the service locator to initialize the dependency properties in the static method Instance:

this.UnityContainer.RegisterInstance<MyClass>(MyClass.Instance);

What is the best way to define the singleton pattern in both cases simultaneous (with and without unity)?

Body:
You only have to use the singleton pattern.
An example you can find here: Singleton Pattern

public class Singleton {
 private Singleton instance = new Singleton();

 private Singleton() {}

 public Singleton getInstance() {
    return instance;
 }
}


问:
How to time-efficiently remove values next to 'NaN' values?
I'm trying to remove wrong values form my data (a series of 15mln values, 700MB). The values to be removed are values next to 'nan' values, e.g.:

Series: /1/,nan,/2/,3,/4/,nan,nan,nan,/8/,9
Numbers surrounded by slashes i.e. /1/,/2/,/4/,/8/ are values, which should be removed.

The problem is that it takes way too long to compute that with the following code that I have:

```<code>%%time

import numpy as np
import pandas as pd

# sample data
speed = np.random.uniform(0,25,15000000)
next_speed = speed[1:]

# create a dataframe
data_dict = {'speed': speed[:-1],
            'next_speed': next_speed}

df = pd.DataFrame(data_dict)

# calculate difference between the current speed and the next speed
list_of_differences = []

for i in df.index:
    difference = df.next_speed[i]-df.speed[i]
    list_of_differences.append(difference)

df['difference'] = list_of_differences

# add 'nan' to data in form of a string.

for i in range(len(df.difference)):
    # arbitrary condition
    if df.difference[i] < -2:
        df.difference[i] = 'nan'

#########################################
# THE TIME-INEFFICIENT LOOP

# remove wrong values before and after 'nan'.
for i in  range(len(df)):

    # check if the value is a number to skip computations of the following "if" cases
    if not(isinstance(df.difference[i], str)):
        continue

    # case 1: where there's only one 'nan' surrounded by values.
    # Without this case the algo will miss some wrong values because 'nan' will be removed
    # Example of a series: /1/,nan,/2/,3,4,nan,nan,nan,8,9
    # A number surrounded by slashes e.g. /1/ is a value to be removed
    if df.difference[i] == 'nan' and df.difference[i-1] != 'nan' and df.difference[i+1] != 'nan':
        df.difference[i-1]= 'wrong'
        df.difference[i+1]= 'wrong'

    # case 2: where the following values are 'nan': /1/, nan, nan, 4
    # E.g.: /1/, nan,/2/,3,/4/,nan,nan,nan,8,9
    elif df.difference[i] == 'nan' and df.difference[i+1] == 'nan':
        df.difference[i-1]= 'wrong'

    # case 3: where next value is NOT 'nan'  wrong, nan,nan,4
        # E.g.: /1/, nan,/2/,3,/4/,nan,nan,nan,/8/,9
    elif df.difference[i] == 'nan' and df.difference[i+1] != 'nan':
        df.difference[i+1]= 'wrong'
</code>```

How to make it more time-efficient?

答:
This is still a work in progress for me. I knocked 100x off your dummy data size to get down to something I could stand to wait for.

I also added this code at the top of my version:

```<code> import time

current_milli_time = lambda: int(round(time.time() * 1000))

def mark(s):
    print("[{}] {}".format(current_milli_time()/1000, s))
</code>```

This just prints a string with a time-mark in front of it, to see what's taking so long.

With that done, in your 'difference' column computation, you can replace the manual list generation with a vector operation. This code:

```<code>df = pd.DataFrame(data_dict)

mark("Got DataFrame")

# calculate difference between the current speed and the next speed
list_of_differences = []

for i in df.index:
    difference = df.next_speed[i]-df.speed[i]
    list_of_differences.append(difference)

df['difference'] = list_of_differences
mark("difference 1")

df['difference2'] = df['next_speed'] - df['speed']
mark('difference 2')

print(df[:10])
</code>```

Produces this output:

```<code>[1490943913.921] Got DataFrame
[1490943922.094] difference 1
[1490943922.096] difference 2
   next_speed      speed  difference  difference2
0   18.008314  20.182982   -2.174669    -2.174669
1   14.736095  18.008314   -3.272219    -3.272219
2    5.352993  14.736095   -9.383102    -9.383102
3    5.854199   5.352993    0.501206     0.501206
4    2.003826   5.854199   -3.850373    -3.850373
5   12.736061   2.003826   10.732236    10.732236
6    2.512623  12.736061  -10.223438   -10.223438
7   18.224716   2.512623   15.712093    15.712093
8   14.023848  18.224716   -4.200868    -4.200868
9   15.991590  14.023848    1.967741     1.967741
</code>```

Notice that the two difference columns are the same, but the second version took about 8 seconds less time. (Presumably 800 seconds when you have 100x more data.)

I did the same thing in the 'nanify' process:

```<code>df.difference2[df.difference2 < -2] = np.nan
</code>```

The idea here is that many of the binary operators actually generate either a placeholder, or a Series or vector. And that can be used as an index, so that df.difference2 < -2 becomes (in essence) a list of the places where that condition is true, and you can then index either df (the whole table) or any of the columns of df, like df.difference2, using that index. It's a fast shorthand for the otherwise-slow python for loop.

Update

Okay, finally, here is a version that vectorizes the "Time-inefficient Loop". I'm just pasting the whole thing in at the bottom, for copying.

The premise is that the Series.isnull() method returns a boolean Series (column) that is true if the contents are "missing" or "invalid" or "bogus." Generally, this means NaN, but it also recognizes Python None, etc.

The tricky part, in pandas, is shifting that column up or down by one to reflect "around"-ness.

That is, I want another boolean column, where col[n-1] is true if col[n] is null. That's my "before a nan" column. And likewise, I want another column where col[n+1] is true if col[n] is null. That's my "after a nan" column.

It turns out I had to take the damn thing apart! I had to reach in, extract the underlying numpy array using the Series.values attribute, so that the pandas index would be discarded. Then a new index is created, starting at 0, and everything works again. (If you don't strip the index, the columns "remember" what their numbers are supposed to be. So even if you delete column[0], the column doesn't shift down. Instead, is knows "I am missing my [0] value, but everyone else is still in the right place!")

Anyway, with that figured out, I was able to build three columns (needlessly - they could probably be parts of an expression) and then merge them together into a fourth column that indicates what you want: the column is True when the row is before, on, or after a nan value.

```<code>missing = df.difference2.isnull()
df['is_nan'] = missing
df['before_nan'] = np.append(missing[1:].values, False)
df['after_nan'] = np.insert(missing[:-1].values, 0, False)
df['around_nan'] = df.is_nan | df.before_nan | df.after_nan
</code>```

Here's the whole thing:

```<code>import numpy as np
import pandas as pd

import time

current_milli_time = lambda: int(round(time.time() * 1000))

def mark(s):
    print("[{}] {}".format(current_milli_time()/1000, s))

# sample data
speed = np.random.uniform(0,25,150000)
next_speed = speed[1:]

# create a dataframe
data_dict = {'speed': speed[:-1],
            'next_speed': next_speed}

df = pd.DataFrame(data_dict)

mark("Got DataFrame")

# calculate difference between the current speed and the next speed
list_of_differences = []

#for i in df.index:
    #difference = df.next_speed[i]-df.speed[i]
    #list_of_differences.append(difference)

#df['difference'] = list_of_differences
#mark("difference 1")

df['difference'] = df['next_speed'] - df['speed']
mark('difference 2')

df['difference2'] = df['next_speed'] - df['speed']

# add 'nan' to data in form of a string.

#for i in range(len(df.difference)):
    ## arbitrary condition
    #if df.difference[i] < -2:
        #df.difference[i] = 'nan'

df.difference[df.difference < -2] = np.nan
mark('nanify')

df.difference2[df.difference2 < -2] = np.nan
mark('nanify 2')

missing = df.difference2.isnull()
df['is_nan'] = missing
df['before_nan'] = np.append(missing[1:].values, False)
df['after_nan'] = np.insert(missing[:-1].values, 0, False)
df['around_nan'] = df.is_nan | df.before_nan | df.after_nan
mark('looped')

#########################################
# THE TIME-INEFFICIENT LOOP

# remove wrong values before and after 'nan'.
for i in  range(len(df)):

    # check if the value is a number to skip computations of the following "if" cases
    if not(isinstance(df.difference[i], str)):
        continue

    # case 1: where there's only one 'nan' surrounded by values.
    # Without this case the algo will miss some wrong values because 'nan' will be removed
    # Example of a series: /1/,nan,/2/,3,4,nan,nan,nan,8,9
    # A number surrounded by slashes e.g. /1/ is a value to be removed
    if df.difference[i] == 'nan' and df.difference[i-1] != 'nan' and df.difference[i+1] != 'nan':
        df.difference[i-1]= 'wrong'
        df.difference[i+1]= 'wrong'

    # case 2: where the following values are 'nan': /1/, nan, nan, 4
    # E.g.: /1/, nan,/2/,3,/4/,nan,nan,nan,8,9
    elif df.difference[i] == 'nan' and df.difference[i+1] == 'nan':
        df.difference[i-1]= 'wrong'

    # case 3: where next value is NOT 'nan'  wrong, nan,nan,4
        # E.g.: /1/, nan,/2/,3,/4/,nan,nan,nan,/8/,9
    elif df.difference[i] == 'nan' and df.difference[i+1] != 'nan':
        df.difference[i+1]= 'wrong'

mark('time-inefficient loop done')
</code>```

Body:
I'm trying to remove wrong values form my data (a series of 15mln values, 700MB). The values to be removed are values next to 'nan' values, e.g.:

Series: /1/,nan,/2/,3,/4/,nan,nan,nan,/8/,9
Numbers surrounded by slashes i.e. /1/,/2/,/4/,/8/ are values, which should be removed.

The problem is that it takes way too long to compute that with the following code that I have:

%%time

import numpy as np
import pandas as pd

# sample data
speed = np.random.uniform(0,25,15000000)
next_speed = speed[1:]

# create a dataframe
data_dict = {'speed': speed[:-1],
            'next_speed': next_speed}

df = pd.DataFrame(data_dict)

# calculate difference between the current speed and the next speed
list_of_differences = []

for i in df.index:
    difference = df.next_speed[i]-df.speed[i]
    list_of_differences.append(difference)

df['difference'] = list_of_differences

# add 'nan' to data in form of a string.

for i in range(len(df.difference)):
    # arbitrary condition
    if df.difference[i] < -2:
        df.difference[i] = 'nan'

#########################################
# THE TIME-INEFFICIENT LOOP

# remove wrong values before and after 'nan'.
for i in  range(len(df)):

    # check if the value is a number to skip computations of the following "if" cases
    if not(isinstance(df.difference[i], str)):
        continue

    # case 1: where there's only one 'nan' surrounded by values.
    # Without this case the algo will miss some wrong values because 'nan' will be removed
    # Example of a series: /1/,nan,/2/,3,4,nan,nan,nan,8,9
    # A number surrounded by slashes e.g. /1/ is a value to be removed
    if df.difference[i] == 'nan' and df.difference[i-1] != 'nan' and df.difference[i+1] != 'nan':
        df.difference[i-1]= 'wrong'
        df.difference[i+1]= 'wrong'

    # case 2: where the following values are 'nan': /1/, nan, nan, 4
    # E.g.: /1/, nan,/2/,3,/4/,nan,nan,nan,8,9
    elif df.difference[i] == 'nan' and df.difference[i+1] == 'nan':
        df.difference[i-1]= 'wrong'

    # case 3: where next value is NOT 'nan'  wrong, nan,nan,4
        # E.g.: /1/, nan,/2/,3,/4/,nan,nan,nan,/8/,9
    elif df.difference[i] == 'nan' and df.difference[i+1] != 'nan':
        df.difference[i+1]= 'wrong'

How to make it more time-efficient?

Body:
This is still a work in progress for me. I knocked 100x off your dummy data size to get down to something I could stand to wait for.

I also added this code at the top of my version:

 import time

current_milli_time = lambda: int(round(time.time() * 1000))

def mark(s):
    print("[{}] {}".format(current_milli_time()/1000, s))

This just prints a string with a time-mark in front of it, to see what's taking so long.

With that done, in your 'difference' column computation, you can replace the manual list generation with a vector operation. This code:

df = pd.DataFrame(data_dict)

mark("Got DataFrame")

# calculate difference between the current speed and the next speed
list_of_differences = []

for i in df.index:
    difference = df.next_speed[i]-df.speed[i]
    list_of_differences.append(difference)

df['difference'] = list_of_differences
mark("difference 1")

df['difference2'] = df['next_speed'] - df['speed']
mark('difference 2')

print(df[:10])

Produces this output:

[1490943913.921] Got DataFrame
[1490943922.094] difference 1
[1490943922.096] difference 2
   next_speed      speed  difference  difference2
0   18.008314  20.182982   -2.174669    -2.174669
1   14.736095  18.008314   -3.272219    -3.272219
2    5.352993  14.736095   -9.383102    -9.383102
3    5.854199   5.352993    0.501206     0.501206
4    2.003826   5.854199   -3.850373    -3.850373
5   12.736061   2.003826   10.732236    10.732236
6    2.512623  12.736061  -10.223438   -10.223438
7   18.224716   2.512623   15.712093    15.712093
8   14.023848  18.224716   -4.200868    -4.200868
9   15.991590  14.023848    1.967741     1.967741

Notice that the two difference columns are the same, but the second version took about 8 seconds less time. (Presumably 800 seconds when you have 100x more data.)

I did the same thing in the 'nanify' process:

df.difference2[df.difference2 < -2] = np.nan

The idea here is that many of the binary operators actually generate either a placeholder, or a Series or vector. And that can be used as an index, so that df.difference2 < -2 becomes (in essence) a list of the places where that condition is true, and you can then index either df (the whole table) or any of the columns of df, like df.difference2, using that index. It's a fast shorthand for the otherwise-slow python for loop.

Update

Okay, finally, here is a version that vectorizes the "Time-inefficient Loop". I'm just pasting the whole thing in at the bottom, for copying.

The premise is that the Series.isnull() method returns a boolean Series (column) that is true if the contents are "missing" or "invalid" or "bogus." Generally, this means NaN, but it also recognizes Python None, etc.

The tricky part, in pandas, is shifting that column up or down by one to reflect "around"-ness.

That is, I want another boolean column, where col[n-1] is true if col[n] is null. That's my "before a nan" column. And likewise, I want another column where col[n+1] is true if col[n] is null. That's my "after a nan" column.

It turns out I had to take the damn thing apart! I had to reach in, extract the underlying numpy array using the Series.values attribute, so that the pandas index would be discarded. Then a new index is created, starting at 0, and everything works again. (If you don't strip the index, the columns "remember" what their numbers are supposed to be. So even if you delete column[0], the column doesn't shift down. Instead, is knows "I am missing my [0] value, but everyone else is still in the right place!")

Anyway, with that figured out, I was able to build three columns (needlessly - they could probably be parts of an expression) and then merge them together into a fourth column that indicates what you want: the column is True when the row is before, on, or after a nan value.

missing = df.difference2.isnull()
df['is_nan'] = missing
df['before_nan'] = np.append(missing[1:].values, False)
df['after_nan'] = np.insert(missing[:-1].values, 0, False)
df['around_nan'] = df.is_nan | df.before_nan | df.after_nan

Here's the whole thing:

import numpy as np
import pandas as pd

import time

current_milli_time = lambda: int(round(time.time() * 1000))

def mark(s):
    print("[{}] {}".format(current_milli_time()/1000, s))

# sample data
speed = np.random.uniform(0,25,150000)
next_speed = speed[1:]

# create a dataframe
data_dict = {'speed': speed[:-1],
            'next_speed': next_speed}

df = pd.DataFrame(data_dict)

mark("Got DataFrame")

# calculate difference between the current speed and the next speed
list_of_differences = []

#for i in df.index:
    #difference = df.next_speed[i]-df.speed[i]
    #list_of_differences.append(difference)

#df['difference'] = list_of_differences
#mark("difference 1")

df['difference'] = df['next_speed'] - df['speed']
mark('difference 2')

df['difference2'] = df['next_speed'] - df['speed']

# add 'nan' to data in form of a string.

#for i in range(len(df.difference)):
    ## arbitrary condition
    #if df.difference[i] < -2:
        #df.difference[i] = 'nan'

df.difference[df.difference < -2] = np.nan
mark('nanify')

df.difference2[df.difference2 < -2] = np.nan
mark('nanify 2')

missing = df.difference2.isnull()
df['is_nan'] = missing
df['before_nan'] = np.append(missing[1:].values, False)
df['after_nan'] = np.insert(missing[:-1].values, 0, False)
df['around_nan'] = df.is_nan | df.before_nan | df.after_nan
mark('looped')

#########################################
# THE TIME-INEFFICIENT LOOP

# remove wrong values before and after 'nan'.
for i in  range(len(df)):

    # check if the value is a number to skip computations of the following "if" cases
    if not(isinstance(df.difference[i], str)):
        continue

    # case 1: where there's only one 'nan' surrounded by values.
    # Without this case the algo will miss some wrong values because 'nan' will be removed
    # Example of a series: /1/,nan,/2/,3,4,nan,nan,nan,8,9
    # A number surrounded by slashes e.g. /1/ is a value to be removed
    if df.difference[i] == 'nan' and df.difference[i-1] != 'nan' and df.difference[i+1] != 'nan':
        df.difference[i-1]= 'wrong'
        df.difference[i+1]= 'wrong'

    # case 2: where the following values are 'nan': /1/, nan, nan, 4
    # E.g.: /1/, nan,/2/,3,/4/,nan,nan,nan,8,9
    elif df.difference[i] == 'nan' and df.difference[i+1] == 'nan':
        df.difference[i-1]= 'wrong'

    # case 3: where next value is NOT 'nan'  wrong, nan,nan,4
        # E.g.: /1/, nan,/2/,3,/4/,nan,nan,nan,/8/,9
    elif df.difference[i] == 'nan' and df.difference[i+1] != 'nan':
        df.difference[i+1]= 'wrong'

mark('time-inefficient loop done')


问:
Error instantiating an interface
The following code fails to compile with message: cannot instantiate type SymmetricKey SymmetricKey is
 an interface.  How do I fix this?

```<code> ByteArrayOutputStream baos = new ByteArrayOutputStream();
 InitializationVector iv = new InitializationVector("helo".getBytes());
 SymmetricKey key = new SymmetricKey("AES_256","key", 0, "key".length());
 OutputStream os = EncryptorFactory.getEncryptorOutputStream(key, baos, "AES/CBC/PKCS5",);
 os.write("somedata".getBytes());
 byte[] encryptedData = baos.toByteArray();
 ByteArrayInputStream bais = new ByteArrayInputStream(encryptedData);
 InputStream is = DecryptorFactory.getDecryptorInputStream(key, bais, "AES/CBC/PKCS5", iv);
</code>```

答:
I solved my problem by using SymmetricKeyFactory</p>

```<code>SymmetricKey key=
    SymmetricKeyFactory.getInstance("AES_256","key".getBytes(), 0, "abc123".length());
</code>```

ContentLicense: CC BY-SA 2.5

Title: Error instantiating an interface

Body:
The following code fails to compile with message: cannot instantiate type SymmetricKey SymmetricKey is
 an interface.  How do I fix this?

 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 InitializationVector iv = new InitializationVector("helo".getBytes());
 SymmetricKey key = new SymmetricKey("AES_256","key", 0, "key".length());
 OutputStream os = EncryptorFactory.getEncryptorOutputStream(key, baos, "AES/CBC/PKCS5",);
 os.write("somedata".getBytes());
 byte[] encryptedData = baos.toByteArray();
 ByteArrayInputStream bais = new ByteArrayInputStream(encryptedData);
 InputStream is = DecryptorFactory.getDecryptorInputStream(key, bais, "AES/CBC/PKCS5", iv);

Body:
I solved my problem by using SymmetricKeyFactory

SymmetricKey key=
    SymmetricKeyFactory.getInstance("AES_256","key".getBytes(), 0, "abc123".length());


问:
How to rename directory and subdirectories recursively in linux?
Let say I have 200 directories and it have variable hierarchy sub-directories, How can I rename the directory and its sub directories using mv command with find or any sort of combination?

```<code>for dir in ./*/; do (i=1; cd "$dir" && for dir in ./*; do printf -v dest %s_%02d "$dir" "$((i++))"; echo mv "$dir" "$dest"; done); done
</code>```

This is for 2 level sub directory, is there more cleaner way to do it for multiple hierarchy? Any other one line command suggestions/ solutions are welcome.

答:
You have two options when you want to do recursive operations in files/directories:

Option 1 : Find

```<code>while IFS= read -r -d '' subd;do
  #do your stuff here with var $subd
done < <(find . -type d -print0)
</code>```

In this case we use find to return only dirs using -type d

We can ask find to return only files using -type f or not to specify any type and both directories and files will be returned.

We also use find option -print0 to force null separation of the find results and thus to ensure correct names handling in case names include special chars like spaces, etc.

Testing:

```<code>$ while IFS= read -r -d '' s;do echo "$s";done < <(find . -type d -print0)
.
./dir1
./dir1/sub1
./dir1/sub1/subsub1
./dir1/sub1/subsub1/subsubsub1
./dir2
./dir2/sub2
</code>```

Option 2 : Using Bash globstar option

```<code>shopt -s globstar
for subd in **/ ; do
  #Do you stuff here with $subd directories
done
</code>```

In this case , the for loop will match all subdirs under current working directory  (operation **/).

You can also ask bash to return both files and folders using

```<code>for sub in ** ;do #your commands;done
  if [[ -d "$sub" ]];then
      #actions for folders
  elif [[ -e "$sub" ]];then
      #actions for files
  else
     #do something else
  fi
done
</code>```

Folders Test:

```<code>$ shopt -s globstar
$ for i in **/ ;do echo "$i";done
dir1/
dir1/sub1/
dir1/sub1/subsub1/
dir1/sub1/subsub1/subsubsub1/
dir2/
dir2/sub2/
</code>```

In your small script, just by enabling shopt -s globstar and by changing your for to for dir in **/;do it seems that work as you expect.

Body:
Let say I have 200 directories and it have variable hierarchy sub-directories, How can I rename the directory and its sub directories using mv command with find or any sort of combination?

for dir in ./*/; do (i=1; cd "$dir" && for dir in ./*; do printf -v dest %s_%02d "$dir" "$((i++))"; echo mv "$dir" "$dest"; done); done

This is for 2 level sub directory, is there more cleaner way to do it for multiple hierarchy? Any other one line command suggestions/ solutions are welcome.

Body:
You have two options when you want to do recursive operations in files/directories:

Option 1 : Find

while IFS= read -r -d '' subd;do
  #do your stuff here with var $subd
done < <(find . -type d -print0)

In this case we use find to return only dirs using -type d

We can ask find to return only files using -type f or not to specify any type and both directories and files will be returned.

We also use find option -print0 to force null separation of the find results and thus to ensure correct names handling in case names include special chars like spaces, etc.

Testing:

$ while IFS= read -r -d '' s;do echo "$s";done < <(find . -type d -print0)
.
./dir1
./dir1/sub1
./dir1/sub1/subsub1
./dir1/sub1/subsub1/subsubsub1
./dir2
./dir2/sub2

Option 2 : Using Bash globstar option

shopt -s globstar
for subd in **/ ; do
  #Do you stuff here with $subd directories
done

In this case , the for loop will match all subdirs under current working directory  (operation **/).

You can also ask bash to return both files and folders using

for sub in ** ;do #your commands;done
  if [[ -d "$sub" ]];then
      #actions for folders
  elif [[ -e "$sub" ]];then
      #actions for files
  else
     #do something else
  fi
done

Folders Test:

$ shopt -s globstar
$ for i in **/ ;do echo "$i";done
dir1/
dir1/sub1/
dir1/sub1/subsub1/
dir1/sub1/subsub1/subsubsub1/
dir2/
dir2/sub2/

In your small script, just by enabling shopt -s globstar and by changing your for to for dir in **/;do it seems that work as you expect.


问:
Is there a PHP function like array_column that only returns single values?
I am looping through instances of associative arrays (these associative arrays themselves are part of an array).

For each array I want to return a value, based on a key.

Currently I have:

```<code>$image_path = array_column($myarray, 'uri');
</code>```

But of course array_column stores its values in a array, which, considering it's only returning 1 value, is useless to me.

Is there an existing function that will allow me to just get a value based off a supplied key?

Eg:

```<code>$image_path = get_keys_value($myarray, 'uri');
</code>```

Example array. This is a very basic example. The real thing has many levels to it:

```<code>$myarray = array
  (
    'instance' => array(
      'type' => 'somedata',
      'content' => somedata',
      'image' => array(
         'name' => 'photo',
         'uri' => 'path/to/file.png'
      ),
    ),
  );
</code>```

Desired outcome:

$image_path contains 'path/to/file.png' string.

答:
Try this,

```<code>function array_column_recursive(array $haystack, $needle)
{
    $found = [];
    array_walk_recursive($haystack, function ($value, $key) use (&$found, $needle) {
        if ($key == $needle) {
            $found[] = $value;
        }
    });
    return $found;
}
echo array_column_recursive($myarray, 'uri')[0];
</code>```

Here is working code.

array_column will work with only 2 level array structure.

Above array will solve your problem.

I hope this will help

Body:
I am looping through instances of associative arrays (these associative arrays themselves are part of an array).

For each array I want to return a value, based on a key.

Currently I have:

$image_path = array_column($myarray, 'uri');

But of course array_column stores its values in a array, which, considering it's only returning 1 value, is useless to me.

Is there an existing function that will allow me to just get a value based off a supplied key?

Eg:

$image_path = get_keys_value($myarray, 'uri');

Example array. This is a very basic example. The real thing has many levels to it:

$myarray = array
  (
    'instance' => array(
      'type' => 'somedata',
      'content' => somedata',
      'image' => array(
         'name' => 'photo',
         'uri' => 'path/to/file.png'
      ),
    ),
  );

Desired outcome:

$image_path contains 'path/to/file.png' string.

Body:
Try this,

function array_column_recursive(array $haystack, $needle)
{
    $found = [];
    array_walk_recursive($haystack, function ($value, $key) use (&$found, $needle) {
        if ($key == $needle) {
            $found[] = $value;
        }
    });
    return $found;
}
echo array_column_recursive($myarray, 'uri')[0];

Here is working code.

array_column will work with only 2 level array structure.

Above array will solve your problem.

I hope this will help


问:
Axillary curve line for a path in Matlab
There is a noisy image as fig a. by reducing image noise finally a smoothspline could fit to the dots as shown in fig b. now it's desire to find two axillary lines both side of the original line like offset (in this case it's better to say outline). how can these lines(yellow and green) position be found?
if there is a simple straight line it would be easy but here is spline.
any idea would be appreciated.

答:
I think this is what you wanted:

```<code>% generate random curve
xy = randi(5,[2,3]);
t = 1:3;
tq = linspace(1,3,100);
xyq = interp1(t',xy',tq','spline');
xx = xyq(:,1);
yy = xyq(:,2);
% get curve's approx. angle in each point
theta = atan2(xyq(2:end,2) - xyq(1:end-1,2),xyq(2:end,1) - xyq(1:end-1,1));
theta(end+1) = theta(end);
% add or subtract 90 degrees to get downward or upward normal angle
tp1 = theta + pi/2;
tp2 = theta - pi/2;
% distance from original curve
d = 0.1;
% compute x-y additions
[xa1,ya1] = pol2cart(tp1,d);
[xa2,ya2] = pol2cart(tp2,d);
% plot curve and its axillary lines
plot(xx,yy,'g')
hold on
plot(xyq(:,1) + xa1,xyq(:,2) + ya1,'b')
plot(xyq(:,1) + xa2,xyq(:,2) + ya2,'r')
legend('orig.','axil._1','axil._2');
</code>```

and you get this:

Body:
I think this is what you wanted:

% generate random curve
xy = randi(5,[2,3]);
t = 1:3;
tq = linspace(1,3,100);
xyq = interp1(t',xy',tq','spline');
xx = xyq(:,1);
yy = xyq(:,2);
% get curve's approx. angle in each point
theta = atan2(xyq(2:end,2) - xyq(1:end-1,2),xyq(2:end,1) - xyq(1:end-1,1));
theta(end+1) = theta(end);
% add or subtract 90 degrees to get downward or upward normal angle
tp1 = theta + pi/2;
tp2 = theta - pi/2;
% distance from original curve
d = 0.1;
% compute x-y additions
[xa1,ya1] = pol2cart(tp1,d);
[xa2,ya2] = pol2cart(tp2,d);
% plot curve and its axillary lines
plot(xx,yy,'g')
hold on
plot(xyq(:,1) + xa1,xyq(:,2) + ya1,'b')
plot(xyq(:,1) + xa2,xyq(:,2) + ya2,'r')
legend('orig.','axil._1','axil._2');

and you get this:


问:
Alternatives for loss functions in python CNTK
I have created a sequential model in CNTK and pass this model into a loss function like the following:

```<code>ce = cross_entropy_with_softmax(model, labels)
</code>```

As mentioned here and as I have multilabel classifier, I want to use a proper loss function. The problem is I can not find any proper document to find these loss functions in Python. Is there any suggestion or sample code for this requirement.

I should notice that I found these alternatives (logistic and weighted logistic) in BrainScript language, but not in Python.

答:
"my data has more than one label (three label) and each label has more than two values (30 different values)"

Do I understand right, you have 3 network outputs and associated labels, and each one is a 1-in-30 classifier? Then it seems you can just add three cross_entropy_with_softmax() values. Is that what you want?

E.g. if the model function returns a triple (ending in something like return combine([z1, z2, z3])), then your criterion function that you pass to Trainer could look like this (if you don't use Python 3, the syntax is a little different):

```<code>from cntk.layers.typing import Tensor, SparseTensor
@Function
def my_criterion(input : Tensor[input_dim], labels1 : SparseTensor[30],
                 labels2 : SparseTensor[30], labels3 : SparseTensor[30]):
    z1, z2, z3 = my_model(input).outputs
    loss = cross_entropy_with_softmax(z1, labels1) + \
           cross_entropy_with_softmax(z2, labels2) + \
           cross_entropy_with_softmax(z3, labels3)
    return loss

learner = ...
trainer = Trainer(None, my_criterion, learner)

# in MB loop:
input_mb, L1_mb, L2_mb, L3_mb = my_next_minibatch()
trainer.train_minibatch(my_criterion.argument_map(input_mb, L1_mb, L2_mb, L3_mb))
</code>```

Body:
I have created a sequential model in CNTK and pass this model into a loss function like the following:

ce = cross_entropy_with_softmax(model, labels)

As mentioned here and as I have multilabel classifier, I want to use a proper loss function. The problem is I can not find any proper document to find these loss functions in Python. Is there any suggestion or sample code for this requirement.

I should notice that I found these alternatives (logistic and weighted logistic) in BrainScript language, but not in Python.

Body:
"my data has more than one label (three label) and each label has more than two values (30 different values)"

Do I understand right, you have 3 network outputs and associated labels, and each one is a 1-in-30 classifier? Then it seems you can just add three cross_entropy_with_softmax() values. Is that what you want?

E.g. if the model function returns a triple (ending in something like return combine([z1, z2, z3])), then your criterion function that you pass to Trainer could look like this (if you don't use Python 3, the syntax is a little different):

from cntk.layers.typing import Tensor, SparseTensor
@Function
def my_criterion(input : Tensor[input_dim], labels1 : SparseTensor[30],
                 labels2 : SparseTensor[30], labels3 : SparseTensor[30]):
    z1, z2, z3 = my_model(input).outputs
    loss = cross_entropy_with_softmax(z1, labels1) + \
           cross_entropy_with_softmax(z2, labels2) + \
           cross_entropy_with_softmax(z3, labels3)
    return loss

learner = ...
trainer = Trainer(None, my_criterion, learner)

# in MB loop:
input_mb, L1_mb, L2_mb, L3_mb = my_next_minibatch()
trainer.train_minibatch(my_criterion.argument_map(input_mb, L1_mb, L2_mb, L3_mb))


问:
Weird Behavior when using between? method for dates
Open up a Rails console and enter this:

```<code>2.weeks.ago.between? 2.weeks.ago, 1.week.ago
</code>```

Did it give you true or false? No really, try it a few more times and it will give you different answers.

Now, I'm thinking that because we're comparing 2.weeks.ago with 2.weeks.ago, the time between evaluating the two statements is causing this behavior.

I can't say for sure, but I am guessing that the between? method is not inclusive and so if a few milliseconds elapsed between the two statements, the above code will evaluate to true because it will be in between the two dates compared.

However, if the CPU manages to process this quickly enough such that the time elapsed is ignorable, then it will evaluate to false.

Can anyone shed some light on this? It is an edge case at best in a system where this might be critical, but it was giving me a headache when my tests passed and failed seemingly at random.

Oddly enough, this doesn't happen when doing:

```<code> Date.yesterday.between? Date.yesterday, Date.tomorrow
</code>```

答:
tvanfosson, hit it on the head.

2.weeks.ago gives you a time exactly two weeks from the execution to the millisecond. So evaluating it twice could provide two different times.

Doing something like the following would give you consistent results:

```
two_weeks_ago = 2.weeks.ago
two_weeks_ago.between? two_weeks_ago, 1.week.ago
```

OwnerDisplayName: Jaryl

Body:
Open up a Rails console and enter this:

2.weeks.ago.between? 2.weeks.ago, 1.week.ago

Did it give you true or false? No really, try it a few more times and it will give you different answers.

Now, I'm thinking that because we're comparing 2.weeks.ago with 2.weeks.ago, the time between evaluating the two statements is causing this behavior.

I can't say for sure, but I am guessing that the between? method is not inclusive and so if a few milliseconds elapsed between the two statements, the above code will evaluate to true because it will be in between the two dates compared.

However, if the CPU manages to process this quickly enough such that the time elapsed is ignorable, then it will evaluate to false.

Can anyone shed some light on this? It is an edge case at best in a system where this might be critical, but it was giving me a headache when my tests passed and failed seemingly at random.

Oddly enough, this doesn't happen when doing:

 Date.yesterday.between? Date.yesterday, Date.tomorrow

LastEditorDisplayName: Jaryl

Body:
tvanfosson, hit it on the head.

2.weeks.ago gives you a time exactly two weeks from the execution to the millisecond. So evaluating it twice could provide two different times.

Doing something like the following would give you consistent results:

two_weeks_ago = 2.weeks.ago
two_weeks_ago.between? two_weeks_ago, 1.week.ago

OwnerDisplayName: Tony Fontenot


问:
using javascript/jQuery to show certain elements on certain dates?
Pretty much as the title. I have been asked if it is possible to have a specific banner shown in a section on a website on different days without any external user input.

My first thoughts are the use of javascript/jquery. We are limited with the functionality however as the site is controlled by the horror that is Netsuite.

Any help/ideas are appreciated :)

-Wayne

答:
This answer assumes you want a different banner image for each day of the week.

If you aren't able to update the banner in the backend then it would be possible just to have all the banners on the page, hidden with the CSS display: none.

Then just use something like:

```<code>var date = new Date();
$("#banner" + date.getDay()).show();
</code>```

This will work if you have 7 elements named banner0 for Sunday, banner1 for Monday, etc.

Alternatively, if you just want to change the banner image then you could set your CSS like so:

```<code>div#banner { background-image: url(default.jpg)} // Common styling
div#banner.day0 { background-image: url(image0.jpg); } // Image for Sunday
div#banner.day1 { background-image: url(image1.jpg); } // Image for Monday
div#banner.day2 { background-image: url(image2.jpg); } // Image for Tuesday
</code>```

Then your jQuery could look like:

```<code>var date = new Date();
$("div#banner").addClass("day" + date.getDay());
</code>```

Of course, the issue with both these options are that you need to have a different banner for each day. They're just some ways you can do it (but definitely not the only ways)

Body:
This answer assumes you want a different banner image for each day of the week.

If you aren't able to update the banner in the backend then it would be possible just to have all the banners on the page, hidden with the CSS display: none.

Then just use something like:

var date = new Date();
$("#banner" + date.getDay()).show();

This will work if you have 7 elements named banner0 for Sunday, banner1 for Monday, etc.

Alternatively, if you just want to change the banner image then you could set your CSS like so:

div#banner { background-image: url(default.jpg)} // Common styling
div#banner.day0 { background-image: url(image0.jpg); } // Image for Sunday
div#banner.day1 { background-image: url(image1.jpg); } // Image for Monday
div#banner.day2 { background-image: url(image2.jpg); } // Image for Tuesday

Then your jQuery could look like:

var date = new Date();
$("div#banner").addClass("day" + date.getDay());

Of course, the issue with both these options are that you need to have a different banner for each day. They're just some ways you can do it (but definitely not the only ways)


问:
python create a list combined with an append
I'm trying to do something like:

```<code>([0.01]*9).append(0.91)
</code>```

to get to:

```<code>[0.01, 0.01, 0.01, 0.01, ...., 0.91]
</code>```

Is there a way to do this in one line rather than:

```<code>temp = [0.01]*9
temp = temp.append(0.91)
</code>```

答:
Simply concatenate to the list</p>

```<code> temp = [0.01]*9 + [0.91]
</code>```

Body:
I'm trying to do something like:

([0.01]*9).append(0.91)

to get to:

[0.01, 0.01, 0.01, 0.01, ...., 0.91]

Is there a way to do this in one line rather than:

temp = [0.01]*9
temp = temp.append(0.91)

Body:
Simply concatenate to the list

 temp = [0.01]*9 + [0.91]


问:
how to reload data after used $emit in angular js
i have some question about angularJs.. how to re init some variable in scope after i used emit . example code:

$scope.uiConfig = {title: "example"};

$scope.$emit('myCostumCalendar', 'Data to send');

$scope.$on('myCostumCalendar', function () {
  $scope.uiConfig = {title: "new Title"};
});```

答:
The below code is not giving proper result :

inherited scope value will not give proper result in $ emit function and first time emit function will not work in angular js as expected.

Plz any clarify it .


问:
Can I combine values from C# variable and XML
I have a requirement where the email body should contain textbox inputted value. I have predefined contents in email body of xml format but inputted value from the textbox should append to the xml & with this inputted value whole email body should display in the placeholder.

```<code><?xml version="1.0" encoding="UTF-8"?>
<EMAIL>
  <ADDR To="abcd@abcd.com" Sub="Email body"></ADDR>
  <BODY>Data available at <br />**url<br /><br />Thanks</BODY>
</EMAIL>
</code>```

In C#,

```<code> public void EmailDefaultValue(string url)
    {
        XElement xmlMap = XElement.Load(HttpContext.Current.Server.MapPath("~/Config Files/EmailBody.xml"));
        txtToEmail.Value = (from item in xmlMap.Elements("ADDR")
                            select item.Attribute("To").Value).Single();
        txtSubject.Value = (from item in xmlMap.Elements("ADDR")
                            select item.Attribute("Sub").Value).Single();
        txtEmailBody.Text =string.Format((from item in xmlMap.Elements("BODY")
                             select item.Value).Single(),url);
    }
</code>```

in output:
a text **url displayed instead of reading the url variable value and appending.
where am i missing and what?

答:
Part of your string that need to be substituted by String.Format() has to be in a certain format, for example, {0}. Replace **url in your XML template to {0} :

```<code><BODY>Data available at <br />{0}<br /><br />Thanks</BODY>
</code>```

Then your current code should work. Quick test : https://dotnetfiddle.net/U5LHep

Body:
I have a requirement where the email body should contain textbox inputted value. I have predefined contents in email body of xml format but inputted value from the textbox should append to the xml & with this inputted value whole email body should display in the placeholder.

<?xml version="1.0" encoding="UTF-8"?>
<EMAIL>
  <ADDR To="abcd@abcd.com" Sub="Email body"></ADDR>
  Data available at
**url

Thanks
</EMAIL>

In C#,

 public void EmailDefaultValue(string url)
    {
        XElement xmlMap = XElement.Load(HttpContext.Current.Server.MapPath("~/Config Files/EmailBody.xml"));
        txtToEmail.Value = (from item in xmlMap.Elements("ADDR")
                            select item.Attribute("To").Value).Single();
        txtSubject.Value = (from item in xmlMap.Elements("ADDR")
                            select item.Attribute("Sub").Value).Single();
        txtEmailBody.Text =string.Format((from item in xmlMap.Elements("BODY")
                             select item.Value).Single(),url);
    }

in output:
a text **url displayed instead of reading the url variable value and appending.
where am i missing and what?

Body:
Part of your string that need to be substituted by String.Format() has to be in a certain format, for example, {0}. Replace **url in your XML template to {0} :

<BODY>Data available at &lt;br /&gt;{0}&lt;br /&gt;&lt;br /&gt;Thanks</BODY>

Then your current code should work. Quick test : https://dotnetfiddle.net/U5LHep


问:
Bootstrap Datepicker doesn't restrict value by min and max dates
I need to limit the maximum date by today date, so I use the next code:

```<code><div class="datepicker">
    @Html.TextBoxFor(m => m.Birthdate, "{0:dd.MM.yyyy}", new { @class = "form-control", @style="max-width: 240px;" })
</div>
<script type="text/javascript">

    $(function () {
        $('.datepicker input').datepicker({
            language: "ru",
            autoclose: true,
            format: "dd.mm.yyyy",
            todayHighlight: true,
            maxDate: new Date()
        });
    });

</script>
</code>```

Due to some problems between different browsers I use a custom datevalidator also:

```<code>jQuery.validator.methods.date = function (value, element) {
    var pattern = new RegExp('^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$');
    return this.optional(element) || pattern.test(value);
}
</code>```

As I wrote in the title a restriction by min and max dates doesn't work (I tried to set a min date too). I don't sure but maybe it is due to a cutom validation code. But how do I need to change it then?

P.S. Im sorry if my question is too easy but I don't know much JS.

答:
Using startDate and endDate you can set

$(function () {
        $('.datepicker input').datepicker({
            language: "ru",
            autoclose: true,
            format: "dd.mm.yyyy",
            todayHighlight: true,
            startDate : new Date('2017-03-10'),
            endDate : new Date()
        });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" rel="stylesheet"/>

<div class="datepicker">
<input type='text' id='Birthdate'/>
</div></code>```

Body:
I need to limit the maximum date by today date, so I use the next code:

    @Html.TextBoxFor(m => m.Birthdate, "{0:dd.MM.yyyy}", new { @class = "form-control", @style="max-width: 240px;" })

Due to some problems between different browsers I use a custom datevalidator also:

jQuery.validator.methods.date = function (value, element) {
    var pattern = new RegExp('^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$');
    return this.optional(element) || pattern.test(value);
}

As I wrote in the title a restriction by min and max dates doesn't work (I tried to set a min date too). I don't sure but maybe it is due to a cutom validation code. But how do I need to change it then?

P.S. Im sorry if my question is too easy but I don't know much JS.

Body:
Using startDate and endDate you can set

$(function () {
        $('.datepicker input').datepicker({
            language: "ru",
            autoclose: true,
            format: "dd.mm.yyyy",
            todayHighlight: true,
            startDate : new Date('2017-03-10'),
            endDate : new Date()
        });
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" rel="stylesheet"/>

<div class="datepicker">
<input type='text' id='Birthdate'/>
</div>


问:
How to apply alpha for parent layout without effecting it's child elements
I have Come across of a new requirement that am applying alpha for my parent layout using Frame layout. But what is the problem is I don't want to apply it for some of it's child elements like TextViews. How can I get this requirement.</p>

```<code><FrameLayout
            android:layout_width="fill_parent"
            android:orientation="vertical"
            android:layout_height="match_parent"
            android:minWidth="25px"
            android:minHeight="25px"
            android:alpha="0.2"
            android:layout_marginBottom="70dp"
            android:background="@drawable/login_border">
            <LinearLayout
                android:layout_width="fill_parent"
                android:orientation="vertical"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_margin="0.7dp"
                android:layout_gravity="center_vertical"
                android:id="@+id/linearLayout4"
                android:background="#575757">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:layout_marginRight="25dp"
                    android:layout_marginLeft="25dp"
                    android:id="@+id/linearLayout5">
                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:orientation="vertical"
                        android:layout_gravity="center"
                        android:layout_height="wrap_content"
                        android:id="@+id/linearLayout6">
                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_gravity="center"
                            android:id="@+id/countryselect"
                            android:layout_height="wrap_content">
                            <TextView
                                android:layout_width="wrap_content"
                                android:text="+"
                                android:gravity="left"
                                style="@style/txtphonenumerSize"
                                android:id="@+id/txtPluseCode"
                                android:textColor="#ffffff"
                                android:layout_alignParentLeft="true"
                                android:layout_height="wrap_content"
                                android:padding="4dp" />
                            <TextView
                                android:id="@+id/txtCountryCode"
                                android:text="91"
                                android:layout_height="wrap_content"
                                android:layout_width="wrap_content"
                                android:maxLength="3"
                                android:singleLine="true"
                                android:textColor="#ffffff"
                                android:textSize="17dp"
                                android:paddingRight="10dp" />
                        </LinearLayout>
                    </LinearLayout>
                    <View
                        android:layout_width="0.5dp"
                        android:background="#ffffff"
                        android:layout_height="match_parent"
                        android:id="@+id/view1" />
                    <EditText
                        android:layout_width="match_parent"
                        android:textSize="16dp"
                        android:hint="Mobile Number"
                        android:id="@+id/txtMobileNumber"
                        android:gravity="left"
                        android:textColor="#ffffff"
                        android:maxLength="10"
                        android:textColorHint="#f9f9f9"
                        android:singleLine="true"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:background="@android:color/transparent"
                        android:padding="10dp">
                        <requestFocus
                            android:id="@+id/requestFocus2" />
                    </EditText>
                </LinearLayout>
                <View
                    android:layout_width="match_parent"
                    android:background="#ffffff"
                    android:layout_height="0.5dp"
                    android:id="@+id/view2" />
                <EditText
                    android:layout_width="fill_parent"
                    android:textSize="16dp"
                    android:gravity="left"
                    android:textColor="#ffffff"
                    android:textColorHint="#eeeded"
                    android:id="@+id/txtName"
                    android:maxLength="50"
                    android:singleLine="true"
                    android:layout_height="wrap_content"
                    android:hint="Name"
                    android:background="@android:color/transparent"
                    android:padding="10dp"
                    android:textStyle="bold" />
            </LinearLayout>
        </FrameLayout>
</code>```

答:
You can try this:

```<code>yourParentView.getBackground().setAlpha(50);
</code>```

I have set the opacity to 50, but you can use something between 0(fully transparent) or 255 (completely opaque).

Hope it helps.

Body:
I have Come across of a new requirement that am applying alpha for my parent layout using Frame layout. But what is the problem is I don't want to apply it for some of it's child elements like TextViews. How can I get this requirement.

<FrameLayout
            android:layout_width="fill_parent"
            android:orientation="vertical"
            android:layout_height="match_parent"
            android:minWidth="25px"
            android:minHeight="25px"
            android:alpha="0.2"
            android:layout_marginBottom="70dp"
            android:background="@drawable/login_border">
            <LinearLayout
                android:layout_width="fill_parent"
                android:orientation="vertical"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_margin="0.7dp"
                android:layout_gravity="center_vertical"
                android:id="@+id/linearLayout4"
                android:background="#575757">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:layout_marginRight="25dp"
                    android:layout_marginLeft="25dp"
                    android:id="@+id/linearLayout5">
                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:orientation="vertical"
                        android:layout_gravity="center"
                        android:layout_height="wrap_content"
                        android:id="@+id/linearLayout6">
                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_gravity="center"
                            android:id="@+id/countryselect"
                            android:layout_height="wrap_content">
                            <TextView
                                android:layout_width="wrap_content"
                                android:text="+"
                                android:gravity="left"
                                style="@style/txtphonenumerSize"
                                android:id="@+id/txtPluseCode"
                                android:textColor="#ffffff"
                                android:layout_alignParentLeft="true"
                                android:layout_height="wrap_content"
                                android:padding="4dp" />
                            <TextView
                                android:id="@+id/txtCountryCode"
                                android:text="91"
                                android:layout_height="wrap_content"
                                android:layout_width="wrap_content"
                                android:maxLength="3"
                                android:singleLine="true"
                                android:textColor="#ffffff"
                                android:textSize="17dp"
                                android:paddingRight="10dp" />
                        </LinearLayout>
                    </LinearLayout>
                    <View
                        android:layout_width="0.5dp"
                        android:background="#ffffff"
                        android:layout_height="match_parent"
                        android:id="@+id/view1" />
                    <EditText
                        android:layout_width="match_parent"
                        android:textSize="16dp"
                        android:hint="Mobile Number"
                        android:id="@+id/txtMobileNumber"
                        android:gravity="left"
                        android:textColor="#ffffff"
                        android:maxLength="10"
                        android:textColorHint="#f9f9f9"
                        android:singleLine="true"
                        android:layout_height="wrap_content"
                        android:inputType="number"
                        android:background="@android:color/transparent"
                        android:padding="10dp">
                        <requestFocus
                            android:id="@+id/requestFocus2" />
                    </EditText>
                </LinearLayout>
                <View
                    android:layout_width="match_parent"
                    android:background="#ffffff"
                    android:layout_height="0.5dp"
                    android:id="@+id/view2" />
                <EditText
                    android:layout_width="fill_parent"
                    android:textSize="16dp"
                    android:gravity="left"
                    android:textColor="#ffffff"
                    android:textColorHint="#eeeded"
                    android:id="@+id/txtName"
                    android:maxLength="50"
                    android:singleLine="true"
                    android:layout_height="wrap_content"
                    android:hint="Name"
                    android:background="@android:color/transparent"
                    android:padding="10dp"
                    android:textStyle="bold" />
            </LinearLayout>
        </FrameLayout>

Body:
You can try this:

yourParentView.getBackground().setAlpha(50);

I have set the opacity to 50, but you can use something between 0(fully transparent) or 255 (completely opaque).

Hope it helps.


问:
Converting string to byte array in C# (CSV)
I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] by splitting the string (similar to a CSV string).

```<code>public string ByteArrayToString(byte[] byteArray,string s)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        s += byteArray[i].ToString() + ";";
    }
    s = s.Substring(0, s.Length - 1);
    return s;
}
</code>```

How could I write a function to convert this string to that byte array again?

答: Consider using Split String</p>

Body:
I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] by splitting the string (similar to a CSV string).

public string ByteArrayToString(byte[] byteArray,string s)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        s += byteArray[i].ToString() + ";";
    }
    s = s.Substring(0, s.Length - 1);
    return s;
}

How could I write a function to convert this string to that byte array again?

Body: Consider using Split String


问:
Arduino consuming lots of data from firebase
I am working on Arduino-firebase home automation project.
Now, Firebase data changed through mobile application and Arduino Esp8266 model reads data from firebase. So every time in loop it calls

```<code> FirebaseObject firebaseObject=Firebase.get(path_command);
</code>```

and it consumes data  continuously .
So here is my question, Is there any way to get data only when it is changed on firebase server?.

I have tried below code, but it crashes device at

if (Firebase.available())

```<code>Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.stream("/devices/_18_fe_34_d6_9_4f_/command");
if (Firebase.failed()) {
    Serial.println("streaming error");
    Serial.println(Firebase.error());
  }

  if (Firebase.available()) {
      FirebaseObject firebaseObject = Firebase.readEvent();
      String deviceToken=firebaseObject.getString("device_token");
        Serial.println(deviceToken);
  }
</code>```

Please guide me if better solution available, Thanks you.

答:
We have found the solution for the heavy Data usage.
Previously we were getting all json array using below code.

```<code> FirebaseObject firebaseObject=Firebase.get(path_command);
</code>```

Which consumes several byte or Kb data.
while now we are checking it first that is any change made in data by extra flag
Version. and it is incremental.
We have store it in our database for each node level and each time data updates we need to change it by incrementing  it.
Now we need to check version before getting all json array as below way

```<code>   int version =Firebase.getInt(version_path);
       if(version!=previosVersion)
              FirebaseObject firebaseObject=Firebase.get(path_command);
</code>```

. if we are getting version   difference then only we need to get json object.
Before that in an hour Arduino was consuming around 3 to 5 MB per hour and now it is consuming 700-800 KB per hour. still we are look for best optimization.
thanks.

Body:
I am working on Arduino-firebase home automation project.
Now, Firebase data changed through mobile application and Arduino Esp8266 model reads data from firebase. So every time in loop it calls

 FirebaseObject firebaseObject=Firebase.get(path_command);

and it consumes data  continuously .
So here is my question, Is there any way to get data only when it is changed on firebase server?.

I have tried below code, but it crashes device at

if (Firebase.available())

Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.stream("/devices/_18_fe_34_d6_9_4f_/command");
if (Firebase.failed()) {
    Serial.println("streaming error");
    Serial.println(Firebase.error());
  }

  if (Firebase.available()) {
      FirebaseObject firebaseObject = Firebase.readEvent();
      String deviceToken=firebaseObject.getString("device_token");
        Serial.println(deviceToken);
  }

Please guide me if better solution available, Thanks you.

Body:
We have found the solution for the heavy Data usage.
Previously we were getting all json array using below code.

 FirebaseObject firebaseObject=Firebase.get(path_command);

Which consumes several byte or Kb data.
while now we are checking it first that is any change made in data by extra flag
Version. and it is incremental.
We have store it in our database for each node level and each time data updates we need to change it by incrementing  it.
Now we need to check version before getting all json array as below way

   int version =Firebase.getInt(version_path);
       if(version!=previosVersion)
              FirebaseObject firebaseObject=Firebase.get(path_command);

. if we are getting version   difference then only we need to get json object.
Before that in an hour Arduino was consuming around 3 to 5 MB per hour and now it is consuming 700-800 KB per hour. still we are look for best optimization.
thanks.


问:
how to optimize the following mysql query
I  have  a trouble in the mysql query . the query is following.

```<code>SELECT *
FROM group
WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6);
</code>```

how can I  optimize the query  to  which maybe can drop the OR word . thanks.

also,  the query  may be  extended like follow .

```<code>SELECT *
    FROM group
    WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
    OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6)
    OR     ... ;
</code>```

can someone explain about the Train of thought of  The solution， thanks very much.

答:
The query looks fine as is. Sometimes it is the case that you want one or another condition met. It is the optimizer's job to find the best way to execute the query.

You can try help the optimizer, but that shouldn't actually be necessary, so do this only if you really have performance issues.

Your query could be written as

```<code>SELECT *
FROM group
WHERE  (level = 3 AND  last_time BETWEEN  0 AND 3)
OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6);
</code>```

because of overlapping criteria, but I doubt that would help the optimizer much.

You could also do:

```<code>SELECT *
FROM group
WHERE Level in (3,4,5,6,7)
AND last_time BETWEEN 0 AND 6
AND
(
  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
OR
  (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6)
);
</code>```

So you'd list all values in question first (there is no condition that requires a level not in 3-7, and there is no condition requiring last_time outside 0-6). Only then list the single conditions. This may or may not help the optimizer.

In any way you should have a composite index on level + last_time. Whether using this index or doing a full table scan is faster depends on the data, but you should offer such index anyway.

Body:
I  have  a trouble in the mysql query . the query is following.

SELECT *
FROM group
WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6);

how can I  optimize the query  to  which maybe can drop the OR word . thanks.

also,  the query  may be  extended like follow .

SELECT *
    FROM group
    WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
    OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6)
    OR     ... ;

can someone explain about the Train of thought of  The solution， thanks very much.

Body:
The query looks fine as is. Sometimes it is the case that you want one or another condition met. It is the optimizer's job to find the best way to execute the query.

You can try help the optimizer, but that shouldn't actually be necessary, so do this only if you really have performance issues.

Your query could be written as

SELECT *
FROM group
WHERE  (level = 3 AND  last_time BETWEEN  0 AND 3)
OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6);

because of overlapping criteria, but I doubt that would help the optimizer much.

You could also do:

SELECT *
FROM group
WHERE Level in (3,4,5,6,7)
AND last_time BETWEEN 0 AND 6
AND
(
  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
OR
  (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6)
);

So you'd list all values in question first (there is no condition that requires a level not in 3-7, and there is no condition requiring last_time outside 0-6). Only then list the single conditions. This may or may not help the optimizer.

In any way you should have a composite index on level + last_time. Whether using this index or doing a full table scan is faster depends on the data, but you should offer such index anyway.


问:
How detect which sprites I touch
I'm generating a grid of bricks (SKSpriteNode) in a for loop like this:

```<code>for row in 0..<numRows
    {
        for col in 0..<numColumns
        {
            let brick = SKSpriteNode(color: UIColor.white, size: CGSize(width: brickWidth, height: brickHeight))

            brick.anchorPoint = CGPoint.zero
            brick.name = "brick_d"
            brick.position = CGPoint(x: brickFirstXPosition + col * 65, y: brickFirstYPosition + row * 65)

            self.addChild(brick)
        }
    }
</code>```

Now I don't know how distinguish one node from another, I have to do this according to their different position or something else?
Practically I need to touch one specific node with a touchesBegan func. for doing things according to the node properties (bg, image contained, etc.)

答:
Use touchesBegan():

```<code>    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        let touch = touches.first // get the first touch
        let touchedNode = selectNodeForTouch(touch.location(in: self))
        // do stuff with your 'touchedNode'
    }
</code>```

Title: How detect which sprites I touch

Body:
I'm generating a grid of bricks (SKSpriteNode) in a for loop like this:

for row in 0..<numRows
    {
        for col in 0..<numColumns
        {
            let brick = SKSpriteNode(color: UIColor.white, size: CGSize(width: brickWidth, height: brickHeight))

            brick.anchorPoint = CGPoint.zero
            brick.name = "brick_d"
            brick.position = CGPoint(x: brickFirstXPosition + col * 65, y: brickFirstYPosition + row * 65)

            self.addChild(brick)
        }
    }

Now I don't know how distinguish one node from another, I have to do this according to their different position or something else?
Practically I need to touch one specific node with a touchesBegan func. for doing things according to the node properties (bg, image contained, etc.)

Body:
Use touchesBegan():

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        let touch = touches.first // get the first touch
        let touchedNode = selectNodeForTouch(touch.location(in: self))
        // do stuff with your 'touchedNode'
    }


问:
I want to insert my own view or layout inside expandable List view
I need a little help in expandable list view. When the header is clicked, I need to show a list of information, but not in the format of list. I need to use my own view inside like this.

Example Header 1(On click-expands)

```<code>    Name:
    DOB:
    Nationality:
    Languages Known:
                                 Submit(Button)
</code>```

Header 2 (On click-expands)

```<code>    Name:
    DOB:
    Nationality:
    Languages Known:
                                 Submit(Button)
</code>```

This is what I want to achieve. Please somebody help. Is there any other way to achieve this. Thanks in advance

答:
You can create your own layout. Then it can be set in your adapter class like:

```<code>@Override
    public View getChildView(int groupPosition, final int childPosition,
                             boolean isLastChild, View view, ViewGroup parent) {

        if (view == null) {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.Your_layout, null);
        }

        return view;
    }
</code>```

For more information follow this link:
http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/

Body:
I need a little help in expandable list view. When the header is clicked, I need to show a list of information, but not in the format of list. I need to use my own view inside like this.

Example Header 1(On click-expands)

    Name:
    DOB:
    Nationality:
    Languages Known:
                                 Submit(Button)

Header 2 (On click-expands)

    Name:
    DOB:
    Nationality:
    Languages Known:
                                 Submit(Button)

This is what I want to achieve. Please somebody help. Is there any other way to achieve this. Thanks in advance

Body:
You can create your own layout. Then it can be set in your adapter class like:

@Override
    public View getChildView(int groupPosition, final int childPosition,
                             boolean isLastChild, View view, ViewGroup parent) {

        if (view == null) {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.Your_layout, null);
        }

        return view;
    }

For more information follow this link:
http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/


问:
Q: Angular2: 'switchMap' does not exist on type 'Observable<Params>'
I am learning Angular2, and following the "Tour of Heroes" example, when I setup a detail page for routing, I got this compile error from webpack:

```<code>ERROR in ./ts/router/route-hero-detail.component.ts
(25,23): error TS2339: Property 'switchMap' does not exist on type 'Observable<Params>'.
</code>```

I'm using the webpack to manage the package thing,

below is the JS code:

import 'rxjs/add/operator/switchMap';
import { Component, OnInit }      from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location }               from '@angular/common';

import { Hero }         from '../hero';
import { HeroService }  from '../hero.service';
@Component({
  moduleId: module.id,
  selector: 'my-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: [ './hero-detail.component.css' ]
})
export class RouteHeroDetailComponent implements OnInit {
  hero: Hero;

  constructor(
    private heroService: HeroService,
    private route: ActivatedRoute,
    private location: Location
  ) {}

  ngOnInit(): void {

    this.route.params.switchMap((params: Params) => this.heroService.getHero(+params['id']))
      .subscribe((hero: Hero) => this.hero = hero);
  }

  goBack(): void {
    this.location.back();
  }
}```
</div>
</div>
</p>

<p><strong>package.json:</strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "name": "environment",
  "version": "1.0.0",
  "description": "I will show you how to set up angular2 development environment",
  "keywords": [
    "angular2",
    "environment"
  ],
  "scripts": {
    "start": "webpack-dev-server --hot--host 0.0.0.0"
  },
  "author": "Howard.Zuo",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "^2.4.5",
    "@angular/compiler": "^2.4.5",
    "@angular/core": "^2.4.5",
    "@angular/forms": "^2.4.5",
    "@angular/platform-browser": "^2.4.5",
    "@angular/platform-browser-dynamic": "^2.4.5",
    "@angular/router": "^3.4.8",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-alpha.20",
    "@types/node": "^7.0.5",
    "bootstrap": "^4.0.0-alpha.6",
    "core-js": "^2.4.1",
    "rxjs": "5.0.3",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@types/core-js": "^0.9.35",
    "ts-loader": "^2.0.0",
    "typescript": "^2.1.5",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^2.2.0"
  }
}</code>```

webpack.config.js:

const path = require('path');

module.exports = {
    entry: {
        index: "./ts/index.ts"
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: 'dist/'
    },
    module: {
        exprContextCritical: false,
        rules: [
            {
                test: /\.ts$/,
                use: ['ts-loader']
            }
        ]
    },
    resolve: {
        extensions: [
            '.js',
            '.ts'
        ]
    }
};```
</div>
</div>
</p>

<p><strong>HeroService.ts:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {Injectable} from '@angular/core';
import {Hero} from './hero';
import {HEROES} from './mock-heroes';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HeroService {

    getHeroes() : Promise<Hero[]>{
    return Promise.resolve(HEROES);
  }

   getHero(id: number): Promise<Hero> {
      return this.getHeroes()
               .then(heroes => heroes.find(hero => hero.id === id));
    }

}</code>```

答:
You need to import the switchMap operator:

import 'rxjs/add/operator/switchMap';

update for rxjs >=5.5.0:

for rxjs@5.5.0 or higher it's recommended to use the pipe operator instead of augmentation:

```<code>import { switchMap } from 'rxjs/operators';

\\...

this.route.params.pipe(switchMap((params: Params) => /*... */))
  .subscribe(/*... */);
\\...
</code>```

(this avoids side effects and enable better bundle size optimization)

Body:
I am learning Angular2, and following the "Tour of Heroes" example, when I setup a detail page for routing, I got this compile error from webpack:

ERROR in ./ts/router/route-hero-detail.component.ts
(25,23): error TS2339: Property 'switchMap' does not exist on type 'Observable<Params>'.

I'm using the webpack to manage the package thing,

below is the JS code:

import 'rxjs/add/operator/switchMap';
import { Component, OnInit }      from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location }               from '@angular/common';

import { Hero }         from '../hero';
import { HeroService }  from '../hero.service';
@Component({
  moduleId: module.id,
  selector: 'my-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: [ './hero-detail.component.css' ]
})
export class RouteHeroDetailComponent implements OnInit {
  hero: Hero;

  constructor(
    private heroService: HeroService,
    private route: ActivatedRoute,
    private location: Location
  ) {}

  ngOnInit(): void {

    this.route.params.switchMap((params: Params) => this.heroService.getHero(+params['id']))
      .subscribe((hero: Hero) => this.hero = hero);
  }

  goBack(): void {
    this.location.back();
  }
}

package.json:

{
  "name": "environment",
  "version": "1.0.0",
  "description": "I will show you how to set up angular2 development environment",
  "keywords": [
    "angular2",
    "environment"
  ],
  "scripts": {
    "start": "webpack-dev-server --hot--host 0.0.0.0"
  },
  "author": "Howard.Zuo",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "^2.4.5",
    "@angular/compiler": "^2.4.5",
    "@angular/core": "^2.4.5",
    "@angular/forms": "^2.4.5",
    "@angular/platform-browser": "^2.4.5",
    "@angular/platform-browser-dynamic": "^2.4.5",
    "@angular/router": "^3.4.8",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-alpha.20",
    "@types/node": "^7.0.5",
    "bootstrap": "^4.0.0-alpha.6",
    "core-js": "^2.4.1",
    "rxjs": "5.0.3",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@types/core-js": "^0.9.35",
    "ts-loader": "^2.0.0",
    "typescript": "^2.1.5",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^2.2.0"
  }
}

webpack.config.js:

const path = require('path');

module.exports = {
    entry: {
        index: "./ts/index.ts"
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: 'dist/'
    },
    module: {
        exprContextCritical: false,
        rules: [
            {
                test: /\.ts$/,
                use: ['ts-loader']
            }
        ]
    },
    resolve: {
        extensions: [
            '.js',
            '.ts'
        ]
    }
};

HeroService.ts:

import {Injectable} from '@angular/core';
import {Hero} from './hero';
import {HEROES} from './mock-heroes';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HeroService {

    getHeroes() : Promise<Hero[]>{
    return Promise.resolve(HEROES);
  }

   getHero(id: number): Promise<Hero> {
      return this.getHeroes()
               .then(heroes => heroes.find(hero => hero.id === id));
    }

}

Body:
You need to import the switchMap operator:

import 'rxjs/add/operator/switchMap';

update for rxjs >=5.5.0:

for rxjs@5.5.0 or higher it's recommended to use the pipe operator instead of augmentation:

import { switchMap } from 'rxjs/operators';

\\...

this.route.params.pipe(switchMap((params: Params) => /*... */))
  .subscribe(/*... */);
\\...

(this avoids side effects and enable better bundle size optimization)


问:
Why Java process hang?
There are many threads in my Java server.
It hangs when one thread recursive invoke a method infinitely.
After the method is invoked 54 times, the process hang, and there is no any log like "StackOverFlow" or "OutOfMemory".

However, as I know, only the thread with the problem will crash, other threads can work normally.

environment:

Linux version 2.6.31-20-server
  (buildd@crested) (gcc version 4.4.1
  (Ubuntu 4.4.1-4ubuntu8) ) java version
  "1.6.0_18" Java(TM) SE Runtime
  Environment (build 1.6.0_18-b07) Java
  HotSpot(TM) 64-Bit Server VM (build
  16.0-b13, mixed mode)

答:
Ask for a thread dump to see what your threads do. Set name for each thread you fork to identify them correctly. I suppose there could be also a dead lock on object monitors as well. I suggest use JProfiler to find the object the threads are blocked on.

On the other hand infinite recursion is not soo good. Avoid this, or define limit for it.

Title: Why Java process hang?


问:
How to compile neon on ARM
I used the

arm-linux-gnueabi-g++ test.cpp -march=armv7-a -mfloat-abi=softfp -mfpu=neon -o test

on ubantu to get an excecutable file on ARM, but when I ran

```<code>adb push ./test /data/test
adb shell
cd data
chmod 777 test
./test
</code>```

I got the following error:

```<code>./system/bin/sh: ./test: No such file or directory
</code>```

I was confused about this.

答:
If you intend to run the executable on Android (as it seems), you should ideally build it using the Android NDK. The problem is that your executable links to glibc which is available on normal linux systems, but not on Android. (In detail, the executable can't start because it requires the dynamic linker /lib/ld-linux.so.3 which isn't available on Android. In addition, it also requires glibc in the form of libc.so.6.)

If you build executables using the Android NDK, it will link to the Bionic libc, which is what is available on Android.

Alternatively, if you add -static when linking (in your case, in your single compile+link command), you'll get a static executable, which should work on both normal linux and Android.

Title: How to compile neon on ARM

Body:
I used the

arm-linux-gnueabi-g++ test.cpp -march=armv7-a -mfloat-abi=softfp -mfpu=neon -o test

on ubantu to get an excecutable file on ARM, but when I ran

adb push ./test /data/test
adb shell
cd data
chmod 777 test
./test

I got the following error:

./system/bin/sh: ./test: No such file or directory

I was confused about this.