问:
How to set default permission to /opt/ directory
I have set "chmod -R 777 . /opt/" and made the directory writable. However, this gave error to my phpmyadmin (inside /opt/lampp/) which should not be writable.

Can someone help me to reset to default permission of the /opt/ directory?

Great Thanks!

答:
My /opt directory has permissions drwxr-xr-x with owner root:root. You can set this as follows

```<code>sudo chown root:root /opt
sudo chmod 0755 /opt
</code>```

If you have changed the permissions of sub-directories, then the solution is not generic. Though my subdirectories also have same permissions, it can be different. -R parameter can do this recursively.

```<code>sudo chown -R root:root /opt
sudo chmod -R 0755 /opt
</code>```

Body:
My /opt directory has permissions drwxr-xr-x with owner root:root. You can set this as follows

sudo chown root:root /opt
sudo chmod 0755 /opt

If you have changed the permissions of sub-directories, then the solution is not generic. Though my subdirectories also have same permissions, it can be different. -R parameter can do this recursively.

sudo chown -R root:root /opt
sudo chmod -R 0755 /opt


来源: stackexchange

问:
PHP - HTML Select Menu - Include Value outside of Array
I'm creating a simple HTML Select Menu using PHP from an array as follows:

```<code>$output = '';

foreach($symptoms as $symptom) {

    $symptom = htmlspecialchars($symptom);
    if ($symptom == $record->getField('PatientSymptom')) {
      $output = "<option value='".$symptom."' selected='selected' >$symptom</option>";
    } else {
      $output = "<option value='".$symptom."'>$symptom</option>";
    }
    echo $output;
}
</code>```

This creates the HTML select menu from the $symptoms array successfully, but the original value stored in the input field that I'm displaying might not be part of the $symptoms array. I need to add this to the select menu in this case but not sure the best way to go about this.

I'm storing the original value in a variable: $patientSymptom

What's the best way to check if $patientSymptom isn't in the $symptoms array and add that to the select menu I'm creating?

答:
Use in_array() function:

in_array — Checks if a value exists in an array

Check if element exists in array right before the loop and add it if necessary:

```<code>$output = '';
if (!in_array($patientSymptom, $symptoms)) {
   $symptoms[] = $patientSymptom; // add symptom to end of the array
}
foreach($symptoms as $symptom) {
// ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm creating a simple HTML Select Menu using PHP from an array as follows:

$output = '';

foreach($symptoms as $symptom) {

    $symptom = htmlspecialchars($symptom);
    if ($symptom == $record->getField('PatientSymptom')) {
      $output = "<option value='".$symptom."' selected='selected' >$symptom</option>";
    } else {
      $output = "<option value='".$symptom."'>$symptom</option>";
    }
    echo $output;
}

This creates the HTML select menu from the $symptoms array successfully, but the original value stored in the input field that I'm displaying might not be part of the $symptoms array. I need to add this to the select menu in this case but not sure the best way to go about this.

I'm storing the original value in a variable: $patientSymptom

What's the best way to check if $patientSymptom isn't in the $symptoms array and add that to the select menu I'm creating?

Body:
Use in_array() function:

in_array — Checks if a value exists in an array

Check if element exists in array right before the loop and add it if necessary:

$output = '';
if (!in_array($patientSymptom, $symptoms)) {
   $symptoms[] = $patientSymptom; // add symptom to end of the array
}
foreach($symptoms as $symptom) {
// ...


问:
SAS Regex code to capture Business Address from 10-K company filings
Consider the following EDGAR 10-K SEC Company Filing
https://www.sec.gov/Archives/edgar/data/912382/000136231009004179/0001362310-09-004179.txt

```<code>BUSINESS ADDRESS:
    STREET 1:       107 N PENNSYLVANIA ST
    STREET 2:       STE 600
    CITY:           INDIANAPOLIS
    STATE:          IN
    ZIP:            46204
    BUSINESS PHONE:     3172619000

MAIL ADDRESS:
    STREET 1:       107 N PENNSYLVANIA ST
    STREET 2:       STE 600
    CITY:           INDIANAPOLIS
    STATE:          IN
    ZIP:            46204
</code>```

I need a regex in SAS to capture the fields STREET 1, STREET 2, CITY, STATE and ZIP under the Business Address, but not the Mailing Address. For example for STREET 1, I use STREET\s2\s*(.*) in SAS, but it ends up capturing the STREET 1 for Mailing address. Thanks!

答:
This regex should work.

```<code>BUSINESS ADDRESS:\s*STREET\s1:\s*(.*)\s*STREET\s2:\s*(.*)
</code>```

You can continue the pattern to capture each section you need in a new parenthesis. Basically you're just making sure that you get the first answer after business address. The problem with the pattern you were using is that it was able to match the pattern in two separate locations, and the regex engine will only return the last match it finds. Therefore you have to put something in that specifies which one you want.

In SAS you can use the prxposn function with the second argument indicating the capture buffer (parenthesis) to retrieve. For example.

```<code>address1=prxposn(regex_pattern, 1, edgar10);
</code>```

Best.

Body:
Consider the following EDGAR 10-K SEC Company Filing
https://www.sec.gov/Archives/edgar/data/912382/000136231009004179/0001362310-09-004179.txt

BUSINESS ADDRESS:
    STREET 1:       107 N PENNSYLVANIA ST
    STREET 2:       STE 600
    CITY:           INDIANAPOLIS
    STATE:          IN
    ZIP:            46204
    BUSINESS PHONE:     3172619000

MAIL ADDRESS:
    STREET 1:       107 N PENNSYLVANIA ST
    STREET 2:       STE 600
    CITY:           INDIANAPOLIS
    STATE:          IN
    ZIP:            46204

I need a regex in SAS to capture the fields STREET 1, STREET 2, CITY, STATE and ZIP under the Business Address, but not the Mailing Address. For example for STREET 1, I use STREET\s2\s*(.*) in SAS, but it ends up capturing the STREET 1 for Mailing address. Thanks!

Body:
This regex should work.

BUSINESS ADDRESS:\s*STREET\s1:\s*(.*)\s*STREET\s2:\s*(.*)

You can continue the pattern to capture each section you need in a new parenthesis. Basically you're just making sure that you get the first answer after business address. The problem with the pattern you were using is that it was able to match the pattern in two separate locations, and the regex engine will only return the last match it finds. Therefore you have to put something in that specifies which one you want.

In SAS you can use the prxposn function with the second argument indicating the capture buffer (parenthesis) to retrieve. For example.

address1=prxposn(regex_pattern, 1, edgar10);

Best.


问:
Cannot install openCV 3.1.0 with python3. CMAKE not including or linking python correctly
I'm trying to get OpenCV 3.1.0 installed with Python3 on my machine. Because I have Ubuntu 16.04, I am following this guide exactly:

http://www.pyimagesearch.com/2016/10/24/ubuntu-16-04-how-to-install-opencv/

However, I have trouble in step 4, after running cmake. The output of my cmake program has this snippet:

```<code>--   OpenCL:
--     Version:                     dynamic
--     Include path:                /home/kevin/opencv-3.1.0/3rdparty/include/opencl/1.2
--     Use AMDFFT:                  NO
--     Use AMDBLAS:                 NO
--
--   Python 2:
--     Interpreter:                 /home/kevin/.virtualenvs/cv/bin/python (ver 3.5.2)
--
--   Python 3:
--     Interpreter:                 /home/kevin/.virtualenvs/cv/bin/python3 (ver 3.5.2)
--
--   Python (for build):            /home/kevin/.virtualenvs/cv/bin/python
--
--   Java:
--     ant:                         NO
--     JNI:                         /usr/lib/jvm/java-8-oracle/include /usr/lib/jvm/java-8-oracle/include/linux /usr/lib/jvm/java-8-oracle/include
--     Java wrappers:               NO
--     Java tests:                  NO
</code>```

The cmake file doesnt seem to properly link the missing properties under the python section (libraries, numpy, packages_path). I tried compiling opencv and installing it, and when I load python3 and import cv, it says it could not find the cv package.

I tried modifying the CMAKE command, so instead of using what the guide suggested, I added three parameters to force cmake to include the missing python properties (the last three properties were my modification):

```<code>cmake -D CMAKE_BUILD_TYPE=RELEASE     \
-D CMAKE_INSTALL_PREFIX=/usr/local     \
-D INSTALL_PYTHON_EXAMPLES=ON     \
-D INSTALL_C_EXAMPLES=OFF     \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.1.0/modules     \
-D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python     \
-D BUILD_EXAMPLES=ON    \
-D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.5m.so    \
-D PYTHON_NUMPY_INCLUDE_DIR=~/.virtualenvs/cv/lib/python3.5/site-packages/numpy/core/include    \
-D PYTHON_PACKAGES_PATH=~/.virtualenvs/cv/lib/python3.5/site-packes ..
</code>```

But still, the output of cmake is the same (it only lists the interpretter, and no other python properties), and when I try building opencv and installing it, my python interpretter could not find the opencv package.

My /usr/local/lib/python3.5/ file did NOT have a site-packages directory after I finished installing opencv either.

Can anyone point me in the right direction? I've been trying to search the past few hours on how to fix this, but could not find a way so far, so I'd greatly appreciate any guidance. Thank you!

Update

I realize that I have to add -D BUILD_opencv_python3=yes to the cmake command so that opencv looks for the python libraries. However, this is the new output that I get from cmake:

```<code>--   Python 3:
--     Interpreter:                 /home/kevin/.virtualenvs/cv/bin/python (ver 3.5.2)
--     Libraries:                   NO
--     numpy:                       NO (Python3 wrappers can not be generated)
--     packages path:               lib/python3.5/site-packages
</code>```

Any idea why cmake is not finding my python 3 libraries correctly (even when I add "-D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.5m.so " to the cmake options)?

Update

I fixed the problem by deleting the entire /build directory, and running cmake on a fresh directory. I think the error continued to show up because of some caching done by cmake, but adding the flag -D BUILD_opencv_python3=yes seem to do the trick for me.

答: I fixed my problem by deleting the entire /build directory, and running cmake again (with -D BUILD_opencv_python3=yes). I think it gave an error because of some sort of caching from cmake, so when I deleted everything and started over again, the error was gone.</p>

Body:
I'm trying to get OpenCV 3.1.0 installed with Python3 on my machine. Because I have Ubuntu 16.04, I am following this guide exactly:

http://www.pyimagesearch.com/2016/10/24/ubuntu-16-04-how-to-install-opencv/

However, I have trouble in step 4, after running cmake. The output of my cmake program has this snippet:

--   OpenCL:
--     Version:                     dynamic
--     Include path:                /home/kevin/opencv-3.1.0/3rdparty/include/opencl/1.2
--     Use AMDFFT:                  NO
--     Use AMDBLAS:                 NO
--
--   Python 2:
--     Interpreter:                 /home/kevin/.virtualenvs/cv/bin/python (ver 3.5.2)
--
--   Python 3:
--     Interpreter:                 /home/kevin/.virtualenvs/cv/bin/python3 (ver 3.5.2)
--
--   Python (for build):            /home/kevin/.virtualenvs/cv/bin/python
--
--   Java:
--     ant:                         NO
--     JNI:                         /usr/lib/jvm/java-8-oracle/include /usr/lib/jvm/java-8-oracle/include/linux /usr/lib/jvm/java-8-oracle/include
--     Java wrappers:               NO
--     Java tests:                  NO

The cmake file doesnt seem to properly link the missing properties under the python section (libraries, numpy, packages_path). I tried compiling opencv and installing it, and when I load python3 and import cv, it says it could not find the cv package.

I tried modifying the CMAKE command, so instead of using what the guide suggested, I added three parameters to force cmake to include the missing python properties (the last three properties were my modification):

cmake -D CMAKE_BUILD_TYPE=RELEASE     \
-D CMAKE_INSTALL_PREFIX=/usr/local     \
-D INSTALL_PYTHON_EXAMPLES=ON     \
-D INSTALL_C_EXAMPLES=OFF     \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.1.0/modules     \
-D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python     \
-D BUILD_EXAMPLES=ON    \
-D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.5m.so    \
-D PYTHON_NUMPY_INCLUDE_DIR=~/.virtualenvs/cv/lib/python3.5/site-packages/numpy/core/include    \
-D PYTHON_PACKAGES_PATH=~/.virtualenvs/cv/lib/python3.5/site-packes ..

But still, the output of cmake is the same (it only lists the interpretter, and no other python properties), and when I try building opencv and installing it, my python interpretter could not find the opencv package.

My /usr/local/lib/python3.5/ file did NOT have a site-packages directory after I finished installing opencv either.

Can anyone point me in the right direction? I've been trying to search the past few hours on how to fix this, but could not find a way so far, so I'd greatly appreciate any guidance. Thank you!

Update

I realize that I have to add -D BUILD_opencv_python3=yes to the cmake command so that opencv looks for the python libraries. However, this is the new output that I get from cmake:

--   Python 3:
--     Interpreter:                 /home/kevin/.virtualenvs/cv/bin/python (ver 3.5.2)
--     Libraries:                   NO
--     numpy:                       NO (Python3 wrappers can not be generated)
--     packages path:               lib/python3.5/site-packages

Any idea why cmake is not finding my python 3 libraries correctly (even when I add "-D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.5m.so " to the cmake options)?

Update

I fixed the problem by deleting the entire /build directory, and running cmake on a fresh directory. I think the error continued to show up because of some caching done by cmake, but adding the flag -D BUILD_opencv_python3=yes seem to do the trick for me.


问:
Expected running time of randomized binary search
I want to calculate the expected running time of randomized binary search of the following pseudo-code, where instead of considering the midpoint as the pivot, a random point is selected:

```<code>BinarySearch(x, A, start, end)
    if(start == end)
        if(A[end] == x)
            return end
        else
            return -1
    else
        mid = RANDOM(start, end)
        if(A[mid] == x)
            return mid
        else if(A[mid] > x)
            return BinarySearch(x, A, start, mid-1)
        else
            return BinarySearch(x, A, mid+1, end)
</code>```

I looked at this previous question, which has the following:

```<code>T(n) = sum ( T(r)*Pr(search space becomes r) ) + O(1) = sum ( T(r) )/n + O(1)
</code>```

How is this obtained?

```<code>sum( T(r)*Pr(search space becomes r) )
</code>```

And in the last line of calculation, how was this obtained?

```<code>T(n) = 1 + 1/2 + 1/3 + ... + 1/(n-1) = H(n-1) < H(n) = O(log n)
</code>```

答:
```<code>sum( T(r)*Pr(search space becomes r) )
</code>```

This line obtained by observing fact that you can choose any point to partition array, so to get expected time you need to sum up all possiblities multiplied with their probabilities. See expected value.

```<code>T(n) = 1 + 1/2 + 1/3 + ... + 1/(n-1) = H(n-1) < H(n) = O(log n)
</code>```

About this line. Well you can think of it as of integral of 1/x on [1, n] and it is log(n) - log(1) = log(n). See Harmonic series.

Body:
I want to calculate the expected running time of randomized binary search of the following pseudo-code, where instead of considering the midpoint as the pivot, a random point is selected:

BinarySearch(x, A, start, end)
    if(start == end)
        if(A[end] == x)
            return end
        else
            return -1
    else
        mid = RANDOM(start, end)
        if(A[mid] == x)
            return mid
        else if(A[mid] > x)
            return BinarySearch(x, A, start, mid-1)
        else
            return BinarySearch(x, A, mid+1, end)

I looked at this previous question, which has the following:

T(n) = sum ( T(r)*Pr(search space becomes r) ) + O(1) = sum ( T(r) )/n + O(1)

How is this obtained?

sum( T(r)*Pr(search space becomes r) )

And in the last line of calculation, how was this obtained?

T(n) = 1 + 1/2 + 1/3 + ... + 1/(n-1) = H(n-1) < H(n) = O(log n)

Body:
sum( T(r)*Pr(search space becomes r) )

This line obtained by observing fact that you can choose any point to partition array, so to get expected time you need to sum up all possiblities multiplied with their probabilities. See expected value.

T(n) = 1 + 1/2 + 1/3 + ... + 1/(n-1) = H(n-1) < H(n) = O(log n)

About this line. Well you can think of it as of integral of 1/x on [1, n] and it is log(n) - log(1) = log(n). See Harmonic series.


问:
JavaScript array.sort with multiple values (strings and numbers)
I'd like to sort an array by subject (string, alphabetical), then level (int, ascending), then name (string, alphabetical). I have found numerous other threads on SO but I haven't found any which sort by multiple variable types. I thought I had it, but it isn't sorting properly.

The sort function:

```<code>scipads.sort(function (a, b) {
    if (a.subject != b.subject)
        return a.subject < b.subject;
    if (a.level != b.level)
        return a.level - b.level;
    return a.name < b.name;
});
</code>```

The  array:

```<code>var scipads = [{
        "name": "L2 Physics Externals",
        "level": 2,
        "subject": "physics",
    }, {
        "name": "L2 Physics Internals",
        "level": 2,
        "subject": "physics",
    }, {
        "name": "L2 Chem Externals",
        "level": 2,
        "subject": "chemistry",
    }, {
        "name": "L2 Chem Internals",
        "level": 2,
        "subject": "chemistry",
    }, {
        "name": "L2 Bio Internals",
        "level": 2,
        "subject": "biology",
    }, {
        "name": "L2 Bio Externals",
        "level": 2,
        "subject": "biology",
    }, {
        "name": "L1 Electricity & Magnetism",
        "level": 1,
        "subject": "physics",
    }, {
        "name": "L1 Wave Behaviour",
        "level": 1,
        "subject": "physics",
    }, {
        "name": "L1 Heat",
        "level": 1,
        "subject": "physics",
    }, {
        "name": "L1 Carbon Chemistry",
        "level": 1,
        "subject": "chemistry",
    }, {
        "name": "L1 Selected Elements",
        "level": 1,
        "subject": "chemistry",
    }, {
        "name": "L1 Chemical Reactions",
        "level": 1,
        "subject": "chemistry",
    },
];
</code>```

How can I sort by subject, then level, then name?

答:
My solution, compare subject first, then compare the level

var scipads=[{name:"L2 Physics Externals",level:2,subject:"physics"},{name:"L2 Physics Internals",level:2,subject:"physics"},{name:"L2 Chem Externals",level:2,subject:"chemistry"},{name:"L2 Chem Internals",level:2,subject:"chemistry"},{name:"L2 Bio Internals",level:2,subject:"biology"},{name:"L2 Bio Externals",level:2,subject:"biology"},{name:"L1 Electricity & Magnetism",level:1,subject:"physics"},{name:"L1 Wave Behaviour",level:1,subject:"physics"},{name:"L1 Heat",level:1,subject:"physics"},{name:"L1 Carbon Chemistry",level:1,subject:"chemistry"},{name:"L1 Selected Elements",level:1,subject:"chemistry"},{name:"L1 Chemical Reactions",level:1,subject:"chemistry"}];

// sort by subject, then level, then name
var res = scipads.sort((a, b) => {
  if (a.subject > b.subject) {
    return 1;
  } else if (a.subject  b.level){
    return 1;
  } else if (a.level  b.name) {
    return 1;
  } else if (a.name < b.name) {
    return -1;
  }
  return 0;
});

console.log(res)```

Body:
I'd like to sort an array by subject (string, alphabetical), then level (int, ascending), then name (string, alphabetical). I have found numerous other threads on SO but I haven't found any which sort by multiple variable types. I thought I had it, but it isn't sorting properly.

The sort function:

scipads.sort(function (a, b) {
    if (a.subject != b.subject)
        return a.subject < b.subject;
    if (a.level != b.level)
        return a.level - b.level;
    return a.name < b.name;
});

The  array:

var scipads = [{
        "name": "L2 Physics Externals",
        "level": 2,
        "subject": "physics",
    }, {
        "name": "L2 Physics Internals",
        "level": 2,
        "subject": "physics",
    }, {
        "name": "L2 Chem Externals",
        "level": 2,
        "subject": "chemistry",
    }, {
        "name": "L2 Chem Internals",
        "level": 2,
        "subject": "chemistry",
    }, {
        "name": "L2 Bio Internals",
        "level": 2,
        "subject": "biology",
    }, {
        "name": "L2 Bio Externals",
        "level": 2,
        "subject": "biology",
    }, {
        "name": "L1 Electricity & Magnetism",
        "level": 1,
        "subject": "physics",
    }, {
        "name": "L1 Wave Behaviour",
        "level": 1,
        "subject": "physics",
    }, {
        "name": "L1 Heat",
        "level": 1,
        "subject": "physics",
    }, {
        "name": "L1 Carbon Chemistry",
        "level": 1,
        "subject": "chemistry",
    }, {
        "name": "L1 Selected Elements",
        "level": 1,
        "subject": "chemistry",
    }, {
        "name": "L1 Chemical Reactions",
        "level": 1,
        "subject": "chemistry",
    },
];

How can I sort by subject, then level, then name?

Body:
My solution, compare subject first, then compare the level

var scipads=[{name:"L2 Physics Externals",level:2,subject:"physics"},{name:"L2 Physics Internals",level:2,subject:"physics"},{name:"L2 Chem Externals",level:2,subject:"chemistry"},{name:"L2 Chem Internals",level:2,subject:"chemistry"},{name:"L2 Bio Internals",level:2,subject:"biology"},{name:"L2 Bio Externals",level:2,subject:"biology"},{name:"L1 Electricity & Magnetism",level:1,subject:"physics"},{name:"L1 Wave Behaviour",level:1,subject:"physics"},{name:"L1 Heat",level:1,subject:"physics"},{name:"L1 Carbon Chemistry",level:1,subject:"chemistry"},{name:"L1 Selected Elements",level:1,subject:"chemistry"},{name:"L1 Chemical Reactions",level:1,subject:"chemistry"}];

// sort by subject, then level, then name
var res = scipads.sort((a, b) => {
  if (a.subject > b.subject) {
    return 1;
  } else if (a.subject < b.subject) {
    return -1;
  } else if ( a.level > b.level){
    return 1;
  } else if (a.level < b.level) {
    return -1;
  } else if (a.name > b.name) {
    return 1;
  } else if (a.name < b.name) {
    return -1;
  }
  return 0;
});

console.log(res)


问:
Printing an arraylist with an enhanced foor loop - error: cannot find symbol and variable already defined in method
I am new to java and am trying to write a method that will print out an ArrayList using an enhanced for loop. Whenever I compile, the fore loop gives me the following errors:

error: cannot find symbol

error: variable list2 is already defined in
     method printLists(ArrayList,ArrayList)
           for(String list2: list)

```<code>public static void printLists(ArrayList <String> list1, ArrayList <String> list2 )
{
    System.out.println("list1.txt contains:");
    for(String list1: list)
        System.out.println(list1+ " ");

    System.out.println("list2.txt contains:");
    for(String list2: list)
        System.out.println(list2+ " ");
}
</code>```

Can someone please explain to me what these errors mean?

答:
You've swapped list and list1 (and list2) in your for-each loops. However, I would first suggest you program to the List interface. And assuming you are using Java 8+, I would prefer to stream() the contents and join them with a Collector. Like,

```<code>public static void printLists(List<String> list1, List<String> list2) {
    System.out.printf("list1.txt contains: %s%n", list1.stream()
            .collect(Collectors.joining(" ")));
    System.out.printf("list2.txt contains: %s%n", list2.stream()
            .collect(Collectors.joining(" ")));
}
</code>```

or possibly make the arguments variadic and generic (so it can take any number of Lists of any type) like

```<code>@SafeVarargs
public static <T> void printLists(List<T>... lists) {
    for (int i = 0; i < lists.length; i++) {
        System.out.printf("list%d.txt contains: %s%n", i + 1,
                lists[i].stream().map(Object::toString).collect(
                        Collectors.joining(" ")));
    }
}
</code>```

Body:
I am new to java and am trying to write a method that will print out an ArrayList using an enhanced for loop. Whenever I compile, the fore loop gives me the following errors:

error: cannot find symbol

error: variable list2 is already defined in
     method printLists(ArrayList,ArrayList)
           for(String list2: list)

public static void printLists(ArrayList <String> list1, ArrayList <String> list2 )
{
    System.out.println("list1.txt contains:");
    for(String list1: list)
        System.out.println(list1+ " ");

    System.out.println("list2.txt contains:");
    for(String list2: list)
        System.out.println(list2+ " ");
}

Can someone please explain to me what these errors mean?

Body:
You've swapped list and list1 (and list2) in your for-each loops. However, I would first suggest you program to the List interface. And assuming you are using Java 8+, I would prefer to stream() the contents and join them with a Collector. Like,

public static void printLists(List<String> list1, List<String> list2) {
    System.out.printf("list1.txt contains: %s%n", list1.stream()
            .collect(Collectors.joining(" ")));
    System.out.printf("list2.txt contains: %s%n", list2.stream()
            .collect(Collectors.joining(" ")));
}

or possibly make the arguments variadic and generic (so it can take any number of Lists of any type) like

@SafeVarargs
public static <T> void printLists(List<T>... lists) {
    for (int i = 0; i < lists.length; i++) {
        System.out.printf("list%d.txt contains: %s%n", i + 1,
                lists[i].stream().map(Object::toString).collect(
                        Collectors.joining(" ")));
    }
}


问:
Given that I have a hash of id(key) and countries(values) sorted alphabetically, what is the best way to bubble up an entry to the top of the stack?
This is a php example, but an algorithm for any language would do. What I specifically want to do is bubble up the United States and Canada to the top of the list. Here is an example of the array shortened for brevity.

```<code>array(
  0 => '-- SELECT --',
  1 => 'Afghanistan',
  2 => 'Albania',
  3 => 'Algeria',
  4 => 'American Samoa',
  5 => 'Andorra',)
</code>```

The id's need to stay intact. So making them -1 or -2 will unfortunately not work.

答:
What I usually do in these situations is to add a separate field called DisplayOrder or something similar.  Everything defaults to, say, 1...  You then sort by DisplayOrder and then the Name.  If you want something higher or lower on the list, you can tweak the display order accordingly while keeping your normal IDs as-is.

-- Kevin Fairchild

OwnerDisplayName: mk

Body:
This is a php example, but an algorithm for any language would do. What I specifically want to do is bubble up the United States and Canada to the top of the list. Here is an example of the array shortened for brevity.

array(
  0 => '-- SELECT --',
  1 => 'Afghanistan',
  2 => 'Albania',
  3 => 'Algeria',
  4 => 'American Samoa',
  5 => 'Andorra',)

The id's need to stay intact. So making them -1 or -2 will unfortunately not work.

LastEditorDisplayName: mk

OwnerDisplayName: Kevin Fairchild

ContentLicense: CC BY-SA 2.5


问:
Do .Net Collection Classes Use .Equals() on contained members to evaluate .Contains()?
The subject pretty much says it all.

Does a collection class use an (overridden) .Equals() method to determine if the collection class .Contains() an element or not?  Or does it use reference equality or some other method?

I would like the collection class to ignore a single field on contained members when determining if the collection .Contains() an element or not.

答:
Collection uses EqualityComparer<T>.Default.  List isn't as clear (it says it uses "the default equality comparer, as defined by the object's implementation of the IEquatable<T>.Equals method for T", which doesn't explain what happens if it doesn't implement IEquatable), but I would suspect it's the same.

That will use the IEquatable<T> implementation if the type implements it, or just regular Object.Equals and Object.GetHashCode (which can be overriden).


问:
Java program given string to replace character in the place of another character
Example String str ="Java"; get output as "jXavXa".

hint: replace every 'a' with 'Xa'. and another one in same pgrm replace only last occurrence of 'e' to 'Xa'

example: I/p = "experience" and o/p= "experiencXe" .

答:
Try this.
if you want to replace last occurence of 'e' to 'Xa'.

```<code>String result = str.replaceAll("a|e$", "Xa");
</code>```

Or if you want to replace last occurrence of 'e' to 'Xe'.

```<code>String result = str.replaceAll("(a|e$)", "X$1");
</code>```

Body:
Try this.
if you want to replace last occurence of 'e' to 'Xa'.

String result = str.replaceAll("a|e$", "Xa");

Or if you want to replace last occurrence of 'e' to 'Xe'.

String result = str.replaceAll("(a|e$)", "X$1");


问:
grails run-war causing SLF4J: Class path contains multiple SLF4J bindings
I am using grails 2.4.2 version. When I run the command run-app then application runs fine, no error in Intellij console. When I run the command prod run-app, it also works fine without error. But when I run the command run-war then the following error is given. I have searched for it but no solutions is working for my case or I may not understanding.

Here my error below in Intellij console:

```<code>    |Done creating WAR target\alhikmah-0.1.war
|Running Grails application
Error |
SLF4J: Class path contains multiple SLF4J bindings.
Error |
SLF4J: Found binding in [jar:file:/C:/Users/aina/.m2/repository/org/grails/grails-plugin-log4j/2.4.2/grails-plugin-log4j-2.4.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
Error |
SLF4J: Found binding in [jar:file:/D:/projects/alhikmah/target/work/tomcat/webapps/alhikmah/WEB-INF/lib/grails-plugin-log4j-2.4.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
Error |
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
Error |
SLF4J: Actual binding is of type [org.slf4j.impl.GrailsSlf4jLoggerFactory]
Error |
log4j:WARN No appenders could be found for logger (org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener).
Error |
log4j:WARN Please initialize the log4j system properly.
Error |
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception sending context initialized event to listener instance of class org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pluginManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.reflect.MalformedParameterizedTypeException
    at java.beans.FeatureDescriptor.getParameterTypes(FeatureDescriptor.java:387)
    at java.beans.MethodDescriptor.setMethod(MethodDescriptor.java:114)
    at java.beans.MethodDescriptor.<init>(MethodDescriptor.java:72)
    at java.beans.MethodDescriptor.<init>(MethodDescriptor.java:56)
    at java.beans.Introspector.getTargetMethodInfo(Introspector.java:1131)
    at java.beans.Introspector.getBeanInfo(Introspector.java:414)
    at java.beans.Introspector.getBeanInfo(Introspector.java:161)
    ... 5 more
Error listenerStart
Context [/alhikmah] startup failed due to previous errors
The web application [/alhikmah] registered the JDBC driver [org.h2.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
The web application [/alhikmah] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
The web application [/alhikmah] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.
|Server running. Browse to http://localhost:8080/alhikmah
|Server running. Browse to http://localhost:8080/alhikmah
</code>```

答:
Upgrading your Grails version might solve your problem.
Procedure to upgrade

Project -> Clean

application.properties -> Change app.grails.version = (New version)

Your project -> Properties -> Grails -> Change grails installation to new grails version.

Your project -> Grails tools -> Refresh Dependencies

Run your project

Or have a look on it Grails Upgrade

ContentLicense: CC BY-SA 4.0

Body:
I am using grails 2.4.2 version. When I run the command run-app then application runs fine, no error in Intellij console. When I run the command prod run-app, it also works fine without error. But when I run the command run-war then the following error is given. I have searched for it but no solutions is working for my case or I may not understanding.

Here my error below in Intellij console:

    |Done creating WAR target\alhikmah-0.1.war
|Running Grails application
Error |
SLF4J: Class path contains multiple SLF4J bindings.
Error |
SLF4J: Found binding in [jar:file:/C:/Users/aina/.m2/repository/org/grails/grails-plugin-log4j/2.4.2/grails-plugin-log4j-2.4.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
Error |
SLF4J: Found binding in [jar:file:/D:/projects/alhikmah/target/work/tomcat/webapps/alhikmah/WEB-INF/lib/grails-plugin-log4j-2.4.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
Error |
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
Error |
SLF4J: Actual binding is of type [org.slf4j.impl.GrailsSlf4jLoggerFactory]
Error |
log4j:WARN No appenders could be found for logger (org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener).
Error |
log4j:WARN Please initialize the log4j system properly.
Error |
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception sending context initialized event to listener instance of class org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pluginManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.reflect.MalformedParameterizedTypeException
    at java.beans.FeatureDescriptor.getParameterTypes(FeatureDescriptor.java:387)
    at java.beans.MethodDescriptor.setMethod(MethodDescriptor.java:114)
    at java.beans.MethodDescriptor.<init>(MethodDescriptor.java:72)
    at java.beans.MethodDescriptor.<init>(MethodDescriptor.java:56)
    at java.beans.Introspector.getTargetMethodInfo(Introspector.java:1131)
    at java.beans.Introspector.getBeanInfo(Introspector.java:414)
    at java.beans.Introspector.getBeanInfo(Introspector.java:161)
    ... 5 more
Error listenerStart
Context [/alhikmah] startup failed due to previous errors
The web application [/alhikmah] registered the JDBC driver [org.h2.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
The web application [/alhikmah] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
The web application [/alhikmah] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.
|Server running. Browse to http://localhost:8080/alhikmah
|Server running. Browse to http://localhost:8080/alhikmah


问:
Matlab. Place legend outside the plot
I have the following code

```<code>T = [0:1:30]
a = [5:1:35]; a2 = [0:1:30];
b = [-4:1:26]; b2 = [12:1:42];
c = [16:1:46]; c2 = [15:1:45];
d = [2:1:32]; d2 = [-5:1:25];
figure(1)
title('Time histories of output variables (measured vs estimated)')
subplot(411),plot(T,a, T,a2,'r'); grid; ylabel('p (°/s)');
subplot(412),plot(T,b, T,b2,'r'); grid; ylabel('r (°/s)');
subplot(413),plot(T,c, T,c2,'r'); grid; ylabel('phi (º)');
subplot(414),plot(T,d, T,d2,'r'); grid; ylabel('ay (m/s2)');
legend('measured','estimated','Location','bestoutside')
xlabel('Time [s]');
</code>```

Which generates the following plot

I would like to have the legend outside the plot and that all of them remains with the normal size. (So the legend should be in one of those red circles. Any solutions?

答:
You could add another subplot to act as an empty region to hold only the legend, with the axes visibility turned off and nan values for the 'YData' of the plotted lines, so they don't render:

```<code>figure(1);
hSub = subplot(511); plot(1, nan, 1, nan, 'r'); set(hSub, 'Visible', 'off');
subplot(512); plot(T, a, T, a2, 'r'); grid; ylabel('p (°/s)');
subplot(513); plot(T, b, T, b2, 'r'); grid; ylabel('r (°/s)');
subplot(514); plot(T, c, T, c2, 'r'); grid; ylabel('phi (º)');
subplot(515); plot(T, d, T, d2, 'r'); grid; ylabel('ay (m/s2)');
xlabel('Time [s]');
legend(hSub, 'measured', 'estimated', 'Location', 'east');
</code>```

And here's the result:

Title: Matlab. Place legend outside the plot

Body:
I have the following code

T = [0:1:30]
a = [5:1:35]; a2 = [0:1:30];
b = [-4:1:26]; b2 = [12:1:42];
c = [16:1:46]; c2 = [15:1:45];
d = [2:1:32]; d2 = [-5:1:25];
figure(1)
title('Time histories of output variables (measured vs estimated)')
subplot(411),plot(T,a, T,a2,'r'); grid; ylabel('p (°/s)');
subplot(412),plot(T,b, T,b2,'r'); grid; ylabel('r (°/s)');
subplot(413),plot(T,c, T,c2,'r'); grid; ylabel('phi (º)');
subplot(414),plot(T,d, T,d2,'r'); grid; ylabel('ay (m/s2)');
legend('measured','estimated','Location','bestoutside')
xlabel('Time [s]');

Which generates the following plot

I would like to have the legend outside the plot and that all of them remains with the normal size. (So the legend should be in one of those red circles. Any solutions?

Body:
You could add another subplot to act as an empty region to hold only the legend, with the axes visibility turned off and nan values for the 'YData' of the plotted lines, so they don't render:

figure(1);
hSub = subplot(511); plot(1, nan, 1, nan, 'r'); set(hSub, 'Visible', 'off');
subplot(512); plot(T, a, T, a2, 'r'); grid; ylabel('p (°/s)');
subplot(513); plot(T, b, T, b2, 'r'); grid; ylabel('r (°/s)');
subplot(514); plot(T, c, T, c2, 'r'); grid; ylabel('phi (º)');
subplot(515); plot(T, d, T, d2, 'r'); grid; ylabel('ay (m/s2)');
xlabel('Time [s]');
legend(hSub, 'measured', 'estimated', 'Location', 'east');

And here's the result:


问:
HTML5 Audio Plays Randomly
I am implementing sound effects in HTML5 audio but after a while, it just stops playing any audio. The file type is correct because it starts fine but then seems to give up.

```<code>var sound = new Audio(url);
function play() {
    sound.play();
}
</code>```

Is there a better way to do this so it consistently plays sound?

Here is a link to my implementation. Easy to reproduce by pressing spacebar a lot until it eventually gives up (also shoot the lights for added sounds). http://craftyjs.com/elevatoraction/

This occurs for me in the latest version of Chrome (8.0)

Edit: I did as Gaurav suggested and only played the same instance of each sound file, but the same sort of problems are present. It will arbitrarily stop playing.

Edit 2: I just noticed that whenever I try to play the sound, the networkState is always 1 which according to this means it hasn't fully loaded. That is odd seeing as it still plays sometimes and even when it plays the networkState is always 1

答:
Don't create a new audio object each time you want to play a sound, reuse the same resource.

```<code>var sound1 = new Audio(url);
function playSound1() {
    sound1.play();
}
</code>```

I think this is related to the bug http://code.google.com/p/chromium/issues/detail?id=57070

Title: HTML5 Audio Plays Randomly

Body:
I am implementing sound effects in HTML5 audio but after a while, it just stops playing any audio. The file type is correct because it starts fine but then seems to give up.

var sound = new Audio(url);
function play() {
    sound.play();
}

Is there a better way to do this so it consistently plays sound?

Here is a link to my implementation. Easy to reproduce by pressing spacebar a lot until it eventually gives up (also shoot the lights for added sounds). http://craftyjs.com/elevatoraction/

This occurs for me in the latest version of Chrome (8.0)

Edit: I did as Gaurav suggested and only played the same instance of each sound file, but the same sort of problems are present. It will arbitrarily stop playing.

Edit 2: I just noticed that whenever I try to play the sound, the networkState is always 1 which according to this means it hasn't fully loaded. That is odd seeing as it still plays sometimes and even when it plays the networkState is always 1

Body:
Don't create a new audio object each time you want to play a sound, reuse the same resource.

var sound1 = new Audio(url);
function playSound1() {
    sound1.play();
}

I think this is related to the bug http://code.google.com/p/chromium/issues/detail?id=57070


答:
To compare string, you should use string.localeCompare. Also, you can try to create an array with priority list and loop over it to sort.

var scipads=[{name:"L2 Physics Externals",level:2,subject:"physics"},{name:"L2 Physics Internals",level:2,subject:"physics"},{name:"L2 Chem Externals",level:2,subject:"chemistry"},{name:"L2 Chem Internals",level:2,subject:"chemistry"},{name:"L2 Bio Internals",level:2,subject:"biology"},{name:"L2 Bio Externals",level:2,subject:"biology"},{name:"L1 Electricity & Magnetism",level:1,subject:"physics"},{name:"L1 Wave Behaviour",level:1,subject:"physics"},{name:"L1 Heat",level:1,subject:"physics"},{name:"L1 Carbon Chemistry",level:1,subject:"chemistry"},{name:"L1 Selected Elements",level:1,subject:"chemistry"},{name:"L1 Chemical Reactions",level:1,subject:"chemistry"}];

var priority = ["subject", "level", "name"]

scipads.sort(function(a,b){
  var val = 0;
  priority.some(function(k){
    val = compare(a,b,k);
    return val !== 0;
  });
})

function compare(a,b,k){
  switch(typeof a[k]){
    case "string": return a[k].localeCompare(b[k]);
    case "number": return a[k] - b[k]
  }
}

console.log(scipads)```

Title: JavaScript array.sort with multiple values (strings and numbers)


问:
How can I create iterators of a filtered vector?
Suppose I have a vector named spot_deals of SpotDeal that is a class:

```<code>class SpotDeal
{
public:
    int deal_id_; // primary key, and vector is sorted by id
    string ccy_pair_; // ccy pair, e.g. GBPUSD, AUDUSD
    double amount_;
}
</code>```

Say I need to pass two subset of spot_deals to a function foo for some computation. I could make copies, however, that would cost memory and time. Actually foo only needs iterators of deals. So can I make 2 iterators of vector<SpotDeal>, namely it1 and it2 and pass them to foo?

The two subset of spot_deals could be filtered by ccy_pair_, e.g. deals of GBPUSD and AUDUSD, or by other conditions. So I'm looking for a way to define an iterator defined by a vector and a lambda function (could equivalently be a functor though).

Is there a way to write a helper function make_filtered_iterator so that I can have something like below?

```<code>auto it1 = make_filtered_iterator(spot_deals, filter_lambda1);
auto it2 = make_filtered_iterator(spot_deals, filter_lambda2);
foo(it1, it2);
</code>```

答:
By chance, I've recently worked on this exact problem. As it turns out, filtering is the most complicated of quite some operations on a container, and also contains the most pitfalls.

```<code>template<typename Range, typename Pred>
class filter
{
public:
    friend class const_iterator;
    class const_iterator : public std::iterator_traits<typename Range::const_iterator>
    {
        using underlying = typename Range::const_iterator;
    public:
        auto operator*() {return *u;}
        const_iterator& operator++()
        {
            ++u;
            normalize();
            return *this;
        }
        const_iterator operator++(int)
        {
            auto t = *this;
            u++;
            normalize();
            return t;
        }
        bool operator==(const const_iterator& rhs) const {return u == rhs.u;}
        bool operator!=(const const_iterator& rhs) const {return !(*this == rhs);}
    private:
        friend filter;
        const_iterator(underlying u, const filter& f) : u{std::move(u)}, f{f} {normalize();}
        void normalize()
        {
            for(; u != f.r.end() && !f.p(*u); u++);
        }

        underlying u;
        const filter& f;
    };

    filter(const Range& r, const Pred& p) : r{r}, p{p} {}

    auto begin() const {return const_iterator{r.begin(), *this};}
    auto end() const {return const_iterator{r.end(), *this};}

private:
    const Range& r;
    Pred p;
};
</code>```

We use it as (with c++17 guide)

```<code>vector<int> v{1, 2, 3, 4, 5};
auto f = filter(v, [](int x){return x & 1;});
for(auto i : f)
    // all i in v that is odd
</code>```

Let me explain the pitfalls:

The first element might be filtered out, *r.begin() might not be an element in the filtered range. This means the iterator has to be checked on construction.

r.end() might be invalidated without invalidating other iterators, that is to say, saving a copy of r.end() in any iterators to compare with is a logic error.

operator== is not very straightforward, two underlying iterators referring to different elements in the original range might be referring to the same element in the filtered view because filtered out elements doesn't count as an element.

Body:
Suppose I have a vector named spot_deals of SpotDeal that is a class:

class SpotDeal
{
public:
    int deal_id_; // primary key, and vector is sorted by id
    string ccy_pair_; // ccy pair, e.g. GBPUSD, AUDUSD
    double amount_;
}

Say I need to pass two subset of spot_deals to a function foo for some computation. I could make copies, however, that would cost memory and time. Actually foo only needs iterators of deals. So can I make 2 iterators of vector<SpotDeal>, namely it1 and it2 and pass them to foo?

The two subset of spot_deals could be filtered by ccy_pair_, e.g. deals of GBPUSD and AUDUSD, or by other conditions. So I'm looking for a way to define an iterator defined by a vector and a lambda function (could equivalently be a functor though).

Is there a way to write a helper function make_filtered_iterator so that I can have something like below?

auto it1 = make_filtered_iterator(spot_deals, filter_lambda1);
auto it2 = make_filtered_iterator(spot_deals, filter_lambda2);
foo(it1, it2);

Body:
By chance, I've recently worked on this exact problem. As it turns out, filtering is the most complicated of quite some operations on a container, and also contains the most pitfalls.

template<typename Range, typename Pred>
class filter
{
public:
    friend class const_iterator;
    class const_iterator : public std::iterator_traits<typename Range::const_iterator>
    {
        using underlying = typename Range::const_iterator;
    public:
        auto operator*() {return *u;}
        const_iterator& operator++()
        {
            ++u;
            normalize();
            return *this;
        }
        const_iterator operator++(int)
        {
            auto t = *this;
            u++;
            normalize();
            return t;
        }
        bool operator==(const const_iterator& rhs) const {return u == rhs.u;}
        bool operator!=(const const_iterator& rhs) const {return !(*this == rhs);}
    private:
        friend filter;
        const_iterator(underlying u, const filter& f) : u{std::move(u)}, f{f} {normalize();}
        void normalize()
        {
            for(; u != f.r.end() && !f.p(*u); u++);
        }

        underlying u;
        const filter& f;
    };

    filter(const Range& r, const Pred& p) : r{r}, p{p} {}

    auto begin() const {return const_iterator{r.begin(), *this};}
    auto end() const {return const_iterator{r.end(), *this};}

private:
    const Range& r;
    Pred p;
};

We use it as (with c++17 guide)

vector<int> v{1, 2, 3, 4, 5};
auto f = filter(v, [](int x){return x & 1;});
for(auto i : f)
    // all i in v that is odd

Let me explain the pitfalls:

The first element might be filtered out, *r.begin() might not be an element in the filtered range. This means the iterator has to be checked on construction.

r.end() might be invalidated without invalidating other iterators, that is to say, saving a copy of r.end() in any iterators to compare with is a logic error.

operator== is not very straightforward, two underlying iterators referring to different elements in the original range might be referring to the same element in the filtered view because filtered out elements doesn't count as an element.


问:
How to implement a method with an unknown number of arguments?
I have 1 interface and 3 class. I would like the class to be able to both implement the interface which need a transform method. This method must exist but there can't be more than one per class. I don't know the number of parameters taken by this class.

Example :

```<code>public interface A{
    public void transform(Object ... args);
}

public class B implements A{
    public void transform(String a){
        System.out.println(a);
    }
}

public class C implements A{
    public void transform(Integer a, Character b){
        System.out.println(a+b);
    }
}

// super generic case if possible with Objects + primitive
public class D implements A{
    public void transform(int a, String b){
        System.out.println(a+b);
    }
}
</code>```

This doesn't work. But I hope you got the idea. Is something like this possible in java ? How should I call them in a generic way ? Let's say if I have an other method like :

```<code>void callTransf(A a, Object ... objs){
    Method m = a.getClass().getMethods()[0];
    m.invoke(a, objs)
}
</code>```

答:
You can achieve what you want, with some changes and some help of functional programming...

TL;DR

The main idea is that the transform method doesn't receive any arguments. Instead, it will return an instance of some functional interface.

The implementation of this functional interface will consist of the code that would have been executed by the transform method if it had arguments.

To represent arguments of different types and/or a different number of arguments for each subclass of the A interface, we'll use covariance in the return type of the method transform.

This means that the functional interface will be generic (so that the type of the arguments can be different for each subclass of A), and that there will be subinterfaces that will extend this functional interface, each one accepting a different number of arguments in its single abstract method. This will allow the transform() method's return value to have either 1, 2, 3, ... etc arguments.

To execute the code returned by the transform() method, we'll do:

```<code>instanceOfB.transform().execute("hello");
instanceOfC.transform().execute(1, 'a');
instanceOfD.transform().execute(1, "hello");
</code>```

Finally, in order to be able to execute the code in a generic way, the base functional interface defines a varargs method executeVariadic(Object... args), which will be implemented as a default method by every child functional interface, delegating to its execute method and casting the arguments as needed.

Now the long version...

Let's start by renaming your A interface to something more descriptive. As it defines a method called transform, let's name it Transformer.

Then, let's create a functional interface that will represent the transform method of the Transformer interface. Here it is:

```<code>@FunctionalInterface
public interface Transformation {

    void executeVariadic(Object... args);
}
</code>```

This interface just defines one single abstract method (SAM) that receives an Object... varargs argument. It is there so that subinterfaces can override it.

Now, let's create a Transformation1 functional interface that extends the Transformation interface:

```<code>@FunctionalInterface
public interface Transformation1<A> extends Transformation {

    void execute(A a);

    @Override
    @SuppressWarnings("unchecked")
    default void executeVariadic(Object... args) {
        this.execute((A) args[0]);
    }
}
</code>```

This Transformation1 functional interface is generic and defines the single abstract method execute, which takes one argument of type A. The executeVariadic method is overriden as a default method that delegates its execution to the execute method, casting the first argument accordingly. This cast generates a warning, but oh, well... we'd better learn to live with it.

Now, let's create an analogous interface with two generic type parameters and an execute method that receives two arguments whose types match the generic type parameters:

```<code>@FunctionalInterface
public interface Transformation2<A, B> extends Transformation {

    void execute(A a, B b);

    @Override
    @SuppressWarnings("unchecked")
    default void executeVariadic(Object... args) {
        this.execute((A) args[0], (B) args[1]);
    }
}
</code>```

The idea is the same: the Transformation2 interface extends the Transformation interface and we override the executeVariadic method so that it is delegated to the execute method, casting the arguments accordingly (and suppressing the annoying warning).

For completeness, let's introduce the Transformation3 interface, which is analogous to the previous TransformationX ones:

```<code>@FunctionalInterface
public interface Transformation3<A, B, C> extends Transformation {

    void execute(A a, B b, C c);

    @Override
    @SuppressWarnings("unchecked")
    default void executeVariadic(Object... args) {
        this.execute((A) args[0], (B) args[1], (C) args[2]);
    }
}
</code>```

Hope the pattern is clear by now. You should create as many TransformationX interfaces as arguments you want to support for the transform method of your Transformer interface (A interface in your question, remember I've renamed it).

So far so good, I know this answer is long, but I needed to define the interfaces above so that they can now be used to put all the pieces together.

Remember your A interface? Let's not only keep its name changed to Transformer, but also the signature of its transform method:

```<code>@FunctionalInterface
public interface Transformer {

    Transformation transform();
}
</code>```

So this is your base interface now. The transform method no longer has arguments, but returns a Transformation instead.

Let's see how to implement your B, C and D classes now. But first, allow me to rename them to TransformerB, TransformerC and TransformerD, respectively.

Here's TransformerB:

```<code>public class TransformerB implements Transformer {

    @Override
    public Transformation1<String> transform() {
        return a -> System.out.println(a); // or System.out::println
    }
}
</code>```

The important thing here is the use of covariance in the return type of the transform method. And I'm using the Transformation1<String> type, which is a subtype of Transformation and indicates that, for the TransformerB class, the transform method returns a transformation that accepts one argument of type String. As the Transformation1 interface is a SAM type, I'm using a lambda expression to implement it.

Here's how to invoke the code inside the TransformerB.transform method:

```<code>TransformerB b = new TransformerB();
b.transform().execute("hello");
</code>```

b.transform() returns an instance of Transformation1, whose execute method is immediately invoked with the String argument it expects.

Now let's see the implementation of TransformerC:

```<code>public class TransformerC implements Transformer {

    @Override
    public Transformation2<Integer, Character> transform() {
        return (a, b) -> System.out.println(a + b);
    }
}
</code>```

Again, covariance in the return type of the transform method allows us to return a concrete Transformation, in this case Transformation2<Integer, Character>.

Usage:

```<code>TransformerC c = new TransformerC();
c.transform().execute(1, 'A');
</code>```

For the TransformerD example, I've used a three-argument transformation:

```<code>public class TransformerD implements Transformer {

    public Transformation3<Integer, Double, String> transform() {
        return (a, b, c) -> System.out.println(a + b + c);
    }
}
</code>```

Usage:

```<code>TransformerD d = new TransformerD();
d.transform().execute(12, 2.22, "goodbye");
</code>```

This is all type-safe, because the generic types can be specified in the TransformationX return type of each concrete transform method implementation. It's not possible to use primitive types, though, because primitive types cannot be used as generic type parameters.

Regarding how to call the transform method in a generic way, it's straightforward:

```<code>void callTransf(Transformer a, Object... args) {
    a.transform().executeVariadic(args);
}
</code>```

This is why the executeVariadic method exists. And it's overriden in each TransformationX interface, so that it can be used polymorphically, as in the code above.

Calling the callTransf method is straightforward too:

```<code>callTransf(b, "hello");
callTransf(c, 1, 'A');
callTransf(d, 12, 2.22, "goodbye");
</code>```

Body:
I have 1 interface and 3 class. I would like the class to be able to both implement the interface which need a transform method. This method must exist but there can't be more than one per class. I don't know the number of parameters taken by this class.

Example :

public interface A{
    public void transform(Object ... args);
}

public class B implements A{
    public void transform(String a){
        System.out.println(a);
    }
}

public class C implements A{
    public void transform(Integer a, Character b){
        System.out.println(a+b);
    }
}

// super generic case if possible with Objects + primitive
public class D implements A{
    public void transform(int a, String b){
        System.out.println(a+b);
    }
}

This doesn't work. But I hope you got the idea. Is something like this possible in java ? How should I call them in a generic way ? Let's say if I have an other method like :

void callTransf(A a, Object ... objs){
    Method m = a.getClass().getMethods()[0];
    m.invoke(a, objs)
}

Body:
You can achieve what you want, with some changes and some help of functional programming...

TL;DR

The main idea is that the transform method doesn't receive any arguments. Instead, it will return an instance of some functional interface.

The implementation of this functional interface will consist of the code that would have been executed by the transform method if it had arguments.

To represent arguments of different types and/or a different number of arguments for each subclass of the A interface, we'll use covariance in the return type of the method transform.

This means that the functional interface will be generic (so that the type of the arguments can be different for each subclass of A), and that there will be subinterfaces that will extend this functional interface, each one accepting a different number of arguments in its single abstract method. This will allow the transform() method's return value to have either 1, 2, 3, ... etc arguments.

To execute the code returned by the transform() method, we'll do:

instanceOfB.transform().execute("hello");
instanceOfC.transform().execute(1, 'a');
instanceOfD.transform().execute(1, "hello");

Finally, in order to be able to execute the code in a generic way, the base functional interface defines a varargs method executeVariadic(Object... args), which will be implemented as a default method by every child functional interface, delegating to its execute method and casting the arguments as needed.

Now the long version...

Let's start by renaming your A interface to something more descriptive. As it defines a method called transform, let's name it Transformer.

Then, let's create a functional interface that will represent the transform method of the Transformer interface. Here it is:

@FunctionalInterface
public interface Transformation {

    void executeVariadic(Object... args);
}

This interface just defines one single abstract method (SAM) that receives an Object... varargs argument. It is there so that subinterfaces can override it.

Now, let's create a Transformation1 functional interface that extends the Transformation interface:

@FunctionalInterface
public interface Transformation1<A> extends Transformation {

    void execute(A a);

    @Override
    @SuppressWarnings("unchecked")
    default void executeVariadic(Object... args) {
        this.execute((A) args[0]);
    }
}

This Transformation1<A> functional interface is generic and defines the single abstract method execute, which takes one argument of type A. The executeVariadic method is overriden as a default method that delegates its execution to the execute method, casting the first argument accordingly. This cast generates a warning, but oh, well... we'd better learn to live with it.

Now, let's create an analogous interface with two generic type parameters and an execute method that receives two arguments whose types match the generic type parameters:

@FunctionalInterface
public interface Transformation2<A, B> extends Transformation {

    void execute(A a, B b);

    @Override
    @SuppressWarnings("unchecked")
    default void executeVariadic(Object... args) {
        this.execute((A) args[0], (B) args[1]);
    }
}

The idea is the same: the Transformation2 interface extends the Transformation interface and we override the executeVariadic method so that it is delegated to the execute method, casting the arguments accordingly (and suppressing the annoying warning).

For completeness, let's introduce the Transformation3 interface, which is analogous to the previous TransformationX ones:

@FunctionalInterface
public interface Transformation3<A, B, C> extends Transformation {

    void execute(A a, B b, C c);

    @Override
    @SuppressWarnings("unchecked")
    default void executeVariadic(Object... args) {
        this.execute((A) args[0], (B) args[1], (C) args[2]);
    }
}

Hope the pattern is clear by now. You should create as many TransformationX interfaces as arguments you want to support for the transform method of your Transformer interface (A interface in your question, remember I've renamed it).

So far so good, I know this answer is long, but I needed to define the interfaces above so that they can now be used to put all the pieces together.

Remember your A interface? Let's not only keep its name changed to Transformer, but also the signature of its transform method:

@FunctionalInterface
public interface Transformer {

    Transformation transform();
}

So this is your base interface now. The transform method no longer has arguments, but returns a Transformation instead.

Let's see how to implement your B, C and D classes now. But first, allow me to rename them to TransformerB, TransformerC and TransformerD, respectively.

Here's TransformerB:

public class TransformerB implements Transformer {

    @Override
    public Transformation1<String> transform() {
        return a -> System.out.println(a); // or System.out::println
    }
}

The important thing here is the use of covariance in the return type of the transform method. And I'm using the Transformation1<String> type, which is a subtype of Transformation and indicates that, for the TransformerB class, the transform method returns a transformation that accepts one argument of type String. As the Transformation1 interface is a SAM type, I'm using a lambda expression to implement it.

Here's how to invoke the code inside the TransformerB.transform method:

TransformerB b = new TransformerB();
b.transform().execute("hello");

b.transform() returns an instance of Transformation1, whose execute method is immediately invoked with the String argument it expects.

Now let's see the implementation of TransformerC:

public class TransformerC implements Transformer {

    @Override
    public Transformation2<Integer, Character> transform() {
        return (a, b) -> System.out.println(a + b);
    }
}

Again, covariance in the return type of the transform method allows us to return a concrete Transformation, in this case Transformation2<Integer, Character>.

Usage:

TransformerC c = new TransformerC();
c.transform().execute(1, 'A');

For the TransformerD example, I've used a three-argument transformation:

public class TransformerD implements Transformer {

    public Transformation3<Integer, Double, String> transform() {
        return (a, b, c) -> System.out.println(a + b + c);
    }
}

Usage:

TransformerD d = new TransformerD();
d.transform().execute(12, 2.22, "goodbye");

This is all type-safe, because the generic types can be specified in the TransformationX return type of each concrete transform method implementation. It's not possible to use primitive types, though, because primitive types cannot be used as generic type parameters.

Regarding how to call the transform method in a generic way, it's straightforward:

void callTransf(Transformer a, Object... args) {
    a.transform().executeVariadic(args);
}

This is why the executeVariadic method exists. And it's overriden in each TransformationX interface, so that it can be used polymorphically, as in the code above.

Calling the callTransf method is straightforward too:

callTransf(b, "hello");
callTransf(c, 1, 'A');
callTransf(d, 12, 2.22, "goodbye");


问:
Why is my program goes straight to else block when it should enter if
I was trying to make a simple survey bot, but I had trouble with the second if statement. it just ignores the if and elif, and goes straight to the else statement. I have tried everything, and even though it's probably going to be an easy solution please help...

```<code> import sys

 yes = "yes"
 no = "no"
 experience_good = "yes"
 contact = "1"

 print("How many times have you bean contacted by us in the past quarter (3 months)")
 contact = sys.stdin.readline()

 if contact != 0:
     print("Was your experience was us good? Type a 1 for yes or 0 for no")
     experience_good = sys.stdin.readline()
     print("experiencence_good is", experience_good)
     # The above line was just to double check the variable was inputted
correctly
     if experience_good is 1:
         print("Good to hear that.")
     elif experience_good is 0:
         print("Sorry about that. What could we be doing better?")
         doing_better = sys.stdin.readline()
     else:
         print("Stuff's been messed up")
</code>```

The output I get is just:

How many times have you bean contacted by us in the past quarter (3
months)

3

Was your experience was us good? Type a 1 for yes or 0 for no

1

exp_good is 1

Stuff's been messed up

答:
because experience_good is never 1! It's starts off as

```<code>experience_good = "yes"
</code>```

Then halfway through it maybe changed as

```<code>experience_good = sys.stdin.readline()
</code>```

At this point if the user typed in 1, what the variable will hold is the string value '1' which is not 1 so you need to

```<code>experience_good = int(sys.stdin.readline().strip())
</code>```

Body:
I was trying to make a simple survey bot, but I had trouble with the second if statement. it just ignores the if and elif, and goes straight to the else statement. I have tried everything, and even though it's probably going to be an easy solution please help...

 import sys

 yes = "yes"
 no = "no"
 experience_good = "yes"
 contact = "1"

 print("How many times have you bean contacted by us in the past quarter (3 months)")
 contact = sys.stdin.readline()

 if contact != 0:
     print("Was your experience was us good? Type a 1 for yes or 0 for no")
     experience_good = sys.stdin.readline()
     print("experiencence_good is", experience_good)
     # The above line was just to double check the variable was inputted
correctly
     if experience_good is 1:
         print("Good to hear that.")
     elif experience_good is 0:
         print("Sorry about that. What could we be doing better?")
         doing_better = sys.stdin.readline()
     else:
         print("Stuff's been messed up")

The output I get is just:

How many times have you bean contacted by us in the past quarter (3
months)

3

Was your experience was us good? Type a 1 for yes or 0 for no

1

exp_good is 1

Stuff's been messed up

Body:
because experience_good is never 1! It's starts off as

experience_good = "yes"

Then halfway through it maybe changed as

experience_good = sys.stdin.readline()

At this point if the user typed in 1, what the variable will hold is the string value '1' which is not 1 so you need to

experience_good = int(sys.stdin.readline().strip())


答:
You must use == for int equality test:

```<code>if contact != 0:
    print("Was your experience was us good? Type a 1 for yes or 0 for no")
    experience_good = sys.stdin.readline()
    print("experiencence_good is", experience_good)
    # The above line was just to double check the variable was inputted  correctly
    if experience_good == 1:
        print("Good to hear that.")
    elif experience_good == 0:
        print("Sorry about that. What could we be doing better?")
        doing_better = sys.stdin.readline()
    else:
        print("Stuff's been messed up")
</code>```

Cast the contact and experience_good to int:

```<code>contact = int(contact)

experience_good = int(experience_good)
</code>```

Title: Why is my program goes straight to else block when it should enter if

Body:
You must use == for int equality test:

if contact != 0:
    print("Was your experience was us good? Type a 1 for yes or 0 for no")
    experience_good = sys.stdin.readline()
    print("experiencence_good is", experience_good)
    # The above line was just to double check the variable was inputted  correctly
    if experience_good == 1:
        print("Good to hear that.")
    elif experience_good == 0:
        print("Sorry about that. What could we be doing better?")
        doing_better = sys.stdin.readline()
    else:
        print("Stuff's been messed up")

Cast the contact and experience_good to int:

contact = int(contact)

experience_good = int(experience_good)


问:
Visual Studio Setup Project installation kill existing process
I made a Visual studio setup project. I did the setup of my setup. Later this was born of a desire to make application to the Board to upgrade. When you do a new installation and need to install again the current running application kill. In the first installation custom actions or vbscript I tried but it didn't work. What can I do for that.</p>

答:
If your application has the appropriate access you can use this command.

```<code>taskkill -IM your-app.exe /T /F
</code>```

The /T argument will kill the process and its child processes.  The /F argument stands for 'Force'.

For more information on taskkill, run this command:

```<code>taskkill -?
</code>```

Hope this helps!

Body:
If your application has the appropriate access you can use this command.

taskkill -IM your-app.exe /T /F

The /T argument will kill the process and its child processes.  The /F argument stands for 'Force'.

For more information on taskkill, run this command:

taskkill -?

Hope this helps!


问:
I use regex for removing duplicate words in a string
but it remove white space. I don't want to remove white space! What should I do?

Original text

I like like like this movie, it was so so so good good
  good.

Remove duplicates

I likelike this movie, it was soso goodgood.

Here is my code:

```<code> String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1$1");
</code>```

答:
Updated Answer

Sorry for posting a second answer, but I just want to ascertain that you get notified of this answer.

```<code>String h = s.replaceAll("(?i)\\b([a-z]+)\\b((?:\\s+\\1\\b)+)", "$2");
h = h.replaceAll("\\s+", " "));
</code>```

This should remove the last repeated word :)

Body:
but it remove white space. I don't want to remove white space! What should I do?

Original text

I like like like this movie, it was so so so good good
  good.

Remove duplicates

I likelike this movie, it was soso goodgood.

Here is my code:

 String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1$1");

Body:
Updated Answer

Sorry for posting a second answer, but I just want to ascertain that you get notified of this answer.

String h = s.replaceAll("(?i)\\b([a-z]+)\\b((?:\\s+\\1\\b)+)", "$2");
h = h.replaceAll("\\s+", " "));

This should remove the last repeated word :)


答:
Indentation problem (now edited in question). Bring the last elif and last else block one indent backwards.

```<code>if experience_good == 1:
    print("Good to hear that.")
elif experience_good == 0:
    print("Sorry about that. What could we be doing better?")
    doing_better = sys.stdin.readline()
else:
    print("Stuff's been messed up")
</code>```

Use == to evaluate a value. When you use 'is' it will compare the objects. Not it's value.

Body:
Indentation problem (now edited in question). Bring the last elif and last else block one indent backwards.

if experience_good == 1:
    print("Good to hear that.")
elif experience_good == 0:
    print("Sorry about that. What could we be doing better?")
    doing_better = sys.stdin.readline()
else:
    print("Stuff's been messed up")

Use == to evaluate a value. When you use 'is' it will compare the objects. Not it's value.


问:
Force CharField's Choices
I have few models.CharField objects in my Model, with the choices attribute.

This is working great as far as the GUI is concerned, But I want to block values other than these specified in the choices attribute in the code itself (to protect myself from bugs).

Is there a way to raise an exception (I believe it'll be a ValueError) when trying to save a string which is not in the choices list?

答:
You could use the model clean method for that,</p>

```<code>class YourModel(models.Model):
    CHOICES = ('your_choices_here',)

    def clean(self):
        if not any(self.field_name in item for item in self.CHOICES):
            raise ValueError("Your error message here.")
</code>```

Title: Force CharField's Choices

Body:
You could use the model clean method for that,

class YourModel(models.Model):
    CHOICES = ('your_choices_here',)

    def clean(self):
        if not any(self.field_name in item for item in self.CHOICES):
            raise ValueError("Your error message here.")


问:
Is there a better way to do with_options in Rails 3 routes?
Here are my Rails 2 routes:

```<code>map.with_options :controller => 'foo', :conditions => { :method => :post } do |foo|
  foo.one 'one', :action => 'one'
  foo.two 'two', :action => 'two'

  foo.with_options :special_flag => 'true', :path_prefix => 'special_prefix',
    :conditions => { :method => :get } do |bar|
    bar.three '',        :action => 'for_blank'
    bar.four  'another', :action => 'for_another'
  end
end
</code>```

How do I convert this sort of thing to Rails 3? Just keep using with_options in the same way? It becomes wordier in some cases because instead of doing

```<code>match '' => 'foo#for_blank'
</code>```

I'm doing

```<code>match '', :action => 'for_blank'
</code>```

答: Try to stick to the methods the routes provide. They are very powerful in Rails 3 and should provide everything you need. See http://guides.rubyonrails.org/routing.html for more details</p>

Body:
Here are my Rails 2 routes:

map.with_options :controller => 'foo', :conditions => { :method => :post } do |foo|
  foo.one 'one', :action => 'one'
  foo.two 'two', :action => 'two'

  foo.with_options :special_flag => 'true', :path_prefix => 'special_prefix',
    :conditions => { :method => :get } do |bar|
    bar.three '',        :action => 'for_blank'
    bar.four  'another', :action => 'for_another'
  end
end

How do I convert this sort of thing to Rails 3? Just keep using with_options in the same way? It becomes wordier in some cases because instead of doing

match '' => 'foo#for_blank'

I'm doing

match '', :action => 'for_blank'


问:
Verify whether the next char is the same as first char
I found a problem and i tried my logic but i failed to get to the solution.

This is the problem i am trying to solve in java.

For every opening brace (i.e., (, {, or [), there is a matching closing brace (i.e., ), }, or ]) of the same type (i.e., (matches ), { matches }, and [ matches ]). An opening brace must appear before (to the left of) it’s matching closing brace. For example, ]{}[ is not balanced.

No unmatched braces lie between some pair of matched braces. For example, ({[]}) is balanced, but {[}] and [{)] are not balanced.

I want to write java code which would take such a string input of braces and output whether it is balanced or not.

I am not able to apply logic for this kind of code, i tried however it was not even close to expectations. Please provide with some logic. I know this is not a homework completion site but i am stuck on the logic of this problem. a code snippet would be appreciated.

答:
This has nothing to do with java. You need to use a stack to keep track of the order in which you encounter the brackets.

Algorithm-

loop over the input string.

If the current character is an opening bracket, push it in the stack

It it is a closing bracket, pop an element from the stack and if it is not the corresponding opening bracket to the current closing bracket then it is not balanced.

After traversing the string, if there is an opening bracket in the stack then it is not balanced.


问:
How to not use __init__.py as Flask app name?
I have a flask app structured like so:

repo_root

config.py

requirements.txt

my_cool_app/

my_cool_app/__init__.py

my_cool_app/models.py

my_cool_app/views.py

my_cool_app/static/

my_cool_app/templates/

And the contents of my_cool_app/__init__.py looks like:

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_oauth2_login import GoogleLogin
from flask_login import LoginManager

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
migrate = Migrate(app, db)

google_login = GoogleLogin(app)
login_manager = LoginManager()
login_manager.init_app(app)

import my_cool_app.models
import my_cool_app.views
</code>```

To run it, I invoke:

```<code>FLASK_APP=my_cool_app/__init__.py flask run
</code>```

Based on a variety of documentation online, I thought I should be able to just set FLASK_APP to the package name my_cool_app. When I do this, and invoke flask run, the application starts but in the browser I immediately see the error:

```<code>flask.cli.NoAppException
flask.cli.NoAppException: The file/path provided (my_cool_app) does not appear to exist.  Please verify the path is correct.  If app is not on PYTHONPATH, ensure the extension is .py
</code>```

What should I be doing to be able to set the FLASK_APP to just my_cool_app? Or is it more appropriate/typical for FLASK_APP to be set to something else, given the way this flask application is structured?

答:
It looks like your my_cool_app module isn't getting picked up in your python path.  If it's not, you'd need to set your PYTHONPATH variable as well.

Assuming you're in the repo_root directory when executing your command, you should be able to use:

```<code>FLASK_APP=my_cool_app PYTHONPATH=. flask run
</code>```

If you want to run it from anywhere, then:

```<code>FLASK_APP=my_cool_app PYTHONPATH=/path/to/repo flask run
</code>```

Body:
I have a flask app structured like so:

repo_root

config.py

requirements.txt

my_cool_app/

my_cool_app/__init__.py

my_cool_app/models.py

my_cool_app/views.py

my_cool_app/static/

my_cool_app/templates/

And the contents of my_cool_app/__init__.py looks like:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_oauth2_login import GoogleLogin
from flask_login import LoginManager

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
migrate = Migrate(app, db)

google_login = GoogleLogin(app)
login_manager = LoginManager()
login_manager.init_app(app)

import my_cool_app.models
import my_cool_app.views

To run it, I invoke:

FLASK_APP=my_cool_app/__init__.py flask run

Based on a variety of documentation online, I thought I should be able to just set FLASK_APP to the package name my_cool_app. When I do this, and invoke flask run, the application starts but in the browser I immediately see the error:

flask.cli.NoAppException
flask.cli.NoAppException: The file/path provided (my_cool_app) does not appear to exist.  Please verify the path is correct.  If app is not on PYTHONPATH, ensure the extension is .py

What should I be doing to be able to set the FLASK_APP to just my_cool_app? Or is it more appropriate/typical for FLASK_APP to be set to something else, given the way this flask application is structured?

Body:
It looks like your my_cool_app module isn't getting picked up in your python path.  If it's not, you'd need to set your PYTHONPATH variable as well.

Assuming you're in the repo_root directory when executing your command, you should be able to use:

FLASK_APP=my_cool_app PYTHONPATH=. flask run

If you want to run it from anywhere, then:

FLASK_APP=my_cool_app PYTHONPATH=/path/to/repo flask run


问:
Logstash missing JAVA_HOME
I'm new to Logstash everytime I try to run it I have the following error:

Could not find any executable java binary. Please install java in your PATH or set JAVA_HOME.

When I do echo $JAVA_HOME I have the following:

```<code>/usr/lib/java/jdk1.8.0_45/jre/bin
</code>```

What am I missing?

答:
In your case, you need to export the JAVA_HOME variable. Given by your information, this should do it for you:

```<code>export JAVA_HOME="/usr/lib/java/jdk1.8.0_45/jre/"
</code>```

If you type this command in a Linux Terminal, which I assume you use, the following Logstash is capable to find the java executable, which it needs to run logstash.

Title: Logstash missing JAVA_HOME

Body:
I'm new to Logstash everytime I try to run it I have the following error:

Could not find any executable java binary. Please install java in your PATH or set JAVA_HOME.

When I do echo $JAVA_HOME I have the following:

/usr/lib/java/jdk1.8.0_45/jre/bin

What am I missing?

Body:
In your case, you need to export the JAVA_HOME variable. Given by your information, this should do it for you:

export JAVA_HOME="/usr/lib/java/jdk1.8.0_45/jre/"

If you type this command in a Linux Terminal, which I assume you use, the following Logstash is capable to find the java executable, which it needs to run logstash.


答: There is an overload of Contains that takes an IEqualityComparer, so you can roll your own.</p>

Title: Do .Net Collection Classes Use .Equals() on contained members to evaluate .Contains()?

Body:
The subject pretty much says it all.

Does a collection class use an (overridden) .Equals() method to determine if the collection class .Contains() an element or not?  Or does it use reference equality or some other method?

I would like the collection class to ignore a single field on contained members when determining if the collection .Contains() an element or not.


问:
Material-UI Left Drawer in App Bar won't close on overlay click or menu item click in React
I am having an issue I can't seem to pin down where my LeftDrawer for my App Bar isn't closing if I click a menu item or the overlay (Not sure if this is an option, or possible with react components).  Ideally, I would like both options to close the Drawer.  Thank you in advance for taking your time to look at this!

This is my Navbar class I am using to toggle open the LeftDrawer:

```<code>// Dependencies
import React from 'react';

//Comonents
import LeftDrawer from './left-drawer.jsx';

// Styles
import './nav-bar.scss';
import AppBar from 'material-ui/AppBar';

class NavBar extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      open: false
    };
  }

  toggleDrawer(){
    this.setState({
      open: !this.state.open
    });
  }

  render(){
    return (
      <div className='nav-bar'>
        <AppBar title='My App' onLeftIconButtonTouchTap={() => this.toggleDrawer()}/>
        <LeftDrawer open={this.state.open} onToggleDrawer={this.toggleDrawer.bind(this)} />
      </div>
    );
  }
}

export default NavBar;
</code>```

This is the LeftDrawer class with the MenuItems:

```<code>// Dependencies
import React from 'react';
import { Link } from 'react-router-dom';

// Styles
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';

export default class LeftDrawer extends React.Component {
constructor(props) {
    super(props);
    this.state = {open: false};
}

handleToggle() {
    this.setState({open: !this.state.open});
}

handleClose() {
    this.setState({open: false});
}

render() {
    return (
        <div>
            <Drawer
                docked={false}
                width={200}
                open={this.props.open}
                onRequestChange={(open) => this.setState({open})}
            >
                <Link to="/home"><MenuItem onTouchTap={this.handleClose.bind(this)}>Home</MenuItem></Link>
                <Link to="/topics"><MenuItem onTouchTap={this.handleClose.bind(this)}>404</MenuItem></Link>
            </Drawer>
        </div>
        );
    }
}
</code>```

答:
Reason is you are controlling the Drawer by props values (state value of parent component) so you need to update the parent state value by calling a function from child.

Define a handleClose function in parent:

```<code>handleClose() {
    this.setState({open: false})
}
</code>```

pass this function to LeftDrawer component:

```<code><LeftDrawer open={this.state.open} handleClose={this.handleClose.bind(this)} onToggleDrawer={this.toggleDrawer.bind(this)} />
</code>```

Then inside child handleClose function call that parent handleClose function:

```<code>handleClose() {
    this.props.handleClose();
}
</code>```

Full Code:

```<code>import AppBar from 'material-ui/AppBar';

class NavBar extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      open: false
    };
    this.toggleDrawer = this.toggleDrawer.bind(this);
    this.handleClose = this.handleClose.bind(this);
  }

  toggleDrawer(){
    this.setState({
      open: !this.state.open
    });
  }

  handleClose(){
    this.setState({open: false})
  }

  render(){
    return (
      <div className='nav-bar'>
        <AppBar title='My App' onLeftIconButtonTouchTap={this.toggleDrawer}/>
        <LeftDrawer open={this.state.open} handleClose={this.handleClose} onToggleDrawer={this.toggleDrawer} />
      </div>
    );
  }
}

export default class LeftDrawer extends React.Component {
  constructor(props) {
      super(props);
      this.state = {open: false};
      this.handleClose = this.handleClose.bind(this);
  }

  handleToggle() {
      this.setState({open: !this.state.open});
  }

  handleClose() {
     this.props.handleClose();
  }

  render() {
    return (
        <div>
            <Drawer
                docked={false}
                width={200}
                open={this.props.open}
                onRequestChange={(open) => this.setState({open})}
            >
                <Link to="/home"><MenuItem onTouchTap={this.handleClose}>Home</MenuItem></Link>
                <Link to="/topics"><MenuItem onTouchTap={this.handleClose}>404</MenuItem></Link>
            </Drawer>
        </div>
    );
  }
}
</code>```

Body:
I am having an issue I can't seem to pin down where my LeftDrawer for my App Bar isn't closing if I click a menu item or the overlay (Not sure if this is an option, or possible with react components).  Ideally, I would like both options to close the Drawer.  Thank you in advance for taking your time to look at this!

This is my Navbar class I am using to toggle open the LeftDrawer:

// Dependencies
import React from 'react';

//Comonents
import LeftDrawer from './left-drawer.jsx';

// Styles
import './nav-bar.scss';
import AppBar from 'material-ui/AppBar';

class NavBar extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      open: false
    };
  }

  toggleDrawer(){
    this.setState({
      open: !this.state.open
    });
  }

  render(){
    return (

        <AppBar title='My App' onLeftIconButtonTouchTap={() => this.toggleDrawer()}/>
        <LeftDrawer open={this.state.open} onToggleDrawer={this.toggleDrawer.bind(this)} />

    );
  }
}

export default NavBar;

This is the LeftDrawer class with the MenuItems:

// Dependencies
import React from 'react';
import { Link } from 'react-router-dom';

// Styles
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';

export default class LeftDrawer extends React.Component {
constructor(props) {
    super(props);
    this.state = {open: false};
}

handleToggle() {
    this.setState({open: !this.state.open});
}

handleClose() {
    this.setState({open: false});
}

render() {
    return (

            <Drawer
                docked={false}
                width={200}
                open={this.props.open}
                onRequestChange={(open) => this.setState({open})}
            >
                <Link to="/home"><MenuItem onTouchTap={this.handleClose.bind(this)}>Home</MenuItem></Link>
                <Link to="/topics"><MenuItem onTouchTap={this.handleClose.bind(this)}>404</MenuItem></Link>
            </Drawer>

        );
    }
}

Body:
Reason is you are controlling the Drawer by props values (state value of parent component) so you need to update the parent state value by calling a function from child.

Define a handleClose function in parent:

handleClose() {
    this.setState({open: false})
}

pass this function to LeftDrawer component:

<LeftDrawer open={this.state.open} handleClose={this.handleClose.bind(this)} onToggleDrawer={this.toggleDrawer.bind(this)} />

Then inside child handleClose function call that parent handleClose function:

handleClose() {
    this.props.handleClose();
}

Full Code:

import AppBar from 'material-ui/AppBar';

class NavBar extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      open: false
    };
    this.toggleDrawer = this.toggleDrawer.bind(this);
    this.handleClose = this.handleClose.bind(this);
  }

  toggleDrawer(){
    this.setState({
      open: !this.state.open
    });
  }

  handleClose(){
    this.setState({open: false})
  }

  render(){
    return (
      <div className='nav-bar'>
        <AppBar title='My App' onLeftIconButtonTouchTap={this.toggleDrawer}/>
        <LeftDrawer open={this.state.open} handleClose={this.handleClose} onToggleDrawer={this.toggleDrawer} />
      </div>
    );
  }
}

export default class LeftDrawer extends React.Component {
  constructor(props) {
      super(props);
      this.state = {open: false};
      this.handleClose = this.handleClose.bind(this);
  }

  handleToggle() {
      this.setState({open: !this.state.open});
  }

  handleClose() {
     this.props.handleClose();
  }

  render() {
    return (
        <div>
            <Drawer
                docked={false}
                width={200}
                open={this.props.open}
                onRequestChange={(open) => this.setState({open})}
            >
                <Link to="/home"><MenuItem onTouchTap={this.handleClose}>Home</MenuItem></Link>
                <Link to="/topics"><MenuItem onTouchTap={this.handleClose}>404</MenuItem></Link>
            </Drawer>
        </div>
    );
  }
}


问:
Assign buses to routes base on their capacity
I am facing problem in assigning buses to routes. I have four buses and four routes with their capacities.

Bus capacity is the number of seats in each bus. Route capacity is number of people on each stop of a route. Route is actually a combination of multiple stops.

An example of a single test case is:

```<code>BUS CAPACITY          ROUTE CAPACITY
BUS 1 44 Seats        Route 1 30 Peoples
BUS 2 63 Seats        Route 2 50 Peoples
BUS 3 14 Seats        Route 3 40 Peoples
BUS 4 17 Seats        Route 4 17 Peoples
</code>```

There is a lot of test cases with multiple combinations for this problem. The numbers of routes and buses are always equal.

I am looking for a algorithm that helps out in solve this problem optimally.

答:
You don't actually say what optimal means here, and that might change what the best solution is, but I would be inclined to sort the routes and buses and then assign the largest bus to the route with the largest number of people waiting, the next largest bus to the route with the next largest number of people waiting, and so on.

There will be unhappy people here if a route is assigned a bus that doesn't have enough seats for the people on the route, but with this assignment all of the buses with more seats are assigned to routes with even more people waiting, so giving a bigger bus would leave at least as many other people without a seat.

For a more sophisticated way of matching people and buses look at https://en.wikipedia.org/wiki/Assignment_problem

An example of how the definition of optimal changes things is if you don't care about the number of people annoyed but about the number of routes where people don't get a seat. In this case if you have routes with 2,3,5,9 people waiting and buses to carry 1,2,4,8 people it might make sense to assign them as 2 people-2 seats, 3 people-4 seats, 5 people-8 seats, 9-people-1 seat which leaves 8 people without a seat instead of 4 but all of those 8 people are on just 1 route.

Body:
I am facing problem in assigning buses to routes. I have four buses and four routes with their capacities.

Bus capacity is the number of seats in each bus. Route capacity is number of people on each stop of a route. Route is actually a combination of multiple stops.

An example of a single test case is:

BUS CAPACITY          ROUTE CAPACITY
BUS 1 44 Seats        Route 1 30 Peoples
BUS 2 63 Seats        Route 2 50 Peoples
BUS 3 14 Seats        Route 3 40 Peoples
BUS 4 17 Seats        Route 4 17 Peoples

There is a lot of test cases with multiple combinations for this problem. The numbers of routes and buses are always equal.

I am looking for a algorithm that helps out in solve this problem optimally.