问:
Automatically accept all SDK licences
Since gradle android plugins 2.2-alpha4:

Gradle will attempt to download missing SDK packages that a project
depends on

Which is amazingly cool and was know to be a JakeWharton project.

But, to download the SDK library you need to: accept the license agreements or gradle tells you:

You have not accepted the license agreements of the following SDK
components: [Android SDK Build-Tools 24, Android SDK Platform 24].
Before building your project, you need to accept the license
agreements and complete the installation of the missing components
using the Android Studio SDK Manager. Alternatively, to learn how to
transfer the license agreements from one workstation to another, go to
http://d.android.com/r/studio-ui/export-licenses.html

And this is a problem because I would love to install all sdk dependencies while doing a gradle build.

I am looking for a solution to automatically accept all licenses. Maybe a gradle script ?
Do you have any ideas ?

答:
I had the same error while using Cordova.

The problem was due to the fact that I installed Android Sdk through Android Studio and through apt with apt install android-sdk adb. And Cordova was calling the files installed through apt instead of the files in my home directory.

It worked once I changed the path to SDK in bash:

```<code># Change path
export ANDROID_HOME="$HOME/Android/Sdk/"
echo "Android home = $ANDROID_HOME"
# Accept licenses
eval "${ANDROID_HOME}/tools/bin/sdkmanager --licenses"
# Run Cordova
cordova build android
</code>```

Then I removed the system files that weren't used anymore: apt remove android-sdk adb.

Title: Automatically accept all SDK licences

Body:
I had the same error while using Cordova.

The problem was due to the fact that I installed Android Sdk through Android Studio and through apt with apt install android-sdk adb. And Cordova was calling the files installed through apt instead of the files in my home directory.

It worked once I changed the path to SDK in bash:

# Change path
export ANDROID_HOME="$HOME/Android/Sdk/"
echo "Android home = $ANDROID_HOME"
# Accept licenses
eval "${ANDROID_HOME}/tools/bin/sdkmanager --licenses"
# Run Cordova
cordova build android

Then I removed the system files that weren't used anymore: apt remove android-sdk adb.


来源: stackexchange

问:
Java - Create Zip-file with multiple files from different locations with subfolders
I am trying to generate a zip file in Java, that contains several files of different types (e.g. images, fonts etc) that are lying in different locations. Furthermore I want the zip file to have subfolders where the files are put by their type (e.g. images should go to the images folder within the zip.

These are the files that I have (each can be in a different location):

index.html

img1.jpg

img2.jpg

font1.woff

font2.woff

style.css

custom.js

And this is how they should be in the zip file:

index.html

images/img1.jpg

images/img2.jpg

fonts/font1.woff

fonts/font2.woff

js/custom.js

css/styles.css

So far I have managed to take one file in a specific path and prompt the user for the output location. A zip-file will be generated with the file that is specified in the input. Here is the code I have so far:

```<code>JFrame parentFrame = new JFrame();

JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Speicherort auswählen");

int userSelection = fileChooser.showSaveDialog(parentFrame);
String pathToFile;

if (userSelection == JFileChooser.APPROVE_OPTION) {
    File fileToSave = fileChooser.getSelectedFile();
    print(fileToSave.getAbsolutePath());
    pathToFile = fileToSave.getAbsolutePath();
}

pathToFile = pathToFile.replace("\\", "/");

String outFileName = pathToFile;
String inFileName = "C:/Users/asoares/Desktop/mobio_export_test/index.html";
ZipOutputStream zos = null;
FileInputStream fis = null;

try {
    zos = new ZipOutputStream(new FileOutputStream(outFileName));
    fis = new FileInputStream(inFileName);
    zos.putNextEntry(new ZipEntry(new File(inFileName).getName()));
    int len;
    byte[] buffer = new byte[2048];
    while((len = fis.read(buffer, 0, buffer.length)) > 0) {
        zos.write(buffer, 0, len);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if(fis != null){
        try {
            fis.close();
        } catch (IOException e) {}
    }
    if(zos != null){
        try {
            zos.closeEntry();
            zos.close();
        } catch (IOException e) {}
    }
}
</code>```

I would be really glad if someone can help me!!!

答:
It should work like this.

The zip directory name should at best be created by another method (there are more image types than jpg :)).

```<code>public static Path zip(List<Path> files, Path zipFileTarget) throws IOException {
    try (FileOutputStream fos = new FileOutputStream(zipFileTarget.toFile());
         ZipOutputStream zos = new ZipOutputStream(fos)) {
        if (!Files.exists(zipFileTarget))
            Files.createFile(zipFileTarget);
        createEntries(files, zos);
        zos.close();
        return zipFileTarget;
    }
}

private static List<String> createEntries(List<Path> files, ZipOutputStream zos) throws IOException {
    List<String> zippedFiles = new ArrayList<>();
    Matcher matcherFileExt = Pattern.compile("^.*\\.([^.]+)$").matcher("");
    for (Path f : files) {
        if (Files.isRegularFile(f)) {
            String fileName = f.getFileName().toString();
            String fileExt = matcherFileExt.reset(fileName).matches()
                    ? matcherFileExt.replaceAll("$1")
                    : "unknown";
            // You should determine the dir name with a more sophisticated
            // approach.
            String dir;
            if      (fileExt.equals("jpg")) dir = "images";
            else if (fileExt.equals("woff")) dir = "fonts";
            else    dir = fileExt;

            zos.putNextEntry(new ZipEntry(dir + "/" + fileName));
            Files.copy(f, zos);
            zippedFiles.add(fileName);
        }
    }
    return zippedFiles;
}
</code>```

Edit: this approach works with java 1.7+. You can easily convert a File object to a Path object by calling its toPath() method.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to generate a zip file in Java, that contains several files of different types (e.g. images, fonts etc) that are lying in different locations. Furthermore I want the zip file to have subfolders where the files are put by their type (e.g. images should go to the images folder within the zip.

These are the files that I have (each can be in a different location):

index.html

img1.jpg

img2.jpg

font1.woff

font2.woff

style.css

custom.js

And this is how they should be in the zip file:

index.html

images/img1.jpg

images/img2.jpg

fonts/font1.woff

fonts/font2.woff

js/custom.js

css/styles.css

So far I have managed to take one file in a specific path and prompt the user for the output location. A zip-file will be generated with the file that is specified in the input. Here is the code I have so far:

JFrame parentFrame = new JFrame();

JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Speicherort auswählen");

int userSelection = fileChooser.showSaveDialog(parentFrame);
String pathToFile;

if (userSelection == JFileChooser.APPROVE_OPTION) {
    File fileToSave = fileChooser.getSelectedFile();
    print(fileToSave.getAbsolutePath());
    pathToFile = fileToSave.getAbsolutePath();
}

pathToFile = pathToFile.replace("\\", "/");

String outFileName = pathToFile;
String inFileName = "C:/Users/asoares/Desktop/mobio_export_test/index.html";
ZipOutputStream zos = null;
FileInputStream fis = null;

try {
    zos = new ZipOutputStream(new FileOutputStream(outFileName));
    fis = new FileInputStream(inFileName);
    zos.putNextEntry(new ZipEntry(new File(inFileName).getName()));
    int len;
    byte[] buffer = new byte[2048];
    while((len = fis.read(buffer, 0, buffer.length)) > 0) {
        zos.write(buffer, 0, len);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if(fis != null){
        try {
            fis.close();
        } catch (IOException e) {}
    }
    if(zos != null){
        try {
            zos.closeEntry();
            zos.close();
        } catch (IOException e) {}
    }
}

I would be really glad if someone can help me!!!

Body:
It should work like this.

The zip directory name should at best be created by another method (there are more image types than jpg :)).

public static Path zip(List<Path> files, Path zipFileTarget) throws IOException {
    try (FileOutputStream fos = new FileOutputStream(zipFileTarget.toFile());
         ZipOutputStream zos = new ZipOutputStream(fos)) {
        if (!Files.exists(zipFileTarget))
            Files.createFile(zipFileTarget);
        createEntries(files, zos);
        zos.close();
        return zipFileTarget;
    }
}

private static List<String> createEntries(List<Path> files, ZipOutputStream zos) throws IOException {
    List<String> zippedFiles = new ArrayList<>();
    Matcher matcherFileExt = Pattern.compile("^.*\\.([^.]+)$").matcher("");
    for (Path f : files) {
        if (Files.isRegularFile(f)) {
            String fileName = f.getFileName().toString();
            String fileExt = matcherFileExt.reset(fileName).matches()
                    ? matcherFileExt.replaceAll("$1")
                    : "unknown";
            // You should determine the dir name with a more sophisticated
            // approach.
            String dir;
            if      (fileExt.equals("jpg")) dir = "images";
            else if (fileExt.equals("woff")) dir = "fonts";
            else    dir = fileExt;

            zos.putNextEntry(new ZipEntry(dir + "/" + fileName));
            Files.copy(f, zos);
            zippedFiles.add(fileName);
        }
    }
    return zippedFiles;
}

Edit: this approach works with java 1.7+. You can easily convert a File object to a Path object by calling its toPath() method.


问:
Retrieving Dictionary Item value based on wildcard - VBA Excel
At the moment I am running over a dictionary so that I can fill missing values in a table based on the stored keys within it. The problem is that my table has more values (keys) than the ones stored in the dictionary. In some cases the information in my table is similar to the a certain key in the Dictionary and i was wondering if it is possible to use a wildcard to retrieve the items. Example below:

Example records in dictionary:

Mercedes (key) car   (item)

Kawasaki (key) motor (item)

Lets assume my table has the following entry:

Merc (key) but is missing the item, which should be "car" in this case.

Is it possible to make this happen? I am sorry if the example is bad, but I hope any of you can help me.

I found several articles on the topic:

Wildcard search of dictionary

How to search for a part of a dictionary key? - VB.Net

Thank you in advance!

答:
You can write a function which returns a boolean.

```<code>Public Function KeywordExists(ByVal Keyword As String) As Boolean
    Dim k As Variant
    For Each k In objDict.Keys  'Your dictionary object
        If Keyword Like "*" & k & "*" Then
            KeywordExists = True
            Exit For
        End If
    Next k
End Function
</code>```

To call it:

```<code>If KeywordExists("Foo") then '...
</code>```

Edit:

To return the key, simply change the return type to string.

```<code>Public Function StringKeyword(ByVal Keyword As String) As String
    Dim k As Variant
    For Each k In objDict.Keys  'Your dictionary object
        If Keyword Like "*" & k & "*" Then
            StringKeyword = K
            Exit For
        End If
    Next k
End Function
</code>```

To call it:

```<code>Dim key As String
    key = StringKeyword("Foo")
</code>```

Body:
You can write a function which returns a boolean.

Public Function KeywordExists(ByVal Keyword As String) As Boolean
    Dim k As Variant
    For Each k In objDict.Keys  'Your dictionary object
        If Keyword Like "*" & k & "*" Then
            KeywordExists = True
            Exit For
        End If
    Next k
End Function

To call it:

If KeywordExists("Foo") then '...

Edit:

To return the key, simply change the return type to string.

Public Function StringKeyword(ByVal Keyword As String) As String
    Dim k As Variant
    For Each k In objDict.Keys  'Your dictionary object
        If Keyword Like "*" & k & "*" Then
            StringKeyword = K
            Exit For
        End If
    Next k
End Function

To call it:

Dim key As String
    key = StringKeyword("Foo")


问:
Functional Programming Python: smallest number divisible by each of the numbers 1 to 20
I want to build a while loop in python using its functional programming capabilities, but until now I'm failing.

What I have accomplished is this peace of code, which should calculate the smallest number divisible by each of the numbers 1 to 20. But it doens't seem it's using functional programming capabilities a lot. And also gives me the error as below:

"RuntimeError: maximum recursion depth exceeded" at the line of the incrementation of "i";

even if this should be limited to 20.

```<code>def byYmult(x, y): return x % y == 0
def first20div():
    i=0
    for y in range(1,20):
        i += byYmult(x, y)
    return i >= 20

def while_block():
    global x
    if first20div():
        print(x)
        return 1
    else:
        x += 1
    return 0

x = 0
while_FP = lambda: ((not first20div()) and while_block() ) or while_FP()
while_FP()
</code>```

答:
This is non-functial for a lot of reasons:

you do not pass, nor return functions;

you only construct a named lambda expression at the bottom, but this is usually considered un-Pythonic;

usually functional programming means you do not alter data, but here you define a global x, that you update;

by some globals are also seen as non-functional: all data should be passed to the function.

So there is a lot to work with. Furthermore the algorithm you describe is not very optimal. Instead of performing a brute force approach where we keep guessing the number until finally we got lucky, a better approach is to calculate the least common multiple (LCM) of the numbers 1..20.

We can first define - in a functional way - we can calculate the LCM by calculating the greatest common divider (GCD) first, and this can be done by the Euclidean Algorithm. Lucky for us, it is already in the math package:

```<code>from math import gcd
</code>```

Now the LCM is:

```<code>def lcm(a,b):
    return (a*b)//gcd(a,b)
</code>```

The LCM of three or more numbers can be calculated by calculating the LCM of the first two numbers and then pass it as first argument to the LCM with the third number, or more formally:

```<code>lcm(x,y,z) == lcm(lcm(x,y),z)
</code>```

and this can be done by using reduce from functools:

```<code>from functools import reduce

def lcm_multiple(xs):
    return reduce(lcm, xs)
</code>```

and now we can calculate the answer, by passing it a range(2,20) object:

```<code>answer = lcm_multiple(range(2, 20))
</code>```

Or in full:

```<code>from math import gcd
from functools import reduce

def lcm(a,b):
    return (a*b)//gcd(a,b)

def lcm_multiple(xs):
    return reduce(lcm, xs)

answer = lcm_multiple(range(2, 20))
</code>```

Body:
I want to build a while loop in python using its functional programming capabilities, but until now I'm failing.

What I have accomplished is this peace of code, which should calculate the smallest number divisible by each of the numbers 1 to 20. But it doens't seem it's using functional programming capabilities a lot. And also gives me the error as below:

"RuntimeError: maximum recursion depth exceeded" at the line of the incrementation of "i";

even if this should be limited to 20.

def byYmult(x, y): return x % y == 0
def first20div():
    i=0
    for y in range(1,20):
        i += byYmult(x, y)
    return i >= 20

def while_block():
    global x
    if first20div():
        print(x)
        return 1
    else:
        x += 1
    return 0

x = 0
while_FP = lambda: ((not first20div()) and while_block() ) or while_FP()
while_FP()

Body:
This is non-functial for a lot of reasons:

you do not pass, nor return functions;

you only construct a named lambda expression at the bottom, but this is usually considered un-Pythonic;

usually functional programming means you do not alter data, but here you define a global x, that you update;

by some globals are also seen as non-functional: all data should be passed to the function.

So there is a lot to work with. Furthermore the algorithm you describe is not very optimal. Instead of performing a brute force approach where we keep guessing the number until finally we got lucky, a better approach is to calculate the least common multiple (LCM) of the numbers 1..20.

We can first define - in a functional way - we can calculate the LCM by calculating the greatest common divider (GCD) first, and this can be done by the Euclidean Algorithm. Lucky for us, it is already in the math package:

from math import gcd

Now the LCM is:

def lcm(a,b):
    return (a*b)//gcd(a,b)

The LCM of three or more numbers can be calculated by calculating the LCM of the first two numbers and then pass it as first argument to the LCM with the third number, or more formally:

lcm(x,y,z) == lcm(lcm(x,y),z)

and this can be done by using reduce from functools:

from functools import reduce

def lcm_multiple(xs):
    return reduce(lcm, xs)

and now we can calculate the answer, by passing it a range(2,20) object:

answer = lcm_multiple(range(2, 20))

Or in full:

from math import gcd
from functools import reduce

def lcm(a,b):
    return (a*b)//gcd(a,b)

def lcm_multiple(xs):
    return reduce(lcm, xs)

answer = lcm_multiple(range(2, 20))


问:
Access perforce command line from P4V
Is there a way to run P4 command line from P4V? I understand that it can be done MS command prompt. But want to know, if it can be invoked via P4v?

Thanks.

答: Helix sadly removed the input textbox in 2017.3.</p>

Title: Access perforce command line from P4V


问:
XPath: Find all known tags with specific attribute
I want to get a list of all trololo tags with attr attribute (but not xxx or any other) using Python from following XML:

```<code><data>
    <test>
        <trololo attr="1">
        </trololo>
    </test>
    <test>
        <trololo>
        </trololo>
    </test>
    <test>
        <trololo attr="X">
        </trololo>
    </test>
    <test>
        <xxx attr="Y">
        </xxx>
    </test>
</data>
</code>```

I've tried using //*[@attr], but result includes xxx tag as well. All other variations I tried are failing so far.

The actual Python code I'm using:

```<code>import xml.etree.ElementTree as ET
from pprint import pprint

tree  = ET.parse('test.xml')
nodes = tree.findall('//*trololo[@attr]')

pprint(nodes)
</code>```

Output:

```<code>[]
</code>```

UPDATE:

I've found out this was a namespace problem, which makes this question a duplicate. The problem was I had a root node looking like this:

```<code><data xmlns="http://example.com">
</code>```

答:
All elements by name with a named attribute

As @har07 correctly answers in the comments, the XPath

```<code>//trololo[@attr]
</code>```

will select all trololo elements with an attr attribute (regardless of its value), as requested.

This string,

```<code>//*trololo[@attr]
</code>```

is syntactically not an XPath expression at all but does resemble,

```<code>//*:trololo[@attr]
</code>```

which is syntactically invalid under XPath 2.0 (but not XPath 1.0).  It says to select trololol elements in any namespace.  To disregard namespaces in XPath 1.0  (but you really shouldn't), use local-name():

```<code>//*[local-name() = 'trololo' and @attr]
</code>```

Other variations

All elements with a named attribute: //*[@attr]

All elements with any attribute: //*[@*]

Body:
I want to get a list of all trololo tags with attr attribute (but not xxx or any other) using Python from following XML:

<data>
    <test>
        <trololo attr="1">
        </trololo>
    </test>
    <test>
        <trololo>
        </trololo>
    </test>
    <test>
        <trololo attr="X">
        </trololo>
    </test>
    <test>
        <xxx attr="Y">
        </xxx>
    </test>
</data>

I've tried using //*[@attr], but result includes xxx tag as well. All other variations I tried are failing so far.

The actual Python code I'm using:

import xml.etree.ElementTree as ET
from pprint import pprint

tree  = ET.parse('test.xml')
nodes = tree.findall('//*trololo[@attr]')

pprint(nodes)

Output:

[]

UPDATE:

I've found out this was a namespace problem, which makes this question a duplicate. The problem was I had a root node looking like this:

<data xmlns="http://example.com">

Body:
All elements by name with a named attribute

As @har07 correctly answers in the comments, the XPath

//trololo[@attr]

will select all trololo elements with an attr attribute (regardless of its value), as requested.

This string,

//*trololo[@attr]

is syntactically not an XPath expression at all but does resemble,

//*:trololo[@attr]

which is syntactically invalid under XPath 2.0 (but not XPath 1.0).  It says to select trololol elements in any namespace.  To disregard namespaces in XPath 1.0  (but you really shouldn't), use local-name():

//*[local-name() = 'trololo' and @attr]

Other variations

All elements with a named attribute: //*[@attr]

All elements with any attribute: //*[@*]


问:
fast way find to files in millions of files
I had a huge amount of data, about 50*50*10000 files with total file size 3TB. The file structure looks like:

/myhdd/Experiment_{id}/Run_{id}/Filename

Now given a filename, I want to locate where it is; however a straightforward find /myhdd -name "filename" is super inefficient. It need to look up the entire harddisk to find one file. Is there a better way to do this, like somehow build an index of my file structure to accelerate find?

答:
Maybe you can use locate command, it usually works faster than find:

locate -b filename


问:
R - Understanding pipes and the magrittr syntax
I am trying out pipes and the magrittr package.
Although it seems somewhat easy to understand, I have a hard time understanding how to write conditional subsetting with pipes.

For a dataset, you can use 'filter' function and others but it gets  unclear for a vector (at least to me).

For example, if I want to subset values greater than 2, how am I supposed to do that?
I know there is the aliases available but they did something funky yesterday.

I'd like to understand how to write my pipes using [and <for example but also using the aliases.
Can you provide me with some examples and compare the two syntax?
Like

1) subsetting of a vector and retrieving values greater/lower than 2

2) how to combine two logical expressions (that I would normally do with & or |...)

```<code>Num1 <-
DataSet$myvariable %>%
strsplit(split = " ") %>%
lengths() %>% is_less_than(2) %>% #subset?
</code>```

How to extract the values when I have my TRUE and FALSE?

Thanks a lot

答:
I think I found partly the answer to my questions.

First for the syntax:

```<code>%>% is_less_than(2) #would be equivalent to
%>% `<`(2) # I didn't know about the parenthesis here
</code>```

If there exists a more detailed documentation about magrittr with many examples, I would be happy to know about it.

Second, concerning the subset, it could be written as such:

```<code>AssignData <- Vector %>%
purrr::keep(., `<`(., 2))
</code>```

AND FURTHER

```<code>AssignData <- DATASET %$% SOME OPERATIONS THAT GIVES A VECTOR (split?) %>%
`<`(2) %>%
which %>%
DATASET[.,]
</code>```

To extract something from the dataset based on some criterias in the vector.

Body:
I am trying out pipes and the magrittr package.
Although it seems somewhat easy to understand, I have a hard time understanding how to write conditional subsetting with pipes.

For a dataset, you can use 'filter' function and others but it gets  unclear for a vector (at least to me).

For example, if I want to subset values greater than 2, how am I supposed to do that?
I know there is the aliases available but they did something funky yesterday.

I'd like to understand how to write my pipes using [and <for example but also using the aliases.
Can you provide me with some examples and compare the two syntax?
Like

1) subsetting of a vector and retrieving values greater/lower than 2

2) how to combine two logical expressions (that I would normally do with & or |...)

Num1 <-
DataSet$myvariable %>%
strsplit(split = " ") %>%
lengths() %>% is_less_than(2) %>% #subset?

How to extract the values when I have my TRUE and FALSE?

Thanks a lot

Body:
I think I found partly the answer to my questions.

First for the syntax:

%>% is_less_than(2) #would be equivalent to
%>% `<`(2) # I didn't know about the parenthesis here

If there exists a more detailed documentation about magrittr with many examples, I would be happy to know about it.

Second, concerning the subset, it could be written as such:

AssignData <- Vector %>%
purrr::keep(., `<`(., 2))

AND FURTHER

AssignData <- DATASET %$% SOME OPERATIONS THAT GIVES A VECTOR (split?) %>%
`<`(2) %>%
which %>%
DATASET[.,]

To extract something from the dataset based on some criterias in the vector.


问:
Google text-to-speech nodejs
I am trying to code a nodejs application that uses google tts api what my problem is, it returns an url to an audio. I need to be able to hear the text automatically without going to link and playing the audio. </p>

答:
first, install mpv player then try this ==> </p>

```<code>const googleTTS = require("google-tts-api");
let mpv = require('node-mpv');
let mpvPlayer = new mpv();
googleTTS("Hello world", "en",1).then(url => mpvPlayer.load(url));
</code>```

Title: Google text-to-speech nodejs

Body:
first, install mpv player then try this ==>

const googleTTS = require("google-tts-api");
let mpv = require('node-mpv');
let mpvPlayer = new mpv();
googleTTS("Hello world", "en",1).then(url => mpvPlayer.load(url));


问:
How do I sort a list of words by their letter endings?
How do I sort a list of strings by the last two characters

Input:

```<code> ['abby', 'acts', 'aden', 'afro', 'agni', 'agra', 'aida', 'ainu', 'alba', 'aldo', 'alec', 'alex', 'alma', 'alpo', 'alps', 'alta', 'alva', 'amie', 'amos']
</code>```

Output:

```<code>**aa
**ab
**ac
**ad
**ae
**af
**ag
**ah
**ai
**aj
**ak
**al
**am
**an
**ao
**ap
**aq
**ar
**as
**at
**au
**av
**aw
**ax
**ay
**az
etc...
**ba
**ca
**da
**ea
**fa
**ga
etc...
</code>```

答:
In one line you can try:

Take the advantage of tuple sorting trick :

```<code>list_1=['abby', 'acts', 'aden', 'afro', 'agni', 'agra', 'aida', 'ainu', 'alba', 'aldo', 'alec', 'alex', 'alma', 'alpo', 'alps',
 'alta', 'alva', 'amie', 'amos']

print([sub_item[1] for sub_item in sorted([(item[-2:],item) for item in list_1])])
</code>```

output:

```<code>['alba', 'abby', 'aida', 'aldo', 'alec', 'aden', 'alex', 'amie', 'alma', 'agni', 'ainu', 'amos', 'alpo', 'alps', 'agra', 'afro', 'alta', 'acts', 'alva']
</code>```

Detailed solution:

above list comprehension is same as:

```<code>sub_list=[]
for item in list_1:
    sub_list.append((item[-2:],item))

final_list=[]
for sub_item in sorted(sub_list):

    final_list.append(sub_item[1])
print(final_list)
</code>```

Body:
How do I sort a list of strings by the last two characters

Input:

 ['abby', 'acts', 'aden', 'afro', 'agni', 'agra', 'aida', 'ainu', 'alba', 'aldo', 'alec', 'alex', 'alma', 'alpo', 'alps', 'alta', 'alva', 'amie', 'amos']

Output:

**aa
**ab
**ac
**ad
**ae
**af
**ag
**ah
**ai
**aj
**ak
**al
**am
**an
**ao
**ap
**aq
**ar
**as
**at
**au
**av
**aw
**ax
**ay
**az
etc...
**ba
**ca
**da
**ea
**fa
**ga
etc...

Body:
In one line you can try:

Take the advantage of tuple sorting trick :

list_1=['abby', 'acts', 'aden', 'afro', 'agni', 'agra', 'aida', 'ainu', 'alba', 'aldo', 'alec', 'alex', 'alma', 'alpo', 'alps',
 'alta', 'alva', 'amie', 'amos']

print([sub_item[1] for sub_item in sorted([(item[-2:],item) for item in list_1])])

output:

['alba', 'abby', 'aida', 'aldo', 'alec', 'aden', 'alex', 'amie', 'alma', 'agni', 'ainu', 'amos', 'alpo', 'alps', 'agra', 'afro', 'alta', 'acts', 'alva']

Detailed solution:

above list comprehension is same as:

sub_list=[]
for item in list_1:
    sub_list.append((item[-2:],item))

final_list=[]
for sub_item in sorted(sub_list):

    final_list.append(sub_item[1])
print(final_list)


问:
External Translations in .NET
Good morning,

I am interested in developing an application which supports external GUI translation files to be added as desired by the users. I thought about using the localization methods built into .NET, but I think this way I cannot distribute isolated files with translations (can I?) after the application is built.

What is the better way to achieve localization using external files in C#?

Thank you very much.

答:
You can use .NET localizations without any issues.

After you sucessfully localized yopur appliation files, in your application folder will contain subfolders for you localized versions of assembly resources. So after adding new language into localizations, you can distrubute these new DLLs to your castomers from folder for your newly added localizations.

Cheers ;)

ContentLicense: CC BY-SA 2.5

Title: External Translations in .NET


问:
How to use NgReduxTestingModule
I want to use MockNgRedux mocked store. I imported it to my test suite

```<code>import { NgReduxTestingModule, MockNgRedux } from '@angular-redux/store/testing';
</code>```

Then I placed it in configureTestingModule imports.

In test case example object has been created and passed to the function I wanted to examined. As acting with the store is asynchronious action - I used fakeAsync zone, and called tick and detectChanges(). While I use subscribe() on Observable variable which should be updated by the store - application doesn't reach body of this method.

What do I wrong? Please help. It is my test:

```<code>it('should has specified version after calling changeVersion', fakeAsync(() => {

    let inputVersion: Version = new Version();
    inputVersion.id = 7;
    inputVersion.majorVersion = 1;
    inputVersion.minorVersion = 4;
    inputVersion.createdAt = new Date(2017, 6, 4);
    inputVersion.createdBy = "user1";

    component.changeVersion(inputVersion);

    console.log(MockNgRedux.mockInstance);

    fixture.detectChanges();
    tick();
    fixture.detectChanges();

    console.log(MockNgRedux.mockInstance.getState()); //it's null

    let currentVersion: Version;

    component.selectedVersion$.subscribe((ver: Version) => {
      fixture.detectChanges();
      currentVersion = ver;
    });

    expect(currentVersion.id).toBe(7);
 }));
</code>```

答:
I'm assuming that your component property selectedVersion$ is decorated with a @select decorator.

In your test, you need to tell the MockNgRedux instance what values you want to stub out in your test, e.g.

```<code>const selectedVersionStub = MockNgRedux.GetSelectedStub<IState, Version>(["path", "to", "version"]);
selectedVersionStub.next(new Version());
selectedVersionStub.complete();

component.selectedVersion$.toArray().subscribe(versions => {
    expect(versions.length).toBe(1);
});
</code>```

Where IState is your state's root type, and the path to your version is the object traversal path to the item of your interest. In addition, I would recommend using async over fakeAsync... it will wait until all the async tasks have completed before evaluating your expectations. Note: selectedVersionStub is an rxjs/Subject<Version> type in this case, so you can pump values through with next, and close the observable with complete so that toArray() works.

Edit: you can use the getInstance() to spy on the getState method, but that will only work in the case where you are actually injecting NgRedux into your component and actually calling the getState method. Decorating with @select doesn't work in the same way.

Title: How to use NgReduxTestingModule

Body:
I want to use MockNgRedux mocked store. I imported it to my test suite

import { NgReduxTestingModule, MockNgRedux } from '@angular-redux/store/testing';

Then I placed it in configureTestingModule imports.

In test case example object has been created and passed to the function I wanted to examined. As acting with the store is asynchronious action - I used fakeAsync zone, and called tick and detectChanges(). While I use subscribe() on Observable variable which should be updated by the store - application doesn't reach body of this method.

What do I wrong? Please help. It is my test:

it('should has specified version after calling changeVersion', fakeAsync(() => {

    let inputVersion: Version = new Version();
    inputVersion.id = 7;
    inputVersion.majorVersion = 1;
    inputVersion.minorVersion = 4;
    inputVersion.createdAt = new Date(2017, 6, 4);
    inputVersion.createdBy = "user1";

    component.changeVersion(inputVersion);

    console.log(MockNgRedux.mockInstance);

    fixture.detectChanges();
    tick();
    fixture.detectChanges();

    console.log(MockNgRedux.mockInstance.getState()); //it's null

    let currentVersion: Version;

    component.selectedVersion$.subscribe((ver: Version) => {
      fixture.detectChanges();
      currentVersion = ver;
    });

    expect(currentVersion.id).toBe(7);
 }));

Body:
I'm assuming that your component property selectedVersion$ is decorated with a @select decorator.

In your test, you need to tell the MockNgRedux instance what values you want to stub out in your test, e.g.

const selectedVersionStub = MockNgRedux.GetSelectedStub<IState, Version>(["path", "to", "version"]);
selectedVersionStub.next(new Version());
selectedVersionStub.complete();

component.selectedVersion$.toArray().subscribe(versions => {
    expect(versions.length).toBe(1);
});

Where IState is your state's root type, and the path to your version is the object traversal path to the item of your interest. In addition, I would recommend using async over fakeAsync... it will wait until all the async tasks have completed before evaluating your expectations. Note: selectedVersionStub is an rxjs/Subject<Version> type in this case, so you can pump values through with next, and close the observable with complete so that toArray() works.

Edit: you can use the getInstance() to spy on the getState method, but that will only work in the case where you are actually injecting NgRedux into your component and actually calling the getState method. Decorating with @select doesn't work in the same way.


问:
Proper way to use iloc in Pandas
I have the following dataframe df:

```<code>print(df)

    Food         Taste
0   Apple        NaN
1   Banana       NaN
2   Candy        NaN
3   Milk         NaN
4   Bread        NaN
5   Strawberry   NaN
</code>```

I am trying to replace values in a range of rows using iloc:

```<code>df.Taste.iloc[0:2] = 'good'
df.Taste.iloc[2:6] = 'bad'
</code>```

But it returned the following SettingWithCopyWarning message:

```<code>SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
</code>```

So, I found this Stackoverflow page and tried this:

```<code>df.iloc[0:2, 'Taste'] = 'good'
df.iloc[2:6, 'Taste'] = 'bad'
</code>```

Unfortunately, it returned the following error:

```<code>ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]
</code>```

What would be the proper way to use iloc in this situation? Also, is there a way to combine these two lines above?

答:
Purely integer-location based indexing for selection by position.. eg :-</p>

```<code>lang_sets = {}
lang_sets['en'] = train[train.lang == 'en'].iloc[:,:-1]
lang_sets['ja'] = train[train.lang == 'ja'].iloc[:,:-1]
lang_sets['de'] = train[train.lang == 'de'].iloc[:,:-1]
</code>```

Title: Proper way to use iloc in Pandas

Body:
I have the following dataframe df:

print(df)

    Food         Taste
0   Apple        NaN
1   Banana       NaN
2   Candy        NaN
3   Milk         NaN
4   Bread        NaN
5   Strawberry   NaN

I am trying to replace values in a range of rows using iloc:

df.Taste.iloc[0:2] = 'good'
df.Taste.iloc[2:6] = 'bad'

But it returned the following SettingWithCopyWarning message:

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

So, I found this Stackoverflow page and tried this:

df.iloc[0:2, 'Taste'] = 'good'
df.iloc[2:6, 'Taste'] = 'bad'

Unfortunately, it returned the following error:

ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]

What would be the proper way to use iloc in this situation? Also, is there a way to combine these two lines above?

Body:
Purely integer-location based indexing for selection by position.. eg :-

lang_sets = {}
lang_sets['en'] = train[train.lang == 'en'].iloc[:,:-1]
lang_sets['ja'] = train[train.lang == 'ja'].iloc[:,:-1]
lang_sets['de'] = train[train.lang == 'de'].iloc[:,:-1]


问:
Add a "#" to an Url.Action
The thing is that I have a card div in a View that when being clicked redirects you to another View; it is working fine and Im getting and URL like : localhost:34195/Home/Details/1 , but I need to add a # symbol on the Id parameter for me to get an URL like localhost:34195/Home/Details/#1 .

This is the div that calls the other View:

```<code><div class="card z-depth-5" onclick="location.href='@Url.Action("Details", "Home",new { id = item.Id })'">
</code>```

答:
After some help provided by an user that deleted his answer, I´ve accomplished what I needed by changing the onclick like this:</p>

```<code><div class="card z-depth-5" onclick="location.href='@Url.Action("Details", "Home")/#@item.Id'">
</code>```

Title: Add a "#" to an Url.Action

Body:
After some help provided by an user that deleted his answer, I´ve accomplished what I needed by changing the onclick like this:

<div class="card z-depth-5" onclick="location.href='@Url.Action("Details", "Home")/#@item.Id'">


问:
Patterned gradients in modern browsers
I get more and more complaints regarding badly rendered gradients (CSS, Canvas, and SVG).

As it highly depends on the browser and OS. I can't propose a global MCVE. So I'll focus on this simple CSS gradient which is badly rendered on Chrome/Ubuntu (vertical stripes):

body {
    background: linear-gradient(90deg, #111, #444);
}```

Of course I'd be interested in a solution for this specific case. But I'd value more a general solution to get smooth monotonous gradients. Canvas or image based solutions are not acceptable as my gradients are in great number, dynamic, and usually partially transparent.

答:
In many cases it is not neccessarily the fault of the OS or Browser, it is more the problem, that a lot of people don't know, how gradients work, and why they are patterned.

This is highly a problem of the luminosity of each color. In your example it is easy to find the luminosity of the gradient, since its a grayscaled gradient. So take a look at the picture below, where I put the darkest and lightest color of the gradiend side by side. You will notice, that they have a slightly different luminosity. If you make the black a bit lighter (or the gray a bit darker) the pattern will start to disappear.

Now to make it clearer, lets start with this simple gradient. (Don't worry, I will get to the pattern problem) Looks pretty dirty, doesn't it? Especially that grey in the middle of the gradient.

If we take a look at the RGB Color wheel, we see the problem. The gradient goes right through the middle of the wheel, which is a really washed out spot. We can avoid this, if we just start to add another stop in our gradient, such as green. If you compare it with the wheel on the right side, you cann see, that this avoids the part in the middle. The gradient below is much more colorful and does not look washed out.

But, now we have a pretty hard pattern in our gradient. This is, as already mentioned above, because we have a lot of different luminosities. So we don't actually want to go through the RGB spectrum with our gradients, we would more like to go through a color space, which is based on luminosity. And that is the HSL color space. Below you have a comparison of our initla red-to-cyan gradient between RGB and HSL, and you will notice, that there is much less of the banding in the HSL gradient. There is acutally a tool in the web, which I like to use for gradients. You can give a start and an end point (and steps between) and it generates a gradient in all the different color spaces, and mostly I pick the HSL one, because its the most natural one.

tl;dr
The problem with these patterns is often a problem of the gradients luminosity, and if you try to change the color space, it will work out much better. Now I don't say, that ifferent Monitors, Browsers or Operating Systems don't have any influence on this, but the problem can be reduced with this trick pretty easily.

Title: Patterned gradients in modern browsers

Body:
I get more and more complaints regarding badly rendered gradients (CSS, Canvas, and SVG).

As it highly depends on the browser and OS. I can't propose a global MCVE. So I'll focus on this simple CSS gradient which is badly rendered on Chrome/Ubuntu (vertical stripes):

body {
    background: linear-gradient(90deg, #111, #444);
}

Of course I'd be interested in a solution for this specific case. But I'd value more a general solution to get smooth monotonous gradients. Canvas or image based solutions are not acceptable as my gradients are in great number, dynamic, and usually partially transparent.


问:
Best Way to migrate code from magento 1 to magento 2?
I am trying to migrate magento 1 website to magento 2 i am able to migrate data but i want to know is it possible to migrate code also?</p>

答:
The we have a migration tool kit in git hub

The toolkit covers migration of the following aspects of the Magento code:

```<code>**Module directory structure
Layout XML files
Config XML files
PHP files**
</code>```

This will help you to get a over all skeleton of m1 module.
For Tool Go To

ContentLicense: CC BY-SA 4.0

Body:
The we have a migration tool kit in git hub

The toolkit covers migration of the following aspects of the Magento code:

**Module directory structure
Layout XML files
Config XML files
PHP files**

This will help you to get a over all skeleton of m1 module.
For Tool Go To


问:
How to determine the correct end of a range function in Python?
I noticed that I get the exact same results when I am trying to do this, for example:

```<code>   range(1,13,2)
=> [1, 3, 5, 7, 9, 11]
</code>```

And

```<code>   range(1,12,2)
=> [1, 3, 5, 7, 9, 11]
</code>```

The result is the exact same, but which one would be correct in this case and why?

Does the end of a range have to do something with the steps you take?

Like, the idea that a list should give me 11 as the last number, so I
  should take 13 because we have a step of 2, or is this a bad thought?

答:
```<code>range(start,end,step)
</code>```

The range function will give you numbers starting at "start" until it reaches "end-1", but each number will have a distance to the next with length "step".

for your first case your end is 13-1 = 12, so the final value you can get is 12. But since your step is 2 it gets to 11 (1,3,5,7,9), adds 2 and gets 13, which it can't go to.

For you second case your end is 12-1=11. It adds 2 until it reaches 11 (1,3,5,7,9) and stops there.

There isn't really a right answers to which one you are supposed to use as it will depend on what you are using range for. I guess there will be slightly less calculation going on for your case two as it doesn't have to add the final step, but that is minor.

Body:
I noticed that I get the exact same results when I am trying to do this, for example:

   range(1,13,2)
=> [1, 3, 5, 7, 9, 11]

And

   range(1,12,2)
=> [1, 3, 5, 7, 9, 11]

The result is the exact same, but which one would be correct in this case and why?

Does the end of a range have to do something with the steps you take?

Like, the idea that a list should give me 11 as the last number, so I
  should take 13 because we have a step of 2, or is this a bad thought?

Body:
range(start,end,step)

The range function will give you numbers starting at "start" until it reaches "end-1", but each number will have a distance to the next with length "step".

for your first case your end is 13-1 = 12, so the final value you can get is 12. But since your step is 2 it gets to 11 (1,3,5,7,9), adds 2 and gets 13, which it can't go to.

For you second case your end is 12-1=11. It adds 2 until it reaches 11 (1,3,5,7,9) and stops there.

There isn't really a right answers to which one you are supposed to use as it will depend on what you are using range for. I guess there will be slightly less calculation going on for your case two as it doesn't have to add the final step, but that is minor.


问:
Is there a way to generate a Google Doc from HTML via Javascript?
Title pretty much says it all. ATM I've managed to $.post to a pre-defined Spreadsheet and have that replace some values in an existing Docs template, but unfortunately this doesn't fully meet my needs - generating a Google Doc from HTML via Javascript

Any help would be greatly appreciated.

答:
Google services you will need (Api already exist there's no shortcuts) :

Sheets

Drive

and this is first step :

https://console.developers.google.com/apis/dashboard?

Heres you will create new project and enable what you want.
 This is embedded viewer schema .

Just follow instructions and online demos and examples.


问:
Help with a SQL query
I have been trying different sql queries that do the following:

For all the table entries which have a field that has a field_value in clumn_a of table_1 which equals any field value in column_b of table_2 insert the id of the field in table_2 in id_of_the_other_entry_column of table_1.

However I can only use SQL and not use anything else than a SQL command for that. Is this even possible without the help of another programming language? If so.. any tips?

EDIT:
An example:

```<code>TableOwner
id  name
1   SomeCompany
2   SomeOtherCompany

TableContracts
Name               ownerid
NewCompany       Null --> Should remain null after the query
SomeCompany     Null -->Should change to 1 after the query
SomeCompany        Null -->Should change to 1 after the query
SomeOtherCompany   Null -->Should change to 2 after the query
</code>```

thanks

答:
```<code>update tableContracts t2 set t2.ownerid=t1.id where exists( select t1.id from tableowner t1 where t1.name=t2.Name)
</code>```

Title: Help with a SQL query

Body:
I have been trying different sql queries that do the following:

For all the table entries which have a field that has a field_value in clumn_a of table_1 which equals any field value in column_b of table_2 insert the id of the field in table_2 in id_of_the_other_entry_column of table_1.

However I can only use SQL and not use anything else than a SQL command for that. Is this even possible without the help of another programming language? If so.. any tips?

EDIT:
An example:

TableOwner
id  name
1   SomeCompany
2   SomeOtherCompany

TableContracts
Name               ownerid
NewCompany       Null --> Should remain null after the query
SomeCompany     Null -->Should change to 1 after the query
SomeCompany        Null -->Should change to 1 after the query
SomeOtherCompany   Null -->Should change to 2 after the query

thanks


问:
SQL Statement to Query Expression
I want to convert SQL statement to Query Expression.

```<code>   SELECT q.EMailAddress, fe.torecipients, fe.subject, fe.createdon, fe.actualend ,fe.ActivityId
    FROM QueueItem qi WITH (NOLOCK)
    inner join Email fe WITH (NOLOCK) ON fe.ActivityId = qi.ObjectId and fe.RegardingObjectId is null
    inner join Queue q WITH (NOLOCK) ON q.QueueId= qi.QueueId and q.EMailAddress is not null
    WHERE PATINDEX(CONCAT('%', q.emailaddress, '%'), fe.torecipients ) >= 1
    ORDER BY fe.createdon DESC
</code>```

I could do this. How can I convert 'PATINDEX(CONCAT('%', q.emailaddress, '%'), fe.torecipients ) >= 1'. Can you help me?

```<code>QueryExpression queueQuery = new QueryExpression(Constants.QueryQueueItem);
queueQuery.ColumnSet.AddColumns(Constants.QueryIncidentId);

LinkEntity emailLink = new LinkEntity();
emailLink.LinkFromEntityName = Constants.QueryQueueItem;
emailLink.LinkToAttributeName = Constants.QueryEmail;
emailLink.LinkFromAttributeName = "ObjectId";
emailLink.LinkToAttributeName = "ActivityId";
emailLink.JoinOperator = JoinOperator.Inner;
emailLink.LinkCriteria.AddCondition(new ConditionExpression("RegardingObjectId", ConditionOperator.Null, true))

LinkEntity queueLink = new LinkEntity();
queueLink.LinkFromEntityName = "QueueItem";
queueLink.LinkToAttributeName = "Queue";
queueLink.LinkFromAttributeName = "QueueId";
queueLink.LinkToAttributeName = "QueueId";
queueLink.JoinOperator = JoinOperator.Inner;
queueLink.LinkCriteria.AddCondition(new ConditionExpression("EMailAddress", ConditionOperator.NotNull, true));

queueQuery.LinkEntities.Add(emailLink);
queueQuery.LinkEntities.Add(queueLink);

ConditionExpression emailCondition = new ConditionExpression();
emailCondition.AttributeName = Constants.QueryIncidentId;
emailCondition.Operator = ConditionOperator.NotNull;

FilterExpression emailFilter = new FilterExpression();
emailFilter.Conditions.Add(emailCondition);
queueQuery.Criteria = emailFilter;
</code>```

答:
FetchXML does not support the PATINDEX function, so quick option would be to use the Like operator instead:

new ConditionExpression(“torecipients”, ConditionOperator.Like, "%"+q.emailaddress+"%");

A more complex option that would allow to you match the email address would be to join to the email's Activity Parties and filter based on matching the activity party type and AddressUsed.

Title: SQL Statement to Query Expression

Body:
I want to convert SQL statement to Query Expression.

   SELECT q.EMailAddress, fe.torecipients, fe.subject, fe.createdon, fe.actualend ,fe.ActivityId
    FROM QueueItem qi WITH (NOLOCK)
    inner join Email fe WITH (NOLOCK) ON fe.ActivityId = qi.ObjectId and fe.RegardingObjectId is null
    inner join Queue q WITH (NOLOCK) ON q.QueueId= qi.QueueId and q.EMailAddress is not null
    WHERE PATINDEX(CONCAT('%', q.emailaddress, '%'), fe.torecipients ) >= 1
    ORDER BY fe.createdon DESC

I could do this. How can I convert 'PATINDEX(CONCAT('%', q.emailaddress, '%'), fe.torecipients ) >= 1'. Can you help me?

QueryExpression queueQuery = new QueryExpression(Constants.QueryQueueItem);
queueQuery.ColumnSet.AddColumns(Constants.QueryIncidentId);

LinkEntity emailLink = new LinkEntity();
emailLink.LinkFromEntityName = Constants.QueryQueueItem;
emailLink.LinkToAttributeName = Constants.QueryEmail;
emailLink.LinkFromAttributeName = "ObjectId";
emailLink.LinkToAttributeName = "ActivityId";
emailLink.JoinOperator = JoinOperator.Inner;
emailLink.LinkCriteria.AddCondition(new ConditionExpression("RegardingObjectId", ConditionOperator.Null, true))

LinkEntity queueLink = new LinkEntity();
queueLink.LinkFromEntityName = "QueueItem";
queueLink.LinkToAttributeName = "Queue";
queueLink.LinkFromAttributeName = "QueueId";
queueLink.LinkToAttributeName = "QueueId";
queueLink.JoinOperator = JoinOperator.Inner;
queueLink.LinkCriteria.AddCondition(new ConditionExpression("EMailAddress", ConditionOperator.NotNull, true));

queueQuery.LinkEntities.Add(emailLink);
queueQuery.LinkEntities.Add(queueLink);

ConditionExpression emailCondition = new ConditionExpression();
emailCondition.AttributeName = Constants.QueryIncidentId;
emailCondition.Operator = ConditionOperator.NotNull;

FilterExpression emailFilter = new FilterExpression();
emailFilter.Conditions.Add(emailCondition);
queueQuery.Criteria = emailFilter;


问:
How to get the height and width of a tooltip dynamically in c++?
MSDN link for TTM_GETBUBBLESIZE doesn't have an example, how the lower word and higher word get returned. Didn't get much from Google. Please care to provide an example of it.

Thanks!

答:
From MSDN:

Returns the width of the tooltip in the low word and the height in the
  high word if successful.

A "word" in the context of the Win API usually has a size of 16-bit.

You have to use some bitwise arithmetic to extract width and height from the result of the message:

```<code>width  = result & 0xFFFF;   // extract the low word
height = result >> 16;      // extract the high word
</code>```

Alternatively these macros declared in "windows.h" do the same:

```<code>width  = LOWORD(result);
height = HIWORD(result);
</code>```

Body:
From MSDN:

Returns the width of the tooltip in the low word and the height in the
  high word if successful.

A "word" in the context of the Win API usually has a size of 16-bit.

You have to use some bitwise arithmetic to extract width and height from the result of the message:

width  = result & 0xFFFF;   // extract the low word
height = result >> 16;      // extract the high word

Alternatively these macros declared in "windows.h" do the same:

width  = LOWORD(result);
height = HIWORD(result);


问:
How do I run an import or export command from mysql workbench outside of mysql workbench?
I see that workbench shows the command being run for imports and exports, and I'd like to run that command on another machine in a standalone script. Unfortunately, the script appears to reference a "defaults file" that is temporary and not accessible after the command runs... it seems that workbench is dynamically creating this extraparams.cnf file each time the command is run.. therefore it makes it difficult for me to reproduce this command elsewhere

```<code>13:45:52 Restoring /Users/wes/dumps/Dump20170907.sql
Running: /Applications/MySQLWorkbench.app/Contents/MacOS/mysql --defaults-file="/var/folders/x1/8vgyglcd0hv44_5fdlqj1zssm53dzs/T/tmpsmXKI3/extraparams.cnf" --protocol=tcp --host=server.edu --user=riuser --port=3306 --default-character-set=utf8 --comments --database=prd2 < "/Users/wes/dumps/Dump20170907.sql"
13:46:02 Import of /Users/wes/dumps/Dump20170907.sql has finished
</code>```

Any suggestions?

Thank you.

BTW: I posted this a month ago on the mysql forums with no response:
https://forums.mysql.com/read.php?152,660219

答:
Although I agree with the accepted answer given by Kevin Bott here is what I did on my Mac as a brutal hack to spy the contents of the defaults file extraparams.cnf.

create a folder writable by any user

```<code>cd /tmp
mkdir hack
chmod a+xw hack
</code>```

execute the MySQL Workbench export once and leave the Export Progress tab open

replace the mysqldump binary used by the export with a fake that dumps the contents of the defaults file (see Export Progress log for the correct paths to use in your case)

```<code>cd /private/var/folders/ks/vmng3tc51nb43xkklk7jjxxh0000gn/T/
mv AppTranslocation AppTranslocation.orig
mkdir -p AppTranslocation/10D5E741-FD2F-4247-9CEE-E8A82D8EE23F/d/MySQLWorkbench.app/Contents/MacOS
cd AppTranslocation/10D5E741-FD2F-4247-9CEE-E8A82D8EE23F/d/MySQLWorkbench.app/Contents/MacOS

vim mysqldump

  1 #!/bin/bash
  2 if [ $1 = '--version' ]
  3 then
  4     echo 'mysqldump  Ver 10.13 Distrib 5.6.23, for osx10.8 (x86_64)'
  5     exit 0
  6 fi
  7
  8 VALUE=`echo $1 | sed 's/^[^=]*=//g'`
  9 cat $VALUE > /tmp/hack/extraparams.cnf

chmod +x mysqldump
</code>```

click 'Export Again' in the Export Progress tab

inspect the contents of the captured .cnf file

```<code>cd /tmp/hack
cat extraparams.cnf
</code>```

Body:
I see that workbench shows the command being run for imports and exports, and I'd like to run that command on another machine in a standalone script. Unfortunately, the script appears to reference a "defaults file" that is temporary and not accessible after the command runs... it seems that workbench is dynamically creating this extraparams.cnf file each time the command is run.. therefore it makes it difficult for me to reproduce this command elsewhere

13:45:52 Restoring /Users/wes/dumps/Dump20170907.sql
Running: /Applications/MySQLWorkbench.app/Contents/MacOS/mysql --defaults-file="/var/folders/x1/8vgyglcd0hv44_5fdlqj1zssm53dzs/T/tmpsmXKI3/extraparams.cnf" --protocol=tcp --host=server.edu --user=riuser --port=3306 --default-character-set=utf8 --comments --database=prd2 < "/Users/wes/dumps/Dump20170907.sql"
13:46:02 Import of /Users/wes/dumps/Dump20170907.sql has finished

Any suggestions?

Thank you.

BTW: I posted this a month ago on the mysql forums with no response:
https://forums.mysql.com/read.php?152,660219

Body:
Although I agree with the accepted answer given by Kevin Bott here is what I did on my Mac as a brutal hack to spy the contents of the defaults file extraparams.cnf.

create a folder writable by any user

cd /tmp
mkdir hack
chmod a+xw hack

execute the MySQL Workbench export once and leave the Export Progress tab open

replace the mysqldump binary used by the export with a fake that dumps the contents of the defaults file (see Export Progress log for the correct paths to use in your case)

cd /private/var/folders/ks/vmng3tc51nb43xkklk7jjxxh0000gn/T/
mv AppTranslocation AppTranslocation.orig
mkdir -p AppTranslocation/10D5E741-FD2F-4247-9CEE-E8A82D8EE23F/d/MySQLWorkbench.app/Contents/MacOS
cd AppTranslocation/10D5E741-FD2F-4247-9CEE-E8A82D8EE23F/d/MySQLWorkbench.app/Contents/MacOS

vim mysqldump

  1 #!/bin/bash
  2 if [ $1 = '--version' ]
  3 then
  4     echo 'mysqldump  Ver 10.13 Distrib 5.6.23, for osx10.8 (x86_64)'
  5     exit 0
  6 fi
  7
  8 VALUE=`echo $1 | sed 's/^[^=]*=//g'`
  9 cat $VALUE > /tmp/hack/extraparams.cnf

chmod +x mysqldump

click 'Export Again' in the Export Progress tab

inspect the contents of the captured .cnf file

cd /tmp/hack
cat extraparams.cnf


问:
Read folder paths from FTP directory to IEnumerable
I'm currently working on a .NET 4.6 console application. I need to parse a couple of XML files from different directories on my FTP server. I thought the best approach would be, to read all file paths and store them into an IEnumerable, to process them further (Serialize XML Files to objects).

The root FTP path looks like this:

```<code>string urlFtpServer = @"ftp://128.0.1.70";
</code>```

File paths look like this:

```<code>string file1 = @"ftp://128.0.1.70/MyFolder1/Mainfile.xml";
string file2 = @"ftp://128.0.1.70/MyFolder1/Subfile.xml";
string file3 = @"ftp://128.0.1.70/MyFolder2/Mainfile.xml";
string file4 = @"ftp://128.0.1.70/MyFolder2/Subfile.xml";
string file5 = @"ftp://128.0.1.70/MyFolder3/Mainfile.xml";
</code>```

My question is, do you know how I can get those specific file paths?

I currently can read the folders of my FTP directory with this coding:

```<code>static void Main(string[] args)
{
    string url = @"ftp://128.0.1.70";

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

    request.Credentials = new NetworkCredential("My-User", "mypassword");

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

    Stream responseStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(responseStream);
    Console.WriteLine(reader.ReadToEnd());

    Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

    reader.Close();
    response.Close();

    Console.ReadKey();
}
</code>```

Do you know how I can read all file paths from the FTP main directory and possibly store them into a List<string>?

Thank you very much!!

答:
Using FtpWebRequest

The FtpWebRequest does not have any explicit support for recursive file operations (including listing). You have to implement the recursion yourself:

List the remote directory

Iterate the entries, recursing into subdirectories (listing them again, etc.)

Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the FtpWebRequest. The FtpWebRequest unfortunately does not support the MLSD command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.

Your options are:

Do an operation on a file name that is certain to fail for file and succeeds for directories (or vice versa). I.e. you can try to download the "name". If that succeeds, it's a file, if that fails, it's a directory.

You may be lucky and in your specific case, you can tell a file from a directory by a file name (i.e. all your files have an extension, while subdirectories do not)

You use a long directory listing (LIST command = ListDirectoryDetails method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)

```<code>void ListFtpDirectory(
    string url, string rootPath, NetworkCredential credentials, List<string> list)
{
    FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url + rootPath);
    listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    listRequest.Credentials = credentials;

    List<string> lines = new List<string>();

    using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
    using (Stream listStream = listResponse.GetResponseStream())
    using (StreamReader listReader = new StreamReader(listStream))
    {
        while (!listReader.EndOfStream)
        {
            lines.Add(listReader.ReadLine());
        }
    }

    foreach (string line in lines)
    {
        string[] tokens =
            line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
        string name = tokens[8];
        string permissions = tokens[0];

        string filePath = rootPath + name;

        if (permissions[0] == 'd')
        {
            ListFtpDirectory(url, filePath + "/", credentials, list);
        }
        else
        {
            list.Add(filePath);
        }
    }
}
</code>```

Use the function like:

```<code>List<string> list = new List<string>();
NetworkCredential credentials = new NetworkCredential("user", "mypassword");
string url = "ftp://ftp.example.com/";
ListFtpDirectory(url, "", credentials, list);
</code>```

Using 3rd party library

If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD command and/or parsing various LIST listing formats; and recursive downloads.

For example with WinSCP .NET assembly you can list whole directory with a single call to the Session.EnumerateRemoteFiles:

```<code>// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "ftp.example.com",
    UserName = "user",
    Password = "mypassword",
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // List files
    IEnumerable<string> list =
        session.EnumerateRemoteFiles("/", null, EnumerationOptions.AllDirectories).
        Select(fileInfo => fileInfo.FullName);
}
</code>```

Internally, WinSCP uses the MLSD command, if supported by the server. If not, it uses the LIST command and supports dozens of different listing formats.

(I'm the author of WinSCP)

Body:
I'm currently working on a .NET 4.6 console application. I need to parse a couple of XML files from different directories on my FTP server. I thought the best approach would be, to read all file paths and store them into an IEnumerable, to process them further (Serialize XML Files to objects).

The root FTP path looks like this:

string urlFtpServer = @"ftp://128.0.1.70";

File paths look like this:

string file1 = @"ftp://128.0.1.70/MyFolder1/Mainfile.xml";
string file2 = @"ftp://128.0.1.70/MyFolder1/Subfile.xml";
string file3 = @"ftp://128.0.1.70/MyFolder2/Mainfile.xml";
string file4 = @"ftp://128.0.1.70/MyFolder2/Subfile.xml";
string file5 = @"ftp://128.0.1.70/MyFolder3/Mainfile.xml";

My question is, do you know how I can get those specific file paths?

I currently can read the folders of my FTP directory with this coding:

static void Main(string[] args)
{
    string url = @"ftp://128.0.1.70";

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

    request.Credentials = new NetworkCredential("My-User", "mypassword");

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

    Stream responseStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(responseStream);
    Console.WriteLine(reader.ReadToEnd());

    Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

    reader.Close();
    response.Close();

    Console.ReadKey();
}

Do you know how I can read all file paths from the FTP main directory and possibly store them into a List<string>?

Thank you very much!!

Body:
Using FtpWebRequest

The FtpWebRequest does not have any explicit support for recursive file operations (including listing). You have to implement the recursion yourself:

List the remote directory

Iterate the entries, recursing into subdirectories (listing them again, etc.)

Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the FtpWebRequest. The FtpWebRequest unfortunately does not support the MLSD command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.

Your options are:

Do an operation on a file name that is certain to fail for file and succeeds for directories (or vice versa). I.e. you can try to download the "name". If that succeeds, it's a file, if that fails, it's a directory.

You may be lucky and in your specific case, you can tell a file from a directory by a file name (i.e. all your files have an extension, while subdirectories do not)

You use a long directory listing (LIST command = ListDirectoryDetails method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)

void ListFtpDirectory(
    string url, string rootPath, NetworkCredential credentials, List<string> list)
{
    FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url + rootPath);
    listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    listRequest.Credentials = credentials;

    List<string> lines = new List<string>();

    using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
    using (Stream listStream = listResponse.GetResponseStream())
    using (StreamReader listReader = new StreamReader(listStream))
    {
        while (!listReader.EndOfStream)
        {
            lines.Add(listReader.ReadLine());
        }
    }

    foreach (string line in lines)
    {
        string[] tokens =
            line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
        string name = tokens[8];
        string permissions = tokens[0];

        string filePath = rootPath + name;

        if (permissions[0] == 'd')
        {
            ListFtpDirectory(url, filePath + "/", credentials, list);
        }
        else
        {
            list.Add(filePath);
        }
    }
}

Use the function like:

List<string> list = new List<string>();
NetworkCredential credentials = new NetworkCredential("user", "mypassword");
string url = "ftp://ftp.example.com/";
ListFtpDirectory(url, "", credentials, list);

Using 3rd party library

If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD command and/or parsing various LIST listing formats; and recursive downloads.

For example with WinSCP .NET assembly you can list whole directory with a single call to the Session.EnumerateRemoteFiles:

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "ftp.example.com",
    UserName = "user",
    Password = "mypassword",
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // List files
    IEnumerable<string> list =
        session.EnumerateRemoteFiles("/", null, EnumerationOptions.AllDirectories).
        Select(fileInfo => fileInfo.FullName);
}

Internally, WinSCP uses the MLSD command, if supported by the server. If not, it uses the LIST command and supports dozens of different listing formats.

(I'm the author of WinSCP)


问:
Converting a string[] into a string then split into an array
I need help creating a loop which splits strings. So far I have the code below.

```<code>    System.out.println("*FILE HAS BEEN LOCATED*");
    System.out.println("*File contains: \n");
    List<String> lines = new ArrayList<String>();
    while (scan.hasNextLine())
    {
      lines.add(scan.nextLine());
    }

    String[] arr = lines.toArray(new String[0]);

    String str_array = Arrays.toString(arr);

    String[] arraysplit;
    arraysplit = str_array.split(":");

    for (int i=0; i<arraysplit.length; i++)
    {
        arraysplit[i] = arr[i].trim();
        System.out.println(arr[i]);
    }
</code>```

an example of one of the strings would be

```<code>        Firstname : Lastname : age
</code>```

I want it to split the string into another array that looks like:

```<code>        Firstname
        Lastname
        age
</code>```

I still encounter an error when running the code, it seems as though when I convert the array to a string, it puts commas in the string and therefore it causes problems  as I'm trying to split the string on : not ,

image:

答:
Issue : you are using the old array arr to display values and arraysplit will have resultant values of split method so you need to apply trim() on arraysplit's elements and assign back the elements to same indexes

```<code>String[] arraysplit;
arraysplit = str_array.split(":");

for (int i=0; i<arraysplit.length; i++)
{
    arraysplit[i] = arraysplit[i].trim();
    //              ^^^^^^^^^^^^ has values with spaces
    System.out.println(arr[i]);
}

System.out.println(arraysplit[i]);
</code>```

To simplify solution without (list to array and array to string complication)

1.) Create array of length as sizeOfList * 3

2.) split the list element using \\s*:\\s*

3.) Use array copy with jas index of resultant array to keep the track of the array index

```<code>    String result[] = new String [lines.size()*3];
    int j=0;
    for (int i=0; i<lines.size(); i++)
    {
        System.arraycopy(lines.get(0).split("\\s*:\\s*"), 0, result, j, 3);
        j+=3;
    }
    System.out.println(Arrays.toString(result));
</code>```

You can use regex str_array.split("\\s*:\\s*"); where

\\s*:\\s* : \\s* mean zero or more spaces then : character then zero or more spaces

```<code>arraysplit = str_array.split("\\s*:\\s*");
// just use values of arraysplit
</code>```

Body:
I need help creating a loop which splits strings. So far I have the code below.

    System.out.println("*FILE HAS BEEN LOCATED*");
    System.out.println("*File contains: \n");
    List<String> lines = new ArrayList<String>();
    while (scan.hasNextLine())
    {
      lines.add(scan.nextLine());
    }

    String[] arr = lines.toArray(new String[0]);

    String str_array = Arrays.toString(arr);

    String[] arraysplit;
    arraysplit = str_array.split(":");

    for (int i=0; i<arraysplit.length; i++)
    {
        arraysplit[i] = arr[i].trim();
        System.out.println(arr[i]);
    }

an example of one of the strings would be

        Firstname : Lastname : age

I want it to split the string into another array that looks like:

        Firstname
        Lastname
        age

I still encounter an error when running the code, it seems as though when I convert the array to a string, it puts commas in the string and therefore it causes problems  as I'm trying to split the string on : not ,

image:

Body:
Issue : you are using the old array arr to display values and arraysplit will have resultant values of split method so you need to apply trim() on arraysplit's elements and assign back the elements to same indexes

String[] arraysplit;
arraysplit = str_array.split(":");

for (int i=0; i<arraysplit.length; i++)
{
    arraysplit[i] = arraysplit[i].trim();
    //              ^^^^^^^^^^^^ has values with spaces
    System.out.println(arr[i]);
}

System.out.println(arraysplit[i]);

To simplify solution without (list to array and array to string complication)

1.) Create array of length as sizeOfList * 3

2.) split the list element using \\s*:\\s*

3.) Use array copy with jas index of resultant array to keep the track of the array index

    String result[] = new String [lines.size()*3];
    int j=0;
    for (int i=0; i<lines.size(); i++)
    {
        System.arraycopy(lines.get(0).split("\\s*:\\s*"), 0, result, j, 3);
        j+=3;
    }
    System.out.println(Arrays.toString(result));

You can use regex str_array.split("\\s*:\\s*"); where

\\s*:\\s* : \\s* mean zero or more spaces then : character then zero or more spaces

arraysplit = str_array.split("\\s*:\\s*");
// just use values of arraysplit


问:
CSS - Apply conditional style to table row
I have a requirement where i have to apply conditional style for my table rows but the style never gets applied.

.test1 {
  background-color: '#ffbf00';
}
.test2 {
  background-color: '#92D050';
}
.test3 {
  background-color: ' ';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="testTable">
  <tr styleClass="test1">
    <td></td>
    <td></td>
  </tr>
</table></code>```

But the styling will never be applied. something i am missing?

答:
You have like 10 mistakes in this HTML code. Please learn HTML and CSS. Here is what you might want to achieve in a correct manner.

.test1 {
  background-color: #ffbf00;
}
.test2 {
  background-color: #92D050;
}
.test3 {
  background-color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="testTable">
  <tr class="test1">
    <td>a</td>
    <td>b</td>
  </tr>
</table></code>```

Do not put quotes on colors. It means class, not styleClass. ' ' is not a valid color value.

Body:
I have a requirement where i have to apply conditional style for my table rows but the style never gets applied.

.test1 {
  background-color: '#ffbf00';
}
.test2 {
  background-color: '#92D050';
}
.test3 {
  background-color: ' ';
}

But the styling will never be applied. something i am missing?

Body:
You have like 10 mistakes in this HTML code. Please learn HTML and CSS. Here is what you might want to achieve in a correct manner.

.test1 {
  background-color: #ffbf00;
}
.test2 {
  background-color: #92D050;
}
.test3 {
  background-color: transparent;
}

<table id="testTable">
  <tr class="test1">
    <td>a</td>
    <td>b</td>
  </tr>
</table>

Do not put quotes on colors. It means class, not styleClass. ' ' is not a valid color value.


问:
FileSystemWatcher cannot access files because used in other process
I'm writing a FileSystemWatcher which is to copy images from folder A to folder B, whenever an image is uploaded to folder A. I'm trying to use this as a windows service on the server PC but I'm having some issues where my files are locked when they are to be copied. I think I've found the root to my issue, but I'm not having any luck solving it. So, when I run my windows service it always ends unexpectedly at either the first or the second picture upload. The error message I'm getting says this: The process cannot access the file 'filepath' because it is being used by another process.

Relevant parts of my code:

```<code>public void WatchForChanges()
{
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = Program.SourceFolder;
    watcher.Created += new FileSystemEventHandler(OnImageAdded);
    watcher.EnableRaisingEvents = true;
    watcher.IncludeSubdirectories = true;
}

public void OnImageAdded(object source, FileSystemEventArgs e)
{
    FileInfo file = new FileInfo(e.FullPath);
    ImageHandler handler = new ImageHandler();
    if (handler.IsImage(file))
    {
        handler.CopyImage(file);
    }
}
</code>```

and, my CopyImage method, which includes one of my proposed solutions to this problem, utilizing a while loop that catches the error and retries the copying of the image:

```<code>public void CopyImage(FileSystemInfo file)
{
    // code that sets folder paths
    // code that sets folder paths

    bool retry = true;
    if (!Directory.Exists(targetFolderPath))
    {
        Directory.CreateDirectory(targetFolderPath);
    }
    while (retry)
    {
        try
        {
            File.Copy(file.FullName, targetPath, true);
            retry = false;
        }
        catch (Exception e)
        {
            Thread.Sleep(2000);
        }
    }
}
</code>```

but this CopyImage solution just keeps on copying the same file, which is not very ideal in my case. I wish it was enough but sadly I've got a queue of images waiting.

答:
The image file is probably being created by another application that uses an exclusive access lock on both reading and writing external processes (for more informations, read this, especially the paragraph related to Microsoft Windows). You have to either:

stop/kill the process which is using the file;

wait until the file isn't being used anymore.

Since the other process is probably writing the file in the moment you try to copy it with your application, the first option is by no means recommendable. It could also be an anti-virus checking the new file, and even in this case the first option would not be recommendable.

You could try to integrate the following code into your CopyImage method so that your application will wait until the file will be no longer in use before proceeding:

```<code>private Boolean WaitForFile(String filePath)
{
    Int32 tries = 0;

    while (true)
    {
        ++tries;

        Boolean wait = false;
        FileStream stream = null;

        try
        {
            stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
            break;
        }
        catch (Exception ex)
        {
            Logger.LogWarning("CopyImage({0}) failed to get an exclusive lock: {1}", filePath, ex.ToString());

            if (tries > 10)
            {
                Logger.LogWarning("CopyImage({0}) skipped the file after 10 tries.", filePath);
                return false;
            }

            wait = true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        if (wait)
            Thread.Sleep(250);
    }

    Logger.LogWarning("CopyImage({0}) got an exclusive lock after {1} tries.", filePath, tries);

    return true;
}
</code>```

Body:
I'm writing a FileSystemWatcher which is to copy images from folder A to folder B, whenever an image is uploaded to folder A. I'm trying to use this as a windows service on the server PC but I'm having some issues where my files are locked when they are to be copied. I think I've found the root to my issue, but I'm not having any luck solving it. So, when I run my windows service it always ends unexpectedly at either the first or the second picture upload. The error message I'm getting says this: The process cannot access the file 'filepath' because it is being used by another process.

Relevant parts of my code:

public void WatchForChanges()
{
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = Program.SourceFolder;
    watcher.Created += new FileSystemEventHandler(OnImageAdded);
    watcher.EnableRaisingEvents = true;
    watcher.IncludeSubdirectories = true;
}

public void OnImageAdded(object source, FileSystemEventArgs e)
{
    FileInfo file = new FileInfo(e.FullPath);
    ImageHandler handler = new ImageHandler();
    if (handler.IsImage(file))
    {
        handler.CopyImage(file);
    }
}

and, my CopyImage method, which includes one of my proposed solutions to this problem, utilizing a while loop that catches the error and retries the copying of the image:

public void CopyImage(FileSystemInfo file)
{
    // code that sets folder paths
    // code that sets folder paths

    bool retry = true;
    if (!Directory.Exists(targetFolderPath))
    {
        Directory.CreateDirectory(targetFolderPath);
    }
    while (retry)
    {
        try
        {
            File.Copy(file.FullName, targetPath, true);
            retry = false;
        }
        catch (Exception e)
        {
            Thread.Sleep(2000);
        }
    }
}

but this CopyImage solution just keeps on copying the same file, which is not very ideal in my case. I wish it was enough but sadly I've got a queue of images waiting.

Body:
The image file is probably being created by another application that uses an exclusive access lock on both reading and writing external processes (for more informations, read this, especially the paragraph related to Microsoft Windows). You have to either:

stop/kill the process which is using the file;

wait until the file isn't being used anymore.

Since the other process is probably writing the file in the moment you try to copy it with your application, the first option is by no means recommendable. It could also be an anti-virus checking the new file, and even in this case the first option would not be recommendable.

You could try to integrate the following code into your CopyImage method so that your application will wait until the file will be no longer in use before proceeding:

private Boolean WaitForFile(String filePath)
{
    Int32 tries = 0;

    while (true)
    {
        ++tries;

        Boolean wait = false;
        FileStream stream = null;

        try
        {
            stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
            break;
        }
        catch (Exception ex)
        {
            Logger.LogWarning("CopyImage({0}) failed to get an exclusive lock: {1}", filePath, ex.ToString());

            if (tries > 10)
            {
                Logger.LogWarning("CopyImage({0}) skipped the file after 10 tries.", filePath);
                return false;
            }

            wait = true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        if (wait)
            Thread.Sleep(250);
    }

    Logger.LogWarning("CopyImage({0}) got an exclusive lock after {1} tries.", filePath, tries);

    return true;
}


问:
How to change the color of a JSeparator using the Nimbus L&F
Here is what I've tried in my attempt to change a vertical JSeparator's color from Nimbus default black to red based on the answer in How to change the color of a JSeparator?:

```<code>public class TestFrame extends JFrame {

    public static void main(String[] args) {

        TestFrame frame = new TestFrame();
        frame.setSize(200, 200);
        frame.setLayout(new GridBagLayout());

        for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                try {
                    UIManager.setLookAndFeel(info.getClassName());
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
            }
        }
        UIManager.put("Separator.background", Color.red);
        UIManager.put("Separator.foreground", Color.red);

        JSeparator separator = new JSeparator(JSeparator.VERTICAL);
        separator.setPreferredSize(new Dimension(2, 100));
        separator.setForeground(Color.red);
        separator.setBackground(Color.red);

        frame.add(separator, new GridBagConstraints());
        frame.setVisible(true);

    }

}
</code>```

Yet the vertical separator remains black. What should I be doing?

Note: I know Nimbus is the issue, because I tried without setting the L&F to Nimbus and this worked fine. Also to note that setting the Separator[Enabled].backgroundPainter property seems to have affected the JSeperator but not in the way I intended (just changed the background color vs the separating line color)

答:
```<code>  /**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Windows look and feel instead of NIMBUS*/
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
      /*Change This Line To Make Your TextField Transparent */      if ("WINDOWS".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Furious.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Furious.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Furious.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Furious.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Furious().setVisible(true);
        }
    });
}
</code>```

Just Change Your Look and feel from NIMBUS to WINDOWS,it worked fine for me.

Here is Snapshot Of My UI:

Body:
Here is what I've tried in my attempt to change a vertical JSeparator's color from Nimbus default black to red based on the answer in How to change the color of a JSeparator?:

public class TestFrame extends JFrame {

    public static void main(String[] args) {

        TestFrame frame = new TestFrame();
        frame.setSize(200, 200);
        frame.setLayout(new GridBagLayout());

        for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                try {
                    UIManager.setLookAndFeel(info.getClassName());
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
            }
        }
        UIManager.put("Separator.background", Color.red);
        UIManager.put("Separator.foreground", Color.red);

        JSeparator separator = new JSeparator(JSeparator.VERTICAL);
        separator.setPreferredSize(new Dimension(2, 100));
        separator.setForeground(Color.red);
        separator.setBackground(Color.red);

        frame.add(separator, new GridBagConstraints());
        frame.setVisible(true);

    }

}

Yet the vertical separator remains black. What should I be doing?

Note: I know Nimbus is the issue, because I tried without setting the L&F to Nimbus and this worked fine. Also to note that setting the Separator[Enabled].backgroundPainter property seems to have affected the JSeperator but not in the way I intended (just changed the background color vs the separating line color)

Body:
  /**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Windows look and feel instead of NIMBUS*/
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
      /*Change This Line To Make Your TextField Transparent */      if ("WINDOWS".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Furious.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Furious.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Furious.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Furious.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Furious().setVisible(true);
        }
    });
}

Just Change Your Look and feel from NIMBUS to WINDOWS,it worked fine for me.

Here is Snapshot Of My UI:


答:
Use class for the definition in HTML and don't use quotes around the hex value.

.test1 {
  background-color: #ffbf00;
}
.test2 {
  background-color: #92D050;
}
.test3 {
  background-color: ' ';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="testTable">
  <tr class="test1">
    <td>Test</td>
    <td>Test</td>
  </tr>
</table></code>```

Title: CSS - Apply conditional style to table row

Body:
Use class for the definition in HTML and don't use quotes around the hex value.

.test1 {
  background-color: #ffbf00;
}
.test2 {
  background-color: #92D050;
}
.test3 {
  background-color: ' ';
}

<table id="testTable">
  <tr class="test1">
    <td>Test</td>
    <td>Test</td>
  </tr>
</table>


问:
Formatting Floating Point Numbers
I have a variable of type double, I need to print it in upto 3 decimals of precision but it shouldn't have any trailing zeros...

eg. I need

```<code>2.5 // not 2.500
2   // not 2.000
1.375 // exactly till 3 decimals
2.12  // not 2.120
</code>```

I tried using DecimalFormatter, Am i doing it wrong?

```<code>DecimalFormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);
</code>```

Thanks. :)

答:
Try the pattern "0.###" instead of "0.000":

```<code>import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("0.###");
        double[] tests = {2.50, 2.0, 1.3751212, 2.1200};
        for(double d : tests) {
            System.out.println(df.format(d));
        }
    }
}
</code>```

output:

```<code>2.5
2
1.375
2.12
</code>```

Title: Formatting Floating Point Numbers

Body:
I have a variable of type double, I need to print it in upto 3 decimals of precision but it shouldn't have any trailing zeros...

eg. I need

2.5 // not 2.500
2   // not 2.000
1.375 // exactly till 3 decimals
2.12  // not 2.120

I tried using DecimalFormatter, Am i doing it wrong?

DecimalFormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);

Thanks. :)

Body:
Try the pattern "0.###" instead of "0.000":

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("0.###");
        double[] tests = {2.50, 2.0, 1.3751212, 2.1200};
        for(double d : tests) {
            System.out.println(df.format(d));
        }
    }
}

output:

2.5
2
1.375
2.12


问:
vue-styleguidist error when dependency contains a .vue file
I'm generating documentation for a VueJS component using vue-styleguidist.

This normally works just fine, but in this case I get an error:

```<code>./node_modules/vue-awesome/components/Icon.vue
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
 <template>
   <svg version="1.1"
     :class="klass"

Learn how to add webpack loaders to your style guide:
https://github.com/vue-styleguidist/vue-styleguidist/blob/master/docs/Webpack.md
</code>```

My config file for vue-styleguidist (styleguide.config.js) includes the default rules for loading webpack files:

```<code>const loaders = require('vue-webpack-loaders');

module.exports = {
  ...
  webpackConfig: {
    module: {
      loaders,
    },
    ...
  },
  ...
};
</code>```

Other .vue files are loaded correctly, but not Icon.vue.

答:
The problem is that the default webpack loading rule provided by vue-webpack-loaders specifically excludes mode_modules directory, but the npm module contains that Vue file Icon.vue.

```<code>{
    test: /\.vue$/,
    exclude: /node_modules/,
    loader: 'vue-loader',
    options: vueLoaderConfig
},
</code>```

The solution is to add an extra rule to the default rules to specifically load that file under node_modules.

```<code>const loaders = require('vue-webpack-loaders');

var vueLoaderConfig = require('vue-webpack-loaders/lib/vue-loader.conf')
loaders.push({
  test: /vue-awesome\/components\/Icon\.vue$/,   <-- path to .vue file
  loader: 'vue-loader',
  options: vueLoaderConfig
})
</code>```

Body:
I'm generating documentation for a VueJS component using vue-styleguidist.

This normally works just fine, but in this case I get an error:

./node_modules/vue-awesome/components/Icon.vue
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
 <template>
   <svg version="1.1"
     :class="klass"

Learn how to add webpack loaders to your style guide:
https://github.com/vue-styleguidist/vue-styleguidist/blob/master/docs/Webpack.md

My config file for vue-styleguidist (styleguide.config.js) includes the default rules for loading webpack files:

const loaders = require('vue-webpack-loaders');

module.exports = {
  ...
  webpackConfig: {
    module: {
      loaders,
    },
    ...
  },
  ...
};

Other .vue files are loaded correctly, but not Icon.vue.

Body:
The problem is that the default webpack loading rule provided by vue-webpack-loaders specifically excludes mode_modules directory, but the npm module contains that Vue file Icon.vue.

{
    test: /\.vue$/,
    exclude: /node_modules/,
    loader: 'vue-loader',
    options: vueLoaderConfig
},

The solution is to add an extra rule to the default rules to specifically load that file under node_modules.

const loaders = require('vue-webpack-loaders');

var vueLoaderConfig = require('vue-webpack-loaders/lib/vue-loader.conf')
loaders.push({
  test: /vue-awesome\/components\/Icon\.vue$/,   <-- path to .vue file
  loader: 'vue-loader',
  options: vueLoaderConfig
})


答:
Split using this regex \s*:\s*

```<code>String[] arraysplit = str_array.split("\\s*:\\s*");
</code>```

details :

\s* zero or more spaces

followed by lateral character :

followed by  \s* zero or more spaces

regex demo

Title: Converting a string[] into a string then split into an array

Body:
Split using this regex \s*:\s*

String[] arraysplit = str_array.split("\\s*:\\s*");

details :

\s* zero or more spaces

followed by lateral character :

followed by  \s* zero or more spaces

regex demo


问:
Migrating to Durable Function
I have a non-durable pipeline of three Azure Http Trigger Functions. They pass along a custom json graph in a sequence.

I have started to migrate this to Durable Functions (using the sample as a basis) and it appears that I can just pass the json graph around as a string without using Task<HttpResponseMessage> etc.

Is this the best way with Durable Functions. Could I still keep each function as a HttpTrigger in order to have the flexibility of calling the whole pipeline as Durable but each individual as an HttpTrigger?

答: Each function needs to have an ActivityTrigger to work with Durable Functions - and we do not support having multiple triggers for a single function. To keep both options (HTTP Triggered or as part of a Durable orchestration) you would likely need to factor out the common code into a shared method that each function can invoke.</p>

Title: Migrating to Durable Function