问:
Text to Morse Code
I recently found out that you can play sounds in python. I instantly wanted to make a text to morse code program but when I try to assign winsound.Beep(600,300) to "a" and launch, it just beeps once and when i type a it does nothing.

```<code>import winsound
def dot():
    winsound.Beep(600,100)
def line():
    winsound.Beep(600,100)
a = dot(), line()    #it doesn't work when i just do
                     #a = winsound.Beep(600,100) either
                     #and it beeps at the beginning which i don't want
</code>```

can you tell me how i can assign winsound.Beep() to a varible?

答:
You are mixing up "code that runs right now" with "code I want to run later".

Your line,

```<code>a = dot(), line()
</code>```

runs dot() (which beeps and returns None) then runs line() (which beeps and returns None) then assigns the result (None, None) to the variable a.

Instead try

```<code>def a():
    dot()
    line()
</code>```

which creates a function which you can run later by calling a()... but it will still sound like one continuous beep, because you need to add a short pause after each tone in the definitions of dot() and line(). You might find time.sleep() useful, or possibly winsound already provides something similar.

Edit:

You can use a dispatch table (a dict that translates characters to function calls) and an input loop, like so:

```<code>MORSE_CHARS = {
    "a": (dot, line),
    "b": (dot, dot, line),
    # define other characters and space here
}

def morse(s):
    """
    Turn string s into Morse beeps
    """
    for ch in s.lower():
        for fn in MORSE_CHARS[ch]:
            fn()

def main():
    while True:
        s = input("Enter text to play (or just hit Enter to quit): ")
        if s:
            morse(s)
        else:
            break

if __name__ == "__main__":
    main()
</code>```

Title: Text to Morse Code

Body:
I recently found out that you can play sounds in python. I instantly wanted to make a text to morse code program but when I try to assign winsound.Beep(600,300) to "a" and launch, it just beeps once and when i type a it does nothing.

import winsound
def dot():
    winsound.Beep(600,100)
def line():
    winsound.Beep(600,100)
a = dot(), line()    #it doesn't work when i just do
                     #a = winsound.Beep(600,100) either
                     #and it beeps at the beginning which i don't want

can you tell me how i can assign winsound.Beep() to a varible?

Body:
You are mixing up "code that runs right now" with "code I want to run later".

Your line,

a = dot(), line()

runs dot() (which beeps and returns None) then runs line() (which beeps and returns None) then assigns the result (None, None) to the variable a.

Instead try

def a():
    dot()
    line()

which creates a function which you can run later by calling a()... but it will still sound like one continuous beep, because you need to add a short pause after each tone in the definitions of dot() and line(). You might find time.sleep() useful, or possibly winsound already provides something similar.

Edit:

You can use a dispatch table (a dict that translates characters to function calls) and an input loop, like so:

MORSE_CHARS = {
    "a": (dot, line),
    "b": (dot, dot, line),
    # define other characters and space here
}

def morse(s):
    """
    Turn string s into Morse beeps
    """
    for ch in s.lower():
        for fn in MORSE_CHARS[ch]:
            fn()

def main():
    while True:
        s = input("Enter text to play (or just hit Enter to quit): ")
        if s:
            morse(s)
        else:
            break

if __name__ == "__main__":
    main()


来源: stackexchange

问:
"Please generate new Identifier" error when pushing to cloud services using Android studio
I successfully import the project to google cloud. I am running android studio on a Mac. But, when i try to push the project to the cloud repository i get the error:

fatal: remote error:  Invalid authentication credentials. Please
  generate a new identifier:

  https://source.developers.google.com/auth/start?scopes=https://www.googleapis.com/auth/cloud-platform

I am lost here, Android studio, git and google cloud are all new to me.

The help link provided on the error don't mention where i should get the new credentials. Running the machine command i get the error:

machine: no arguments accepted

答:
The first time you try to clone a repo if you put in the wrong credentials they will be cached and you will continue to get "Invalid authentication credentials" error until fixed. Git Credential Manager is used behind the scenes to cache credentials for sites but it is not obvious on how to edit those credentials. Here is how to fix the cached credentials on Windows:

Follow the link to get you a password to authenticate with so you do not have to use your google account password.

Navigate to Control Panel -> User Accounts -> Credential Manager

Click on Windows Credentials and find an entry for git:https://source.developers.google.com

Click on edit and use your google account email for user name and the git password you copied in step 1 for the password and save.

You should now be able to clone your repository and git will use the stored credentials to authenticate.

ContentLicense: CC BY-SA 3.0


问:
error TS2365: Operator '!==' cannot be applied to types '"("' and '")"'
```<code>function myFunc(id: string) {
  id = "(";
};

let id: string = ")";
if (id !== '(')
  throw "Expected '(' in prototype";

myFunc(id);

if (id !== ')')
  throw "Expected ')' in prototype";
</code>```

If I do the change inline then I do not get the error below

```<code>error TS2365: Operator '!==' cannot be applied to types '"("' and '")"'.
</code>```

The contents of the comparison dont matter. Any string a, basdasd, cqwe, etc. can be used in place of ( and )

答:
What happens is type narrowing. After passing the first if statement, the type of id is narrowed to string literal ")" because otherwise the exception would have been thrown.

```<code>function myFunc(id: string) {
  id = "(";
};
// Note that this function does nothing, but it's not the issue here

let id: string = ")";

if (id !== '(')
  throw "Expected '(' in prototype";
// id is narrowed to "("

myFunc(id);

// now id and ')' does not have same type, hence the error
if (id !== ')')
  throw "Expected ')' in prototype";
</code>```

Body:
function myFunc(id: string) {
  id = "(";
};

let id: string = ")";
if (id !== '(')
  throw "Expected '(' in prototype";

myFunc(id);

if (id !== ')')
  throw "Expected ')' in prototype";

If I do the change inline then I do not get the error below

error TS2365: Operator '!==' cannot be applied to types '"("' and '")"'.

The contents of the comparison dont matter. Any string a, basdasd, cqwe, etc. can be used in place of ( and )

Body:
What happens is type narrowing. After passing the first if statement, the type of id is narrowed to string literal ")" because otherwise the exception would have been thrown.

function myFunc(id: string) {
  id = "(";
};
// Note that this function does nothing, but it's not the issue here

let id: string = ")";

if (id !== '(')
  throw "Expected '(' in prototype";
// id is narrowed to "("

myFunc(id);

// now id and ')' does not have same type, hence the error
if (id !== ')')
  throw "Expected ')' in prototype";


问:
Programmable Video twilio: How to reuse mediaStream
Let say i already have acquired the stream using

```<code>var stream ;
navigator.getUserMedia({ audio: true, video: true}, function(mediastream) {
    stream=mediastream;
});
</code>```

Now how can i use stream when connecting to a room, I dont want Twilio to call getUserMedia again in createLocalTracks when i call Twilio.Video.connect api. ?

答:
Twilio developer evangelist here.

You can use the stream you already collected. You just have to pass the tracks as an option to Video.connect with the tracks key. There is an example in the documentation which I have reproduced below:

```<code>var Video = require('twilio-video');
var token = getAccessToken();

// Connect with media acquired using getUserMedia()
navigator.mediaDevices.getUserMedia({
  audio: true,
  video: true
}).then(function(mediaStream) {
  return Video.connect(token, {
    name: 'my-cool-room',
    tracks: mediaStream.getTracks()
  });
}).then(function(room) {
  room.on('participantConnected', function(participant) {
    console.log(participant.identity + ' has connected');
  });

  room.once('disconnected', function() {
    console.log('You left the Room:', room.name);
  });
});
</code>```

Body:
Let say i already have acquired the stream using

var stream ;
navigator.getUserMedia({ audio: true, video: true}, function(mediastream) {
    stream=mediastream;
});

Now how can i use stream when connecting to a room, I dont want Twilio to call getUserMedia again in createLocalTracks when i call Twilio.Video.connect api. ?

Body:
Twilio developer evangelist here.

You can use the stream you already collected. You just have to pass the tracks as an option to Video.connect with the tracks key. There is an example in the documentation which I have reproduced below:

var Video = require('twilio-video');
var token = getAccessToken();

// Connect with media acquired using getUserMedia()
navigator.mediaDevices.getUserMedia({
  audio: true,
  video: true
}).then(function(mediaStream) {
  return Video.connect(token, {
    name: 'my-cool-room',
    tracks: mediaStream.getTracks()
  });
}).then(function(room) {
  room.on('participantConnected', function(participant) {
    console.log(participant.identity + ' has connected');
  });

  room.once('disconnected', function() {
    console.log('You left the Room:', room.name);
  });
});


问:
getting confusion on this explain this loop result in java
```<code>int a = 0, b = 0;

for (int i = 0; i < 5; i++) {
    if (++a > 2 || ++b > 2) {
        a++;
    }
}

System.out.println("a= " + a + " b=" + b);
</code>```

can you explain the logic please?

答:
++a means the current value of a is increased by 1 before the operations.(in this case, it increase value of a by 1 before compare a > 2)
a++ means the current value of a is increased by 1 after the operations. (in this case, increase value of a, although there is no operations.)

For loop is not interrupted by anything..... So, it loops for 5 times(i = 0,1,2,3,4).

for i = 0 ->
current value of a = 0, current value of b = 0

if ( ++a > 2 || ++b > 2 )

in this statement, a is increase by 1 before compare with 2. So the current value is 0 and the increased by 1. new value is 1.
now compare a (1) with 2.... and same thing happens with the b.

if ( 1 > 2 || 1 > 2 )

the statement is false. so go to the end of the end statement.

for i = 1 -> current value of a = 1, current value of b = 1

same as before value of a is increased by 1 before compare 'a > 2' and also with the b.( new a = 2, b = 2 )

if (2 > 2 || 2 > 2 )

statement is false. to the end of the if statement.

for i = 2 -> current value of a = 2, b = 2

increase a by 1 -> a = 3 and also b = 3 before compare.

if ( 3 > 2 || 3 > 2 )

if condition becomes true. then

a++

statement executes.
new value of a = 4. value of b stays the same (3).

for i =3 -> current values a = 4, b = 3
increase a and b by 1 new values (a= 4, b =4 )

if ( 5 > 2 || 4 > 2 )

true. then

a++

new value of a = 6, b stays the same (4).

for i = 4 -> current values a = 6, b = 4.
increase a and b ( 7, 5 )

if ( 7 > 2 || 5 > 2 )

true. then

a++

new value of a = 8. and b stays the same (5).

end of the for loop ( i < 5 condition fails)

next statement

System.out.println("a= " + a + " b=" + b)

displays "a= 8 b=5"

Body:
int a = 0, b = 0;

for (int i = 0; i < 5; i++) {
    if (++a > 2 || ++b > 2) {
        a++;
    }
}

System.out.println("a= " + a + " b=" + b);

can you explain the logic please?


问:
'print' command in Python (print in the same line)
I am using jupyter notebook. I want to print a simple integer matrix in the general form, i.e., I eant the output to be like this:
a[0][0] = 1    a[0][1] = 2
a[1][0] = 3    a[1][1] = 4

Here's my program:

```<code>column = int(input("Enter the number of columns: "))
row = int (input("Enter the number of rows: "))
a=[[0 for x in range(column)] for y in range(row)]
for i in range (0, row):
    for j in range (0, column):
        a[i][j]=int(input(" Enter the elements: "))
for i in range (0, row):
    for j in range (0, column):
        print ("a[",i,"][",j,"] =",a[i][j],"\t",),
    print ("\n")
</code>```

But I get the output as:

```<code>Enter the number of columns: 2
Enter the number of rows: 2
 Enter the elements: 1
 Enter the elements: 2
 Enter the elements: 3
 Enter the elements: 4
a[ 0 ][ 0 ] = 1
a[ 0 ][ 1 ] = 2

a[ 1 ][ 0 ] = 3
a[ 1 ][ 1 ] = 4
</code>```

The print(), function in the loop goes to a new line even though I have put a comma after it. Please help me get the desired output format. Thank you.

答:
this will not print new line

```<code>print(something,end="")
</code>```

and your code

```<code>column = int(input("Enter the number of columns: "))
row = int (input("Enter the number of rows: "))
a=[[0 for x in range(column)] for y in range(row)]
for i in range (0, row):
    for j in range (0, column):
        a[i][j]=int(input(" Enter the elements: "))
for i in range (0, row):
    for j in range (0, column):
        print("a[%d][%d] = %d "%(i,j,a[i][j]),end="")
</code>```

Body:
I am using jupyter notebook. I want to print a simple integer matrix in the general form, i.e., I eant the output to be like this:
a[0][0] = 1    a[0][1] = 2
a[1][0] = 3    a[1][1] = 4

Here's my program:

column = int(input("Enter the number of columns: "))
row = int (input("Enter the number of rows: "))
a=[[0 for x in range(column)] for y in range(row)]
for i in range (0, row):
    for j in range (0, column):
        a[i][j]=int(input(" Enter the elements: "))
for i in range (0, row):
    for j in range (0, column):
        print ("a[",i,"][",j,"] =",a[i][j],"\t",),
    print ("\n")

But I get the output as:

Enter the number of columns: 2
Enter the number of rows: 2
 Enter the elements: 1
 Enter the elements: 2
 Enter the elements: 3
 Enter the elements: 4
a[ 0 ][ 0 ] = 1
a[ 0 ][ 1 ] = 2

a[ 1 ][ 0 ] = 3
a[ 1 ][ 1 ] = 4

The print(), function in the loop goes to a new line even though I have put a comma after it. Please help me get the desired output format. Thank you.

Body:
this will not print new line

print(something,end="")

and your code

column = int(input("Enter the number of columns: "))
row = int (input("Enter the number of rows: "))
a=[[0 for x in range(column)] for y in range(row)]
for i in range (0, row):
    for j in range (0, column):
        a[i][j]=int(input(" Enter the elements: "))
for i in range (0, row):
    for j in range (0, column):
        print("a[%d][%d] = %d "%(i,j,a[i][j]),end="")


问:
SharpZipLib - ZipException "System.ArgumentOutOfRangeException" - Why am I getting this exception?
I'm using SharpZipLib to unzip files. My code has been working nicely for all zipfiles except the zip file what i am extracting now...

Got this exception:

```<code>System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: length
</code>```

The exception is being thrown at   size = s.Read(data, 0, data.Length);

Hereb is my code...

```<code> public static void UnzipFile(string sourcePath, string targetDirectory)
     {
        try
        {
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    //string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    if (targetDirectory.Length > 0)
                    {
                        Directory.CreateDirectory(targetDirectory);
                    }

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(targetDirectory + fileName))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error unzipping file \"" + sourcePath + "\"", ex);
        }
    }
</code>```

答:
Looks like a bug to me. Fortunately, you have access to the code, so you should be able to see exactly where it's going wrong. I suggest you build a debug version of SharpZipLib, break on the line which is throwing the exception, and have a look at what it's actually testing.

It should be fine to read into a 2K buffer even if there's not 2K of data left.

(I wouldn't actually write the code quite how you have, but that's a different matter. I'd also move it into its own utility method - the act of copying all the data from one stream to another is pretty common. There's no need to tie it to zip.)

ContentLicense: CC BY-SA 2.5

Body:
I'm using SharpZipLib to unzip files. My code has been working nicely for all zipfiles except the zip file what i am extracting now...

Got this exception:

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: length

The exception is being thrown at   size = s.Read(data, 0, data.Length);

Hereb is my code...

 public static void UnzipFile(string sourcePath, string targetDirectory)
     {
        try
        {
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    //string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    if (targetDirectory.Length > 0)
                    {
                        Directory.CreateDirectory(targetDirectory);
                    }

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(targetDirectory + fileName))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error unzipping file \"" + sourcePath + "\"", ex);
        }
    }


问:
Is there a fast way in Python to read in data from a file, separated by empty lines?
I want to read in data from a txt file that looks like this:

```<code># input data
50.  310.  3.0E-07  23.06
50.  310.5  2.4E-07  5.73

50.5  310.  2.9E-07  16.30
50.5  310.5  2.2E-07  4.26

51.  310.  2.3E-07  6.40
51.  310.5  2.7E-07  8.19
</code>```

So I have different blocks, each with a few lines of data and four values, who all end with a blank line.

Currently I read in my data with numpy like this, which gives me an array for every value from all the different blocks.

```<code> x,y,z,err = np.loadtxt(path_to_file, unpack=True)
</code>```

But in fact I'm really interested to get a list of list for each value, so that I can separate the data from each block, which is indicated through a blank line in the datafile.
The results, for example for the third value, should look like this:

```<code># the result i want to achieve
z_list = array([[3.0E-7, 2.4E-07],
   [2.9E-07, 2.2E-07],
   [2.3E-07, 2.7E-07]])
</code>```

Is there a way in Python or numpy where I read my data and separate it by blank lines?

答:
You can do something like this using groupby from itertools module and literal_eval from ast module.

Assuming your input file is called input_file:

```<code>from itertools import groupby
from ast import literal_eval as le

data = []
with open('input_file', 'r') as f:
    data = (k.split() for k in f.read().splitlines())

final = []
for _,v in groupby(data, lambda x: x != []):
    bb = list(v)
    if bb != [[]]:
        final.append([le(k[2]) for k in bb])

print(final)
</code>```

Output:

```<code>[[3e-07, 2.4e-07], [2.9e-07, 2.2e-07], [2.3e-07, 2.7e-07]]
</code>```

Then, you can convert the final list into a numpy array or something else that'll fill your needs.

Body:
I want to read in data from a txt file that looks like this:

# input data
50.  310.  3.0E-07  23.06
50.  310.5  2.4E-07  5.73

50.5  310.  2.9E-07  16.30
50.5  310.5  2.2E-07  4.26

51.  310.  2.3E-07  6.40
51.  310.5  2.7E-07  8.19

So I have different blocks, each with a few lines of data and four values, who all end with a blank line.

Currently I read in my data with numpy like this, which gives me an array for every value from all the different blocks.

 x,y,z,err = np.loadtxt(path_to_file, unpack=True)

But in fact I'm really interested to get a list of list for each value, so that I can separate the data from each block, which is indicated through a blank line in the datafile.
The results, for example for the third value, should look like this:

# the result i want to achieve
z_list = array([[3.0E-7, 2.4E-07],
   [2.9E-07, 2.2E-07],
   [2.3E-07, 2.7E-07]])

Is there a way in Python or numpy where I read my data and separate it by blank lines?

Body:
You can do something like this using groupby from itertools module and literal_eval from ast module.

Assuming your input file is called input_file:

from itertools import groupby
from ast import literal_eval as le

data = []
with open('input_file', 'r') as f:
    data = (k.split() for k in f.read().splitlines())

final = []
for _,v in groupby(data, lambda x: x != []):
    bb = list(v)
    if bb != [[]]:
        final.append([le(k[2]) for k in bb])

print(final)

Output:

[[3e-07, 2.4e-07], [2.9e-07, 2.2e-07], [2.3e-07, 2.7e-07]]

Then, you can convert the final list into a numpy array or something else that'll fill your needs.


问:
What are core threads in a ThreadPoolExecutor?
I was looking at the ThreadPoolExecutor class and I found that it allows to specify the maximum pool size and the core pool size.

I understand, a little, about when to change the core and maximum pool sizes based on the answer here: When is specifying separate core and maximum pool sizes in ThreadPoolExecutor a good idea?

However, I would like to know what are these 'core threads'. I always get 0 when I use the getCorePoolSize() method of a ThreadPoolExecutor

SSCCE here:

```<code>import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

public class PoolSize {
    public static void main(String[] args) {
        // Create a cached thread pool
        ExecutorService cachedPool = Executors.newCachedThreadPool();
        // Cast the object to its class type
        ThreadPoolExecutor pool = (ThreadPoolExecutor) cachedPool;

        // Create a Callable object of anonymous class
        Callable<String> aCallable = new Callable<String>(){
            String result = "Callable done !";
            @Override
            public String call() throws Exception {
                // Print a value
                System.out.println("Callable at work !");
                // Sleep for 5 sec
                Thread.sleep(0);
                return result;
            }
        };

        // Create a Runnable object of anonymous class
        Runnable aRunnable = new Runnable(){
            @Override
            public void run() {
                try {
                    // Print a value
                    System.out.println("Runnable at work !");
                    // Sleep for 5 sec
                    Thread.sleep(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        // Submit the two tasks for execution
        Future<String> callableFuture = cachedPool.submit(aCallable);
        Future<?> runnableFuture = cachedPool.submit(aRunnable);

        System.out.println("Core threads: " + pool.getCorePoolSize());
        System.out.println("Largest number of simultaneous executions: "
                                            + pool.getLargestPoolSize());
        System.out.println("Maximum number of  allowed threads: "
                                            + pool.getMaximumPoolSize());
        System.out.println("Current threads in the pool: "
                                            + pool.getPoolSize());
        System.out.println("Currently executing threads: "
                                            + pool.getTaskCount());

        pool.shutdown(); // shut down

    }
}
</code>```

答:
The core threads are just standard threads but will be always kept alive in the pool, and then the other non-core threads will end their lives after the run() method finished.

But how could these core threads be always alive? That's because they are always waiting for taking a task from the workQueue shared within the pool. By default, the workQueue is a BlockingQueue, its take() method will block the current thread indefinitely until a task becomes available.

Here comes the key point, which threads will become the core threads? They may not be the first started ones or the last ones, but the ones(corePoolSize) that last the longest. Easier to understand from the code.

private Runnable getTask() {
        boolean timedOut = false; // Did the last poll() time out?

        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }

            int wc = workerCountOf(c);

            //------------- key code ------------------
            // Are workers subject to culling?
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

            if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }

            //------------- key code ------------------
            try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }```

What I just said above is based on allowCoreThreadTimeOut set as false.

Actually, I prefer to call core threads as core workers.

Body:
I was looking at the ThreadPoolExecutor class and I found that it allows to specify the maximum pool size and the core pool size.

I understand, a little, about when to change the core and maximum pool sizes based on the answer here: When is specifying separate core and maximum pool sizes in ThreadPoolExecutor a good idea?

However, I would like to know what are these 'core threads'. I always get 0 when I use the getCorePoolSize() method of a ThreadPoolExecutor

SSCCE here:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

public class PoolSize {
    public static void main(String[] args) {
        // Create a cached thread pool
        ExecutorService cachedPool = Executors.newCachedThreadPool();
        // Cast the object to its class type
        ThreadPoolExecutor pool = (ThreadPoolExecutor) cachedPool;

        // Create a Callable object of anonymous class
        Callable<String> aCallable = new Callable<String>(){
            String result = "Callable done !";
            @Override
            public String call() throws Exception {
                // Print a value
                System.out.println("Callable at work !");
                // Sleep for 5 sec
                Thread.sleep(0);
                return result;
            }
        };

        // Create a Runnable object of anonymous class
        Runnable aRunnable = new Runnable(){
            @Override
            public void run() {
                try {
                    // Print a value
                    System.out.println("Runnable at work !");
                    // Sleep for 5 sec
                    Thread.sleep(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        // Submit the two tasks for execution
        Future<String> callableFuture = cachedPool.submit(aCallable);
        Future<?> runnableFuture = cachedPool.submit(aRunnable);

        System.out.println("Core threads: " + pool.getCorePoolSize());
        System.out.println("Largest number of simultaneous executions: "
                                            + pool.getLargestPoolSize());
        System.out.println("Maximum number of  allowed threads: "
                                            + pool.getMaximumPoolSize());
        System.out.println("Current threads in the pool: "
                                            + pool.getPoolSize());
        System.out.println("Currently executing threads: "
                                            + pool.getTaskCount());

        pool.shutdown(); // shut down

    }
}

Body:
The core threads are just standard threads but will be always kept alive in the pool, and then the other non-core threads will end their lives after the run() method finished.

But how could these core threads be always alive? That's because they are always waiting for taking a task from the workQueue shared within the pool. By default, the workQueue is a BlockingQueue, its take() method will block the current thread indefinitely until a task becomes available.

Here comes the key point, which threads will become the core threads? They may not be the first started ones or the last ones, but the ones(corePoolSize) that last the longest. Easier to understand from the code.

private Runnable getTask() {
        boolean timedOut = false; // Did the last poll() time out?

        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }

            int wc = workerCountOf(c);

            //------------- key code ------------------
            // Are workers subject to culling?
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

            if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }

            //------------- key code ------------------
            try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }

What I just said above is based on allowCoreThreadTimeOut set as false.

Actually, I prefer to call core threads as core workers.


问:
How to resolve "undefined function TYPO3\CMS\Core\Localization\Parser\simplexml_load_string()" in TYPO3 8 CMS
Recently I have installed TYPO3 CMS 8 in my local server, after all configuration wizard finally I got error like "Call to undefined function TYPO3\CMS\Core\Localization\Parser\simplexml_load_string()".

Can anyone help me for resolving this error.

答:
This is php extension error. install php7.0-xml using below command and after restart your apache server.

```<code>sudo apt-get install php7.0-xml
sudo service apache2 restart
</code>```

Body:
This is php extension error. install php7.0-xml using below command and after restart your apache server.

sudo apt-get install php7.0-xml
sudo service apache2 restart


问:
Blocking read from std::ifstream
I am reading from a pipe (Linux) or a pipe-like device object (Windows) using std::ifstream::read. However, when there is no more data, read reads 0 bytes and sets EOF. Is there a way to make a blocking read from an ifstream, such that it only returns when there is some more data?

I'd rather not busy wait for the EOF flag to clear.

If it is not possible with the C++ standard library, what is the closest other option? Can I do it in plain C, or do I have to resort to operating system specific APIs?

答:
Unfortunately, std is very poor on any non-algorithmic functionality, like IO. You always have to rely on 3rd-party solutions. Fortunately, there is Boost and, if you do not mind, I will suggest to use it to reduce OS specific code.

```<code>    namespace bs = boost::iostreams;
    int fd; // Create, for example, Posix file descriptor and specify necessary flags for it.
    bs::file_descriptor_source fds(fd);
    bs::stream<bs::file_descriptor_source> stream(fds);
    // Work with the stream as it is std stream
</code>```

In this small example I use Boost IO Streams and specifically file_descriptor_source that works as an underlying stream device and hides Windows or Posix specific pipe inside. The pipe you open yourself, so you can configure the pipe as you want.

Title: Blocking read from std::ifstream

Body:
Unfortunately, std is very poor on any non-algorithmic functionality, like IO. You always have to rely on 3rd-party solutions. Fortunately, there is Boost and, if you do not mind, I will suggest to use it to reduce OS specific code.

    namespace bs = boost::iostreams;
    int fd; // Create, for example, Posix file descriptor and specify necessary flags for it.
    bs::file_descriptor_source fds(fd);
    bs::stream<bs::file_descriptor_source> stream(fds);
    // Work with the stream as it is std stream

In this small example I use Boost IO Streams and specifically file_descriptor_source that works as an underlying stream device and hides Windows or Posix specific pipe inside. The pipe you open yourself, so you can configure the pipe as you want.


问:
unexpected token : using map to form array of object
I want to produce this

```<code>[
        {name: "james", age: 10},
        {name: "john", age: 12},
        {name: "johnny", age: 56}
    ]
</code>```

My below code failed, got expected token?

```<code>let x = [
    {name: "james", age: 10, school: "London"},
    {name: "john", age: 12, school: "India"},
    {name: "johnny", age: 56, school: "USA"}
]

let y = x.map(obj => {name:obj.name, age:obj.age})

console.log(y)
</code>```

答:
you are missing the () change  like this ({name:obj.name, age:obj.age})

You must wrap the returning object literal into parentheses. Otherwise
  curly braces will be considered to denote the function’s body. Next
  works:

Reference question

let x = [
    {name: "james", age: 10, school: "London"},
    {name: "john", age: 12, school: "India"},
    {name: "johnny", age: 56, school: "USA"}
]

let y = x.map(obj => ({name:obj.name, age:obj.age}))

console.log(y)```

Body:
I want to produce this

[
        {name: "james", age: 10},
        {name: "john", age: 12},
        {name: "johnny", age: 56}
    ]

My below code failed, got expected token?

let x = [
    {name: "james", age: 10, school: "London"},
    {name: "john", age: 12, school: "India"},
    {name: "johnny", age: 56, school: "USA"}
]

let y = x.map(obj => {name:obj.name, age:obj.age})

console.log(y)


问:
Batch script to rename files in folder argument
I can't find any references explaining how to loop through a folder passed as an argument and rename each file.  All examples I've seen assume the script is running in the folder where files will be renamed or hardcode the folder path in the loop.  How can I do this?  Here is an example of what I'm trying to do:</p>

```<code>for /f %%a in (%1) do call :RenameFiles

:RenameFiles
Rename %%a "new filename"
Goto :EOF
</code>```

答:
The following adds prefix "renamed-" to every file in the directory specified as a command line argument:

```<code>for %%F in (%~1\*) do ren "%%~F" "renamed-%%~nxF"
</code>```

EDIT The simplest solution to the problem of the infinite loop is to work in two stages:

prepare the list of operations

execute the plan.

-

```<code>set OpList=%TEMP%\%~n0%RANDOM%.bat
copy nul "%OpList%"
for %%F in (%~1\*) do echo ren "%%~F" "renamed-%%~nxF" >> "%OpList%"
call "%OpList%"
del "%OpList%"
</code>```

Body:
I can't find any references explaining how to loop through a folder passed as an argument and rename each file.  All examples I've seen assume the script is running in the folder where files will be renamed or hardcode the folder path in the loop.  How can I do this?  Here is an example of what I'm trying to do:

for /f %%a in (%1) do call :RenameFiles

:RenameFiles
Rename %%a "new filename"
Goto :EOF

Body:
The following adds prefix "renamed-" to every file in the directory specified as a command line argument:

for %%F in (%~1\*) do ren "%%~F" "renamed-%%~nxF"

EDIT The simplest solution to the problem of the infinite loop is to work in two stages:

prepare the list of operations

execute the plan.

-

set OpList=%TEMP%\%~n0%RANDOM%.bat
copy nul "%OpList%"
for %%F in (%~1\*) do echo ren "%%~F" "renamed-%%~nxF" >> "%OpList%"
call "%OpList%"
del "%OpList%"


问:
Getting below issue while fetching private repositories from GitHub with Jenkins
I have added credentials to the jenkins for GItHub account.
I was able to checkout code from github desktop.
But with Jenkins, I am getting below error with the private repositories.

答:
I got root cause for the issue mentioned above.

When the Jenkins is trying to trigger git.exe to download the content from github.THe git is trying to access git credential manager.

So as a fix suggested by some friend in Facebook, I am uncheking the "Git Credential Manager" while installing the git.
Then it is working!!!


答:
When creating objects with arrow expressions, you'll need to wrap the body in parens, or it'll be parsed as an arrow function:</p>

```<code>let y = x.map(obj => ({name: obj.name, age: obj.age}));
</code>```

Title: unexpected token : using map to form array of object

Body:
When creating objects with arrow expressions, you'll need to wrap the body in parens, or it'll be parsed as an arrow function:

let y = x.map(obj => ({name: obj.name, age: obj.age}));


问:
How to change Java version for decompiled bytecode in IntelliJ?
I'm trying to view the decompiled bytecode for a Java 8 class in IntelliJ but when opening it up it is trying to decompile the class using bytecode version Java 6:

I have managed to open it using Java 8 in the past (not sure how) but I have no idea how to change settings in IntelliJ to open it. Does anyone know how to do this?

答: Apologies I realise I did something very silly. The class En I have imported was not the correct Java 8 one. :(</p>


问:
Why is goto poor practise?

This question is a duplicate of  Goto Still Considered Harmful. If you wish to discuss this further please use the original question.

Why exactly is GOTO poor programming practise? It makes sense on some occasions to use it.

答:
Readability becomes a problem, and flow of logic can have unintended effects by the use of goto. </p>

<p>I think its funny that the .net compiler will change some case/switch statements to use goto. </p>

Title: Why is goto poor practise?

LastEditorDisplayName: Rich B

Body:
Readability becomes a problem, and flow of logic can have unintended effects by the use of goto.

I think its funny that the .net compiler will change some case/switch statements to use goto.

OwnerDisplayName: StingyJack


问:
onCreateOptionsMenu Inflater doesn´t work in Android Java Class
in my code i want to infalte an action bar with a menu, but it doesn´t works.
I have more Activities ( Start, Karte, Teilnehmer ) on all three I had place the onCreateOptionsMenu block but only on Karte it works. If anyone can help me, please anwser.

Start ( Menu not working )

```<code>package barsoftware.suedtirolpointer;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Start extends Activity {

Button button_karte;
Button button_teilnehmer;

////////////////////////////////// MENU //////////////////////////////////
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.menu_einstellungen) {

        return true;
    }
    if (id == R.id.menu_update) {

        return true;
    }

    return super.onOptionsItemSelected(item);
}

////////////////////////////// LAYOUT //////////////////////////////

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from activity_main.xml
    setContentView(R.layout.start);

    button_karte = (Button) findViewById(R.id.button_karte);
    button_teilnehmer = (Button) findViewById(R.id.button_teilnehmer);

    // Capture button clicks
    button_karte.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {

            // Start NewActivity.class
            Intent karte = new Intent(Start.this,
                    Karte.class);
            startActivity(karte);
        }
    });

    button_teilnehmer.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {

            // Start NewActivity.class
            Intent teilnehmer = new Intent(Start.this,
                    Teilnehmer.class);
            startActivity(teilnehmer);
        }
    });
}

}
</code>```

答:
you need to extend AppCompatActivity which provide inbuilt Toolbar/ActionBar support so change

Someclass extends Activity

to

Someclass extends AppCompatActivity

Body:
in my code i want to infalte an action bar with a menu, but it doesn´t works.
I have more Activities ( Start, Karte, Teilnehmer ) on all three I had place the onCreateOptionsMenu block but only on Karte it works. If anyone can help me, please anwser.

Start ( Menu not working )

package barsoftware.suedtirolpointer;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Start extends Activity {

Button button_karte;
Button button_teilnehmer;

////////////////////////////////// MENU //////////////////////////////////
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.menu_einstellungen) {

        return true;
    }
    if (id == R.id.menu_update) {

        return true;
    }

    return super.onOptionsItemSelected(item);
}

////////////////////////////// LAYOUT //////////////////////////////

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from activity_main.xml
    setContentView(R.layout.start);

    button_karte = (Button) findViewById(R.id.button_karte);
    button_teilnehmer = (Button) findViewById(R.id.button_teilnehmer);

    // Capture button clicks
    button_karte.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {

            // Start NewActivity.class
            Intent karte = new Intent(Start.this,
                    Karte.class);
            startActivity(karte);
        }
    });

    button_teilnehmer.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {

            // Start NewActivity.class
            Intent teilnehmer = new Intent(Start.this,
                    Teilnehmer.class);
            startActivity(teilnehmer);
        }
    });
}

}


问:
Gurobi-style model construction for Scipy.linprog?
I want to compare Gurobi and Scipy's linear programming tools, such as linprog. Scipy requires to specify problems in a matrix-list-vector-form while Gurobi works like here such that

```<code>m = Model()
m.addVar(...) %for variables
m.addConstr(..>) %for constraints
m.update() %for updating the model
m.optimize % for optimizing the model
m.params %for getting parameters
m._vars %for getting variables
</code>```

in comparison Scipy

```<code>Minimize: c^T * x

Subject to: A_ub * x <= b_ub
A_eq * x == b_eq

c : array_like
Coefficients of the linear objective function to be minimized.
A_ub : array_like, optional
2-D array which, when matrix-multiplied by x, gives the values of the upper-bound inequality constraints at x.
b_ub : array_like, optional
1-D array of values representing the upper-bound of each inequality constraint (row) in A_ub.
A_eq : array_like, optional
2-D array which, when matrix-multiplied by x, gives the values of the equality constraints at x.
b_eq : array_like, optional
1-D array of values representing the RHS of each equality constraint (row) in A_eq.
bounds : sequence, optional
</code>```

My goal is to write the code in only one method and still benchmark the results with both solvers. In order to speed up comparing the solvers:

Does there exist Gurobi-style model construction of LP problems for Scipy?

Does there exist some package to make the two methods interchangeable (I could write scipy-style for Gurobi or in Gurobi-style for Scipy)?

Does scipy provide any other interface to specify linear programming problems?

答:
That sounds like a lot of work to show the obvious:

Commercial solvers like Gurobi are much faster and much more robust than non-commercial ones

There are also high-quality benchmarks showing this by H. Mittelmann (CLP and GLPK beeing the most popular non-commercial ones)

While scipy's linprog is ok, it's much worse than the open-source competition including CBC/CLP, GLPK, lpSolve...

Speed and robustness!

Also: scipy's linprog really seems unmaintained open issues

There are some ways you could do that:

A) Use linprog's way of problem-definition and convert this to Gurobi-style

very easy to convert-matrix form to Gurobi's modelling

B) Use cvxpy as modelling-tool, grab the standard-form and write a wrapper for Gurobi (actually: there is one) and linprog (again easy). This would allow a very powerful modelling-language to be used by both

Disadvantage: Intransparent transformations according to the problem (e.g. abs(some_vector) might introduce auxiliary variables)

C) Write some MPS-reader / or take one from other tools to model you problems within Gurobi, output these and read & solve within linprog

Candidate tools: cvxopt's mps-reader (well-hidden in the docs), some GLPK-interface or even some CBC-interface

(Maybe hidden transformations)

No matter what you do, solution-process analysis will be a big part of your code as linprog might fail a lot. It's also not able to handle big sparse models.

Remarks based on your gurobi-example

Your example (TSP) is a MIP, not an LP

For MIP, everything said above get's worse (especially performance differences between commerical and open-source)

There is no MIP-solver within scipy!

Body:
I want to compare Gurobi and Scipy's linear programming tools, such as linprog. Scipy requires to specify problems in a matrix-list-vector-form while Gurobi works like here such that

m = Model()
m.addVar(...) %for variables
m.addConstr(..>) %for constraints
m.update() %for updating the model
m.optimize % for optimizing the model
m.params %for getting parameters
m._vars %for getting variables

in comparison Scipy

Minimize: c^T * x

Subject to: A_ub * x <= b_ub
A_eq * x == b_eq

c : array_like
Coefficients of the linear objective function to be minimized.
A_ub : array_like, optional
2-D array which, when matrix-multiplied by x, gives the values of the upper-bound inequality constraints at x.
b_ub : array_like, optional
1-D array of values representing the upper-bound of each inequality constraint (row) in A_ub.
A_eq : array_like, optional
2-D array which, when matrix-multiplied by x, gives the values of the equality constraints at x.
b_eq : array_like, optional
1-D array of values representing the RHS of each equality constraint (row) in A_eq.
bounds : sequence, optional

My goal is to write the code in only one method and still benchmark the results with both solvers. In order to speed up comparing the solvers:

Does there exist Gurobi-style model construction of LP problems for Scipy?

Does there exist some package to make the two methods interchangeable (I could write scipy-style for Gurobi or in Gurobi-style for Scipy)?

Does scipy provide any other interface to specify linear programming problems?


问:
Get data from each row of a column in C #
It's as follows, I have a DataGridView with multiple columns. In each row of the DataGridView will be the version of the installation path of a program. With this value, I would like to use for the size of the folder and put it in the new column.

I have a method to calculate the size of a string:

```<code>private static long ObterTamanhoDiretorio(string tamanhoDir)
{
    DirectoryInfo dire = new DirectoryInfo(tamanhoDir.ToString());
    return dire.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
}
</code>```

I do not know if it's something like that that I have to use.

```<code>foreach (DataGridViewRow item in dataGridView1.Rows)
{

}
</code>```

This is what I got:

```<code>ObjectQuery query8 = new ObjectQuery("SELECT Description, Version, InstallDate, Vendor, InstallLocation FROM Win32_Product");

ManagementObjectSearcher searcher8 = new ManagementObjectSearcher(scope, query8);

DataTable dt = new DataTable();
dt.Columns.Add("Program");
dt.Columns.Add("Version");
dt.Columns.Add("Installing Date");
dt.Columns.Add("Company");
dt.Columns.Add("Install Location");
dt.Columns.Add("Size");

foreach (DataGridViewRow item in dataGridView1.Rows)
{
    foreach (ManagementObject queryObj in searcher8.Get())
    {
        var paths = new List<string>();
        var installPathColumnPos = 0;
        string s = item.Cells[installPathColumnPos].Value.ToString();
        dt.Rows.Add(new object[] { queryObj["Description"], queryObj["Version"], FormatDateTime(queryObj["InstallDate"]), queryObj["Vendor"], queryObj["InstallLocation"], s });
    }
}
dataGridView1.DataSource = dt;
</code>```

What I would like to know is how to get this value seeing on each line. If you have any ideas, thank you.

答:
OK, based on our comments, I believe the below is what you are after.

```<code>            DataTable dt = new DataTable();

            dt.Columns.Add("Program", typeof(string));
            dt.Columns.Add("Version", typeof(double));
            dt.Columns.Add("InstallDate", typeof(DateTime));
            dt.Columns.Add("Company", typeof(string));
            dt.Columns.Add("InstallLocation", typeof(string));
            dt.Columns.Add("Size", typeof(long));

            foreach (ManagementObject queryObj in searcher8.Get())
            {
                var newRow = dt.NewRow();
                newRow["Program"] = queryObj["Description"];
                newRow["Version"] = queryObj["Version"];
                newRow["InstallDate"] = FormatDateTime(queryObj["InstallDate"]);
                newRow["Company"] = queryObj["Vendor"];
                newRow["InstallLocation"] = queryObj["InstallLocation"];
                newRow["Size"] = ObterTamanhoDiretorio(queryObj["InstallLocation"]);

                dt.Rows.Add(newRow);
            }

            dataGridView1.DataSource = dt;
</code>```

So we iterate through your results from searcher8 and add a new row to your datatable for each entry. The size column is then set from the value in "InstallLocation"

```<code>        private static long ObterTamanhoDiretorio(string tamanhoDir)
        {
            if (string.IsNullOrEmpty(tamanhoDir))
                return 0;

            DirectoryInfo dire = new DirectoryInfo(tamanhoDir.ToString());
            return dire.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
        }
</code>```

Hope that helps.

Body:
It's as follows, I have a DataGridView with multiple columns. In each row of the DataGridView will be the version of the installation path of a program. With this value, I would like to use for the size of the folder and put it in the new column.

I have a method to calculate the size of a string:

private static long ObterTamanhoDiretorio(string tamanhoDir)
{
    DirectoryInfo dire = new DirectoryInfo(tamanhoDir.ToString());
    return dire.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
}

I do not know if it's something like that that I have to use.

foreach (DataGridViewRow item in dataGridView1.Rows)
{

}

This is what I got:

ObjectQuery query8 = new ObjectQuery("SELECT Description, Version, InstallDate, Vendor, InstallLocation FROM Win32_Product");

ManagementObjectSearcher searcher8 = new ManagementObjectSearcher(scope, query8);

DataTable dt = new DataTable();
dt.Columns.Add("Program");
dt.Columns.Add("Version");
dt.Columns.Add("Installing Date");
dt.Columns.Add("Company");
dt.Columns.Add("Install Location");
dt.Columns.Add("Size");

foreach (DataGridViewRow item in dataGridView1.Rows)
{
    foreach (ManagementObject queryObj in searcher8.Get())
    {
        var paths = new List<string>();
        var installPathColumnPos = 0;
        string s = item.Cells[installPathColumnPos].Value.ToString();
        dt.Rows.Add(new object[] { queryObj["Description"], queryObj["Version"], FormatDateTime(queryObj["InstallDate"]), queryObj["Vendor"], queryObj["InstallLocation"], s });
    }
}
dataGridView1.DataSource = dt;

What I would like to know is how to get this value seeing on each line. If you have any ideas, thank you.

Body:
OK, based on our comments, I believe the below is what you are after.

            DataTable dt = new DataTable();

            dt.Columns.Add("Program", typeof(string));
            dt.Columns.Add("Version", typeof(double));
            dt.Columns.Add("InstallDate", typeof(DateTime));
            dt.Columns.Add("Company", typeof(string));
            dt.Columns.Add("InstallLocation", typeof(string));
            dt.Columns.Add("Size", typeof(long));

            foreach (ManagementObject queryObj in searcher8.Get())
            {
                var newRow = dt.NewRow();
                newRow["Program"] = queryObj["Description"];
                newRow["Version"] = queryObj["Version"];
                newRow["InstallDate"] = FormatDateTime(queryObj["InstallDate"]);
                newRow["Company"] = queryObj["Vendor"];
                newRow["InstallLocation"] = queryObj["InstallLocation"];
                newRow["Size"] = ObterTamanhoDiretorio(queryObj["InstallLocation"]);

                dt.Rows.Add(newRow);
            }

            dataGridView1.DataSource = dt;

So we iterate through your results from searcher8 and add a new row to your datatable for each entry. The size column is then set from the value in "InstallLocation"

        private static long ObterTamanhoDiretorio(string tamanhoDir)
        {
            if (string.IsNullOrEmpty(tamanhoDir))
                return 0;

            DirectoryInfo dire = new DirectoryInfo(tamanhoDir.ToString());
            return dire.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
        }

Hope that helps.


答:
the other answers are good, but a much more readable code would be this:</p>

```<code>some_string = ''
for i in range (0, row):
    for j in range (0, column):
        some_string += "a[{}][{}]= {} ".format(i,j,a[i][j])
print(some_string)
</code>```

Title: 'print' command in Python (print in the same line)

Body:
I am using jupyter notebook. I want to print a simple integer matrix in the general form, i.e., I eant the output to be like this:
a[0][0] = 1    a[0][1] = 2
a[1][0] = 3    a[1][1] = 4

Here's my program:

column = int(input("Enter the number of columns: "))
row = int (input("Enter the number of rows: "))
a=[[0 for x in range(column)] for y in range(row)]
for i in range (0, row):
    for j in range (0, column):
        a[i][j]=int(input(" Enter the elements: "))
for i in range (0, row):
    for j in range (0, column):
        print ("a[",i,"][",j,"] =",a[i][j],"\t",),
    print ("\n")

But I get the output as:

Enter the number of columns: 2
Enter the number of rows: 2
 Enter the elements: 1
 Enter the elements: 2
 Enter the elements: 3
 Enter the elements: 4
a[ 0 ][ 0 ] = 1
a[ 0 ][ 1 ] = 2

a[ 1 ][ 0 ] = 3
a[ 1 ][ 1 ] = 4

The print(), function in the loop goes to a new line even though I have put a comma after it. Please help me get the desired output format. Thank you.

Body:
the other answers are good, but a much more readable code would be this:

some_string = ''
for i in range (0, row):
    for j in range (0, column):
        some_string += "a[{}][{}]= {} ".format(i,j,a[i][j])
print(some_string)


问:
c# Wrong data in Sokcet programming
I've been developing simple remote desktop program sending, receiving screen images between server, client and doing mouse control, keyboard control.

When I attempted to send server mouse X,Y position to client to control, client received wrong data.

ex) server sends data which is MouseControl$Position$10(Mouse_X_Position)$10(Mouse_Y_Position)$450(pictureBox.Width)$450(pictureBox.Height). It works well at first, client receives the same data that server sent. But, a few seconds later client receives data like ntrol$Position$10(Mouse_X_Position)$10(Mouse_Y_Position)$450(pictureBox.Width)$450(pictureBox.Height). Some part of The first word MouseControl is disappeared while server still sends right data MouseControl$Position$10(Mouse_X_Position)$10(Mouse_Y_Position)$450(pictureBox.Width)$450(pictureBox.Height)

Help me out of this trouble. I want to know why it is happening
Thank you in advance!

Here is my code below

```<code>    -server
    private void StartMouseControl()
    {
        NetworkStream MouseControlStream = MouseControlDataSock.GetStream();
        byte[] buffer = null;

        while (true)
        {
            Point PointXY = pictureBox1.PointToClient(new Point(Control.MousePosition.X, Control.MousePosition.Y));
            int MouseX = PointXY.X;
            int MouseY = PointXY.Y;

            /* when mouse pointer in pictureBox ... */
            if ((MouseX >= 0 && MouseX <= pictureBox1.Width) && (MouseY >= 0 && MouseY <= pictureBox1.Height))
            {
                MouseControlStream.Flush();
                buffer = Encoding.Unicode.GetBytes("MouseControl$Postion$" + MouseX.ToString() + "$" + MouseY.ToString() + "$" + pictureBox1.Width.ToString() + "$" + pictureBox1.Height.ToString());
                MouseControlStream.Write(buffer, 0, buffer.Length);
                MouseControlStream.Flush();
            }

            Thread.Sleep(400);
        }
    }

    -client
    private void StartMouseControl()
    {
        int BUFFERSIZE = 72;
        int read;
        byte[] buffer = new byte[BUFFERSIZE];

        while (MouseControlDataSock.Connected)
        {
            /* seperate protocol data from server and save in Sep_message[] */
            MouseControlstream = MouseControlDataSock.GetStream();

            read = 0;
            while (read < buffer.Length)
            {
                int readbyte = MouseControlstream.Read(buffer, read, buffer.Length - read);
                if (readbyte == 0)
                {
                    break;
                }
                read += readbyte;
            }
            MouseControlstream.Flush();

            string message = Encoding.Unicode.GetString(buffer, 0, read);

            string splitter = "$";
            char[] split = splitter.ToArray();

            string[] Sep_message = message.Split(split, StringSplitOptions.RemoveEmptyEntries);

            if (Sep_message[0].Equals("MouseControl"))
            {
                if (Sep_message[1].Equals("Postion"))
                {
                    // Mouse_X_Position, Mouse_Y_Position, pictureBox.Width, pictureBox.Height
                    int MouseX_FromServer = int.Parse(Sep_message[2]);
                    int MouseY_FromServer = int.Parse(Sep_message[3]);
                    int PicBoxWidth_FromServer = int.Parse(Sep_message[4]);
                    int PicBoxHeight_FromServer = int.Parse(Sep_message[5]);
                }
            }

            Thread.Sleep(100);
        }
    }
</code>```

答:
You seem to be assuming that your data arrives in the same units in which it is sent; that might work with UDP, but with a TCP stream there is no such guarantee - and if you have automatic buffering and/or "nagle" enabled, it certainly isn't going to happen. So: when you have "some data" from the socket, message could be (any of):

exactly one message

half of one message

a single character

one and a bit messages

the end of one message, 17 entire messages, and the start of another

In the case of unicode, it could also be parts of a single character - which is why you should work in binary until you know you have a "frame", and only do unicode decoding inside a frame. So you also need to account for:

the end of one character, one entire character, and half of another character (zero frames)

It is your job to split the TCP stream into "frames" (i.e. logical messages inside a stream). Since this is a text-based protocol, newlines would be the obvious way to track entire messages. It is also your job to keep a back-buffer of data that you aren't able to process yet - i.e. incomplete frames; which should (as mentioned) be binary unless you know you are only ever going to see ASCII data.

Title: c# Wrong data in Sokcet programming

Body:
I've been developing simple remote desktop program sending, receiving screen images between server, client and doing mouse control, keyboard control.

When I attempted to send server mouse X,Y position to client to control, client received wrong data.

ex) server sends data which is MouseControl$Position$10(Mouse_X_Position)$10(Mouse_Y_Position)$450(pictureBox.Width)$450(pictureBox.Height). It works well at first, client receives the same data that server sent. But, a few seconds later client receives data like ntrol$Position$10(Mouse_X_Position)$10(Mouse_Y_Position)$450(pictureBox.Width)$450(pictureBox.Height). Some part of The first word MouseControl is disappeared while server still sends right data MouseControl$Position$10(Mouse_X_Position)$10(Mouse_Y_Position)$450(pictureBox.Width)$450(pictureBox.Height)

Help me out of this trouble. I want to know why it is happening
Thank you in advance!

Here is my code below

    -server
    private void StartMouseControl()
    {
        NetworkStream MouseControlStream = MouseControlDataSock.GetStream();
        byte[] buffer = null;

        while (true)
        {
            Point PointXY = pictureBox1.PointToClient(new Point(Control.MousePosition.X, Control.MousePosition.Y));
            int MouseX = PointXY.X;
            int MouseY = PointXY.Y;

            /* when mouse pointer in pictureBox ... */
            if ((MouseX >= 0 && MouseX <= pictureBox1.Width) && (MouseY >= 0 && MouseY <= pictureBox1.Height))
            {
                MouseControlStream.Flush();
                buffer = Encoding.Unicode.GetBytes("MouseControl$Postion$" + MouseX.ToString() + "$" + MouseY.ToString() + "$" + pictureBox1.Width.ToString() + "$" + pictureBox1.Height.ToString());
                MouseControlStream.Write(buffer, 0, buffer.Length);
                MouseControlStream.Flush();
            }

            Thread.Sleep(400);
        }
    }

    -client
    private void StartMouseControl()
    {
        int BUFFERSIZE = 72;
        int read;
        byte[] buffer = new byte[BUFFERSIZE];

        while (MouseControlDataSock.Connected)
        {
            /* seperate protocol data from server and save in Sep_message[] */
            MouseControlstream = MouseControlDataSock.GetStream();

            read = 0;
            while (read < buffer.Length)
            {
                int readbyte = MouseControlstream.Read(buffer, read, buffer.Length - read);
                if (readbyte == 0)
                {
                    break;
                }
                read += readbyte;
            }
            MouseControlstream.Flush();

            string message = Encoding.Unicode.GetString(buffer, 0, read);

            string splitter = "$";
            char[] split = splitter.ToArray();

            string[] Sep_message = message.Split(split, StringSplitOptions.RemoveEmptyEntries);

            if (Sep_message[0].Equals("MouseControl"))
            {
                if (Sep_message[1].Equals("Postion"))
                {
                    // Mouse_X_Position, Mouse_Y_Position, pictureBox.Width, pictureBox.Height
                    int MouseX_FromServer = int.Parse(Sep_message[2]);
                    int MouseY_FromServer = int.Parse(Sep_message[3]);
                    int PicBoxWidth_FromServer = int.Parse(Sep_message[4]);
                    int PicBoxHeight_FromServer = int.Parse(Sep_message[5]);
                }
            }

            Thread.Sleep(100);
        }
    }


问:
Set Tkinter Label Text from SharedCtypes array
Ok, i have some multiprocess code and i try to monitor the value of some array in my program. I do some research but still not found any solution here is my code

```<code>from tkinter import *
from tkinter.ttk import *
import multiprocessing as mp
from multiprocessing.sharedctypes import Array
import time

class Form:
    def __init__(self, timer):
        window = Tk()
        window.wm_title('Multiprocess Monitor')

        tvar = StringVar()
        tvar.set(timer)

        ArrayStat = Label(window, textvariable = tvar)

        window.loop()

def Countdown(timer):
    while True:
        for i,v in enumerate(timer):
            timer[i] = v-1
        time.sleep(1)

if __name__ == '__main__':
    timer = Array('i',[-1,-1,-1,-1])
    Ptimer = mp.Process(target = Countdown, args=(timer,))
    Ptimer.daemon = True
    Ptimer.start()

    app = Form(timer)

    Ptimer.join()
</code>```

The normal way to print sharedctypes array is print(timer[:]). But if use this way in tvar => tvar.set(timer[:]) , my GUI didn't updating the text in label. if i use tvar.set(timer) , the label will show <&SychronizedArray bla bla bla.....> Is there any possible solution? thanks

答:
```<code>from tkinter import *
from tkinter.ttk import *
import multiprocessing as mp
from multiprocessing.sharedctypes import Array
import time

class Form(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.title('Multiprocess Monitor')
        self.ArrayStat = Label(self, text="test")
        self.ArrayStat.pack()

        self.after(10, self.update_label)

    def update_label(self):
        self.ArrayStat.configure(text=timer[:])
        self.after(10, self.update_label)

def Countdown(timer):
    while True:
        for i,v in enumerate(timer):
            timer[i] = v-1
        time.sleep(1)

if __name__ == '__main__':
    app = Form()
    timer = Array('i',[-1,-1,-1,-1])
    Ptimer = mp.Process(target = Countdown, args=(timer,))
    Ptimer.daemon = True
    Ptimer.start()

    app.mainloop()

    Ptimer.join()
</code>```

your code as posted wouldn't even run, undeclared variables etc.
you also hadn't packed/gridded/placed your label so nothing would ever appear.
because a tkinter window cannot be serialised for passing between processes an update of the label cannot be directly called, however an after loop can keep checking the value of the timer variable which is shared between the two processes.
also its bad practice to call mainloop inside the constructor, so i have moved it out into the if __name__ == '__main__' block.

Body:
Ok, i have some multiprocess code and i try to monitor the value of some array in my program. I do some research but still not found any solution here is my code

from tkinter import *
from tkinter.ttk import *
import multiprocessing as mp
from multiprocessing.sharedctypes import Array
import time

class Form:
    def __init__(self, timer):
        window = Tk()
        window.wm_title('Multiprocess Monitor')

        tvar = StringVar()
        tvar.set(timer)

        ArrayStat = Label(window, textvariable = tvar)

        window.loop()

def Countdown(timer):
    while True:
        for i,v in enumerate(timer):
            timer[i] = v-1
        time.sleep(1)

if __name__ == '__main__':
    timer = Array('i',[-1,-1,-1,-1])
    Ptimer = mp.Process(target = Countdown, args=(timer,))
    Ptimer.daemon = True
    Ptimer.start()

    app = Form(timer)

    Ptimer.join()

The normal way to print sharedctypes array is print(timer[:]). But if use this way in tvar => tvar.set(timer[:]) , my GUI didn't updating the text in label. if i use tvar.set(timer) , the label will show <&SychronizedArray bla bla bla.....> Is there any possible solution? thanks

Body:
from tkinter import *
from tkinter.ttk import *
import multiprocessing as mp
from multiprocessing.sharedctypes import Array
import time

class Form(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.title('Multiprocess Monitor')
        self.ArrayStat = Label(self, text="test")
        self.ArrayStat.pack()

        self.after(10, self.update_label)

    def update_label(self):
        self.ArrayStat.configure(text=timer[:])
        self.after(10, self.update_label)

def Countdown(timer):
    while True:
        for i,v in enumerate(timer):
            timer[i] = v-1
        time.sleep(1)

if __name__ == '__main__':
    app = Form()
    timer = Array('i',[-1,-1,-1,-1])
    Ptimer = mp.Process(target = Countdown, args=(timer,))
    Ptimer.daemon = True
    Ptimer.start()

    app.mainloop()

    Ptimer.join()

your code as posted wouldn't even run, undeclared variables etc.
you also hadn't packed/gridded/placed your label so nothing would ever appear.
because a tkinter window cannot be serialised for passing between processes an update of the label cannot be directly called, however an after loop can keep checking the value of the timer variable which is shared between the two processes.
also its bad practice to call mainloop inside the constructor, so i have moved it out into the if __name__ == '__main__' block.


问:
Database Design
I'm trying to model nested relationships and am having a tough time getting to where I want to be.  I want to present an example that will hopefully answer some of my questions; its based on geography.

I'd like to have a single Region entity.  This region entity allows for Planets, Continents and Countries.

I would basically have a single Region called Earth.  This would be the first level of the hierarchy.  Then I would have the 7 Continents which would be nested within Region Earth.  Then I would add all the countries of the world and associate each with their outer continent.  There may be edges cases (I don't know if there are in this example, but I want there to be) where a Country belongs to more than one continent.

What I essentially want to get to is the ability to say:

Select All Countries in a Continent.  I'd like the ability to indefinitely nest too; so the next layer would be states/provinces.  So I could then say I want all provinces in North America.

I can kind of envision how the SQL would look, but I don't know how to do the multi-tier nesting:

```<code>Select *
From Region Outer, Region Inner
Where Outer.Name = "North America"
AND Inner.Type = "State"
</code>```

I've come up with just a simple Region entity and then a self-referential Parent-Child entity:

```<code>Region {RegionID, Name, Type}
SubRegion {ParentID, ChildID}
</code>```

I'm most interested in learning how this should be achieved.  If I'm making incorrect or poor design decisions/assumptions feel free to make your own suggestion.  I'm also not explicitly interested in the geographic stuff, I just thought it was a good example that illustrated what I am trying to accomplish.

I'm trying to do this in SQL 2008 R2 with C# and Linq.

This feels like a hierarchical network graph, so I think there should be a well understood way to do this; I just don't know it..

答:
Why complicate things?

Just have "country","continent","state","county","city" and "district" columns in your table.

The "country" and "continent" may seem redundant but "Moscow" is in europe and Vladivostock is in asia but both are in the Russian Federation.

Similar situations exist for Turkey, Denmark and Egypt.

Title: Database Design

Body:
I'm trying to model nested relationships and am having a tough time getting to where I want to be.  I want to present an example that will hopefully answer some of my questions; its based on geography.

I'd like to have a single Region entity.  This region entity allows for Planets, Continents and Countries.

I would basically have a single Region called Earth.  This would be the first level of the hierarchy.  Then I would have the 7 Continents which would be nested within Region Earth.  Then I would add all the countries of the world and associate each with their outer continent.  There may be edges cases (I don't know if there are in this example, but I want there to be) where a Country belongs to more than one continent.

What I essentially want to get to is the ability to say:

Select All Countries in a Continent.  I'd like the ability to indefinitely nest too; so the next layer would be states/provinces.  So I could then say I want all provinces in North America.

I can kind of envision how the SQL would look, but I don't know how to do the multi-tier nesting:

Select *
From Region Outer, Region Inner
Where Outer.Name = "North America"
AND Inner.Type = "State"

I've come up with just a simple Region entity and then a self-referential Parent-Child entity:

Region {RegionID, Name, Type}
SubRegion {ParentID, ChildID}

I'm most interested in learning how this should be achieved.  If I'm making incorrect or poor design decisions/assumptions feel free to make your own suggestion.  I'm also not explicitly interested in the geographic stuff, I just thought it was a good example that illustrated what I am trying to accomplish.

I'm trying to do this in SQL 2008 R2 with C# and Linq.

This feels like a hierarchical network graph, so I think there should be a well understood way to do this; I just don't know it..


问:
How do I order by a function in LINQ query?
I am developing my first MVC application with Entity Framework. I have a table USERS and a table RESTRICTIONS

In my controller I wrote a function that returns the number of common restrictions between two users:

```<code>public int common_restrictions(int id1, int id2)
    {
        MyModel bd = new MyModel();
        int count= 0;

        var restrictions = from c in bd.RESTRICTIONS where c.ID_USER == id1
        select c;
        var restrictions2 = from c in bd.RESTRICTIONS where c.ID_USER == id2
        select c;

        foreach (var prop in restrictions)
        {
            var nr = restrictions2.Count(p => p.ID_PROP == prop.ID_PROP);
            if (nr != 0)
            {
                count++;
            }
        }
        return count;
    }
</code>```

The function works as it supposed to.
Now in another function in the same controller I want to sort the list of users in descending order of their common restrictions with a specific user (let's say user with the id 12). I got the list of users in a query but I don't know how to sort them after that

```<code>var query = from u in bd.USERS where u.ID != 12
                    select u;
// sort the list??
</code>```

I've tried

```<code>        var query = from u in bd.USERS orderby(common_restrictions(u.ID,
                    12)) select u;
</code>```

but I get the following error message:

"LINQ to Entities does not recognize the method 'Int32 common_restrictions (Int32, Int32)' method, and this method cannot be translated into a store expression."

答:
You need to do this in two steps if you don't want to include another property to your User object. And I think this following way is easier.</p>

```<code>      var query = (from u in bd.USERS where u.ID != 12
                select u).ToList();
      var unSorteUsers = (from u in query
                            select new
                            {

                                User = u,
                                CR = common_restrictions(u.ID,12)
                            });

        var sortedUsers = (from u in unSorteUsers

                           orderby u.CR
                           select new User
                           {

                               ID = u.User.ID,
                               //All other properties.
                           });
</code>```

Body:
I am developing my first MVC application with Entity Framework. I have a table USERS and a table RESTRICTIONS

In my controller I wrote a function that returns the number of common restrictions between two users:

public int common_restrictions(int id1, int id2)
    {
        MyModel bd = new MyModel();
        int count= 0;

        var restrictions = from c in bd.RESTRICTIONS where c.ID_USER == id1
        select c;
        var restrictions2 = from c in bd.RESTRICTIONS where c.ID_USER == id2
        select c;

        foreach (var prop in restrictions)
        {
            var nr = restrictions2.Count(p => p.ID_PROP == prop.ID_PROP);
            if (nr != 0)
            {
                count++;
            }
        }
        return count;
    }

The function works as it supposed to.
Now in another function in the same controller I want to sort the list of users in descending order of their common restrictions with a specific user (let's say user with the id 12). I got the list of users in a query but I don't know how to sort them after that

var query = from u in bd.USERS where u.ID != 12
                    select u;
// sort the list??

I've tried

        var query = from u in bd.USERS orderby(common_restrictions(u.ID,
                    12)) select u;

but I get the following error message:

"LINQ to Entities does not recognize the method 'Int32 common_restrictions (Int32, Int32)' method, and this method cannot be translated into a store expression."

Body:
You need to do this in two steps if you don't want to include another property to your User object. And I think this following way is easier.

      var query = (from u in bd.USERS where u.ID != 12
                select u).ToList();
      var unSorteUsers = (from u in query
                            select new
                            {

                                User = u,
                                CR = common_restrictions(u.ID,12)
                            });

        var sortedUsers = (from u in unSorteUsers

                           orderby u.CR
                           select new User
                           {

                               ID = u.User.ID,
                               //All other properties.
                           });


问:
MySQL - ORDER BY, CASE and DESC
I have a PHP variable called $var. I want to sort my result in dependence of $var. This one works:

```<code>$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber
    END";
</code>```

But when $var is 3 I need to sort by someNumber with DESC. So I tried this:

```<code>$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber DESC
    END";
</code>```

This one throws a syntax error. How can I achieve this?

答:
Split this into three case expressions:

```<code>ORDER BY (CASE WHEN $var = 1 THEN myText1 END) ASC,
         (CASE WHEN $var = 2 THEN myText2 END) ASC,
         (CASE WHEN $var = 3 THEN someNumber END) DESC
</code>```

The ASC is optional, of course -- there just to contract with the DESC.

More importantly, this removes the automatic conversion.  A CASE expression returns only one type.  When you mix different types, then some sort of conversion takes place.  That conversion can affect the ordering of the values.  This fixes that problem.

Title: MySQL - ORDER BY, CASE and DESC

Body:
I have a PHP variable called $var. I want to sort my result in dependence of $var. This one works:

$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber
    END";

But when $var is 3 I need to sort by someNumber with DESC. So I tried this:

$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber DESC
    END";

This one throws a syntax error. How can I achieve this?

Body:
Split this into three case expressions:

ORDER BY (CASE WHEN $var = 1 THEN myText1 END) ASC,
         (CASE WHEN $var = 2 THEN myText2 END) ASC,
         (CASE WHEN $var = 3 THEN someNumber END) DESC

The ASC is optional, of course -- there just to contract with the DESC.

More importantly, this removes the automatic conversion.  A CASE expression returns only one type.  When you mix different types, then some sort of conversion takes place.  That conversion can affect the ordering of the values.  This fixes that problem.


问:
How to make multi level dropdown menu using select option mentod
i want to make multi level dropdown menu using select and option method</p>

```<code><select>
   <option value="" data-display-text="Select">None</option>
   <option value="oranges">SSC</option>
   <option value="oranges">GATE</option>
   <option value="bananas">BANK PO</option>
   <option value="bananas">RAILWAY</option>
 </select>
</code>```

答:
If you want to use ONE select you could use <optgroup/>. See example.
Note: it's not very multi-level, but it allows for some kind of relevant grouping.

<select>
  <option value="" selected="selected">Select an option...</option>
  <optgroup label="SSC">
    <option value="oranges1">some option</option>
    <option value="oranges2">some option</option>
    <option value="oranges3">some option</option>
  </optgroup>
  <optgroup label="GATE">
    <option value="bananas1">some option</option>
    <option value="bananas2">some option</option>
    <option value="bananas3">some option</option>
  </optgroup>
  <optgroup label="BANK PO">
    <option value="apples1">some option</option>
    <option value="apples2">some option</option>
    <option value="apples3">some option</option>
  </optgroup>
  <optgroup label="RAILWAY">
    <option value="grapes1">some option</option>
    <option value="grapes2">some option</option>
    <option value="grapes3">some option</option>
  </optgroup>
</select>```

Body:
i want to make multi level dropdown menu using select and option method

<select>
   <option value="" data-display-text="Select">None</option>
   <option value="oranges">SSC</option>
   <option value="oranges">GATE</option>
   <option value="bananas">BANK PO</option>
   <option value="bananas">RAILWAY</option>
 </select>


问:
how to send device farm test(espresso) report in mail from jenkins
I have configured jenkins to send mail to specific people for every build. I want to send test report along with text. How to do that? If you can help.</p>

答: Simply use Email-ext plugin - https://wiki.jenkins-ci.org/display/JENKINS/Email-ext+plugin and use it in jenkins job 'editable email notification'</p>


问:
Split a Sentences String into sentence per line in Java
I want to split the sentences into one sentence per line in Java.

Input String:
"Volatility returned to the municipal bond market during the first half of the funds’ fiscal year as investors weighed the potential impact of the U.S. presidential election, strengthening economic conditions and rising interest rates. The market was further pressured by a record level of municipal bond issuance in 2016. Against this backdrop, all six funds registered declines, ranging from –0.92% for American Funds Short-Term Tax-Exempt Bond Fund to –3.77% for American High-Income Municipal Bond Fund. (See pages 4 through 10 for fund specific results and information.)"

Output:

Sentence1: Volatility returned to the municipal bond market during the first half of the funds’ fiscal year as investors weighed the potential impact of the U.S. presidential election, strengthening economic conditions and rising interest rates.

Sentence2: The market was further pressured by a record level of municipal bond issuance in 2016. Against this backdrop, all six funds registered declines, ranging from –0.92% for American Funds Short-Term Tax-Exempt Bond Fund to –3.77% for American High-Income Municipal Bond Fund.

Sentence3:(See pages 4 through 10 for fund specific results and information.

I have written a java code to split the Sentences when .('Full stop') occurs, A new line has been coming after U.S.

string = string.replace(". ", ".\n")

答:
Try something like this inside your code:

```<code>List<String> eachLine = new ArrayList<String>();
String initialString = new String("Volatility returned to the municipal bond market during the first half of the funds’ fiscal year as investors weighed the potential impact of the U.S. presidential election, strengthening economic conditions and rising interest rates. The market was further pressured by a record level of municipal bond issuance in 2016. Against this backdrop, all six funds registered declines, ranging from –0.92% for American Funds Short-Term Tax-Exempt Bond Fund to –3.77% for American High-Income Municipal Bond Fund. (See pages 4 through 10 for fund specific results and information.)");

int stopIndex = initialString.indexOf( '. ' );//I am searching for the first occurance of '. ' in the string.
//Note full stop followed blank space, which would denote either end of a sentence or words like U.K. or U.S. etc.

boolean UpperCase = checkForUpperCase(stopIndex+1);//write a function to check whether the alphabet/character following '. ' is in uppercase or not
//checking for Uppercase because a senetence starts with Uppercase
if(UpperCase){
   eachLine.add(initialString.substring(0,stopIndex));//add the sentence to List<String> to be processed later
   initialString = initialString.substring(stopIndex+1);//storing the rest of the sentence in the same string to be processed again
}
//keep parsing till you parse the whole string
</code>```

You can get general idea regarding how you may check for Uppercase from here: Java Program to test if a character is uppercase/lowercase/number/vowel

The aforementioned code is just a snippet to provide you understanding of how you may achieve your goal or approach your issue.

You can also use Regular Expressions to find the full stop pattern as well, but understanding the basic approach might be more useful later.

Regular Expressions in Java: https://www.tutorialspoint.com/java/java_regular_expressions.htm

Body:
Try something like this inside your code:

List<String> eachLine = new ArrayList<String>();
String initialString = new String("Volatility returned to the municipal bond market during the first half of the funds’ fiscal year as investors weighed the potential impact of the U.S. presidential election, strengthening economic conditions and rising interest rates. The market was further pressured by a record level of municipal bond issuance in 2016. Against this backdrop, all six funds registered declines, ranging from –0.92% for American Funds Short-Term Tax-Exempt Bond Fund to –3.77% for American High-Income Municipal Bond Fund. (See pages 4 through 10 for fund specific results and information.)");

int stopIndex = initialString.indexOf( '. ' );//I am searching for the first occurance of '. ' in the string.
//Note full stop followed blank space, which would denote either end of a sentence or words like U.K. or U.S. etc.

boolean UpperCase = checkForUpperCase(stopIndex+1);//write a function to check whether the alphabet/character following '. ' is in uppercase or not
//checking for Uppercase because a senetence starts with Uppercase
if(UpperCase){
   eachLine.add(initialString.substring(0,stopIndex));//add the sentence to List<String> to be processed later
   initialString = initialString.substring(stopIndex+1);//storing the rest of the sentence in the same string to be processed again
}
//keep parsing till you parse the whole string

You can get general idea regarding how you may check for Uppercase from here: Java Program to test if a character is uppercase/lowercase/number/vowel

The aforementioned code is just a snippet to provide you understanding of how you may achieve your goal or approach your issue.

You can also use Regular Expressions to find the full stop pattern as well, but understanding the basic approach might be more useful later.

Regular Expressions in Java: https://www.tutorialspoint.com/java/java_regular_expressions.htm


问:
Confirming the difference between import * and from xxx import *
I was surprised to find out that

```<code>import foo
</code>```

and

```<code>from foo import *
</code>```

had different effects on global members.  I wanted to confirm that my experiments are the correct behavior.

In the first example, changing a member in module foo will reflect in all code that imports foo.  However, changing that member in the later case only seems to affect the file into which it was imported.  In other words, using the later approach will give each importing file its own copy of the members from foo.

the behavior i want is to have access to foo.x from all files, be able to change it from all files, and have that change reflected in all files ( a true global if you will).

答:
Yes, your observations are correct. This is a consequence of the way that binding works in Python.

When one does

```<code>import foo
</code>```

then foo becomes a global name that references the module foo. When one does

```<code>foo.bar = 7
</code>```

Then the reference is followed and the object foo is loaded. Then 7 is stored in the bar attribute.

When another module imports foo, it just pulls the object out of sys.modules['foo'] and gets the modified value.

When one does

```<code>from foo import bar
</code>```

globals()['bar'] is set to reference foo.bar. When one later does

```<code> bar = 7
</code>```

globals()['bar'] no longer references foo.bar but references a copy of 7. That is, the original binding in the global scope of the importing module is simply replaced.

In the fist example, one is modifying attributes of an object that is stored in sys.modules and will be common to all modules that have imported it. In the second example, one is modifying the global scope of the importing module.

If one was to do something along the lines of

```<code> from foo import fobaz
 fobaz.foobar = 7
</code>```

Then that change would be propagated to other importing modules because one is not overwriting the global reference but following it to modify an attribute of the object that it points to. So essentially, you should be able to modify mutable objects so long as you don't overwrite the global binding.

I think that something like this is the closest that you are going to be able to cleanly get to a true global in python. As a language, it greatly values namespaces.

Body:
I was surprised to find out that

import foo

and

from foo import *

had different effects on global members.  I wanted to confirm that my experiments are the correct behavior.

In the first example, changing a member in module foo will reflect in all code that imports foo.  However, changing that member in the later case only seems to affect the file into which it was imported.  In other words, using the later approach will give each importing file its own copy of the members from foo.

the behavior i want is to have access to foo.x from all files, be able to change it from all files, and have that change reflected in all files ( a true global if you will).

Body:
Yes, your observations are correct. This is a consequence of the way that binding works in Python.

When one does

import foo

then foo becomes a global name that references the module foo. When one does

foo.bar = 7

Then the reference is followed and the object foo is loaded. Then 7 is stored in the bar attribute.

When another module imports foo, it just pulls the object out of sys.modules['foo'] and gets the modified value.

When one does

from foo import bar

globals()['bar'] is set to reference foo.bar. When one later does

 bar = 7

globals()['bar'] no longer references foo.bar but references a copy of 7. That is, the original binding in the global scope of the importing module is simply replaced.

In the fist example, one is modifying attributes of an object that is stored in sys.modules and will be common to all modules that have imported it. In the second example, one is modifying the global scope of the importing module.

If one was to do something along the lines of

 from foo import fobaz
 fobaz.foobar = 7

Then that change would be propagated to other importing modules because one is not overwriting the global reference but following it to modify an attribute of the object that it points to. So essentially, you should be able to modify mutable objects so long as you don't overwrite the global binding.

I think that something like this is the closest that you are going to be able to cleanly get to a true global in python. As a language, it greatly values namespaces.