问:
python scrips reads different unicode strings when run from shell or via CGI
On my Ubuntu server I have a directory that contains these two files:

```<code>testDir# ls -als
insgesamt 12
4 drwxr-xr-x 2 root root 4096 Mai 29 15:12 .
4 drwxr-xr-x 6 root root 4096 Mai 28 18:38 ..
0 -rw-r--r-- 1 root root    0 Mai 28 19:17 Ö.txt
4 -rw-r--r-- 1 root root    9 Mai 28 19:16 Ö.txt
</code>```

The file names look the same, but they are not. The file with size 0 has 1 character before the dot (Unicode code point 214 = Ö), the other file (size = 9) has two characters (code point 79 = O followed by 776 = ¨ which is a combining character and modifies the character before it). To display the unicode code points, I wrote this little script:

```<code>#!/usr/bin/env python3

import os

def printFileList(fileList):
    for file in fileList:
        string = ""
        for char in file:
            string += str(ord(char)) + " "
        string += "<br>"
        print(string)

print("Content-Type: text/html\n")

printFileList(os.listdir("testDir"))

printFileList(["Ö.txt", "Ö.txt"])
</code>```

As you can see, I first read the filenames form the operation system and display the code points of the characters of the file names. Then I do the same, but with strings that are written hard coded in program code.

When I run this program from the shell, I get this result:

```<code>testDir# ./test.py
Content-Type: text/html

79 776 46 116 120 116 <br>
214 46 116 120 116 <br>
79 776 46 116 120 116 <br>
214 46 116 120 116 <br>
</code>```

But this script (to be more precise: a more advanced version of this script) is meant to be run as a CGI script from a webserver. My webserver is Apache 2, and when I call this script from a browser, I get this result:

```<code>79 56524 56456 46 116 120 116
56515 56470 46 116 120 116
79 776 46 116 120 116
214 46 116 120 116
</code>```

The String Content-Type: text/html is part of the http protocol and will not be displayed, and
 appears as line breaks, so these parts aren't visible in a browser for good reasons. But look at the numbers!

What should be 776 is 56524 56456 in the first line, and in the second line 214 became 56515 56470. But this happened only for the filenames read form the operating system. The hard coded strings are correct.

My questions:

1) What causes this strange behavior?

2) What has to be changed, so that the correct code points (776 and 214) are shown?

addendum

I added these lines to my program:

```<code>import sys

print(sys.getfilesystemencoding())
</code>```

The output of this line is:

when run from the shell:

```<code>utf-8
</code>```

which is correct.

when run from apache as CGI-script:

```<code>ascii
</code>```

which is wrong.

So, my new question is:

How can I tell my script, that it always should use utf-8 as file system encoding?

答:
I am answering my own question.

I still don't have an answer to my first question ("What causes this strange behavior?"), so this still is open, and I am really curious about it.

But I have found a workaround to get correct results without really solving the original problem.

Here is a version of my test program that produced the same correct output when run from shell as well as from Apache as CGI script:

```<code>#!/usr/bin/env python3

import os

def printFileList(fileList):
    for file in fileList:
        file = file.decode("utf-8")
        string = ""
        for char in file:
            string += str(ord(char)) + " "
        string += "<br>"
        print(string)

print("Content-Type: text/html\n")

printFileList(os.listdir("testDir".encode("utf-8")))

printFileList(["Ö.txt".encode("utf-8"), "Ö.txt".encode("utf-8")])
</code>```

And here is why it works:

os.listdir produces a list of unicode strings as output if it's input is a unicode string or a file descriptor. But if you feed in a sequence of bytes, the output will also be a list of byte sequences. This is well documented here: https://docs.python.org/3/library/os.html#os.listdir

But there is another difference between these two modes, that is not documented:

If the input is a sequence of bytes, python doesn't care about the encoding of the file system. It always reads the filenames as sequences of bytes and appends those sequences to the list that will be the output.

But if the input is something else (a unicode string or a file descriptor), then it also in a first step reads the bytes, but then uses the encoding that will be displayed when you call sys.getfilesystemencoding() to decode this sequence of bytes. If the byte sequence contains something, that is not conform to this encoding, this "garbage" will be replaced by surrogate characters.

This works well if sys.getfilesystemencoding() produces the correct output. (More precise: This works well if python did guess the file system encoding correctly. sys.getfilesystemencoding() doesn't make this guess, it only displays the result from this guess.) But for a reason I'm still curious about, this guess is wrong if the script is run by Apache as a CGI script. In the setting described here, the real file system encoding is utf-8 but python believes it was ascii if it was started from Apache. And so it produced an incorrect output.

The solution is to use os.listdir in that mode where it doesn't perform any encodings and conversions. And this means: bytes in, bytes out.

To do this, you have to replace

```<code>os.listdir("testDir")
</code>```

by

```<code>os.listdir("testDir".encode("utf-8"))
</code>```

Now os.listdir will work in byte mode, and its output will also be a list of byte sequences. To use them as unicode strings, you just need to decode the byte sequences with this line:

```<code>file = file.decode("utf-8")
</code>```

(The encoding in the last line of my little program ("Ö.txt".encode("utf-8")) was only necessary because my function printFileList now no longer was able to process lists of unicode string, but only lists of byte sequences.)

But be careful: This is not a solution of the problem. This is only a workaround. If you implement it as described here, it only will work if the actual file system encoding really is utf-8.

I think that the routine within python, that tries to guess the file system encoding, has a bug. It doesn't work properly and makes a wrong guess when python is started form Apache. A real solution would be to fix this bug.

Another possibility is, that there is some wrong setting of Apache 2 that makes Python believe to work on an ascii based file system. Maybe you just need to find this setting and correct it, but I have no idea if a) there is really such an Apache setting, and b) if so, which parameter needs to be set to which value.

Body:
On my Ubuntu server I have a directory that contains these two files:

testDir# ls -als
insgesamt 12
4 drwxr-xr-x 2 root root 4096 Mai 29 15:12 .
4 drwxr-xr-x 6 root root 4096 Mai 28 18:38 ..
0 -rw-r--r-- 1 root root    0 Mai 28 19:17 Ö.txt
4 -rw-r--r-- 1 root root    9 Mai 28 19:16 Ö.txt

The file names look the same, but they are not. The file with size 0 has 1 character before the dot (Unicode code point 214 = Ö), the other file (size = 9) has two characters (code point 79 = O followed by 776 = ¨ which is a combining character and modifies the character before it). To display the unicode code points, I wrote this little script:

#!/usr/bin/env python3

import os

def printFileList(fileList):
    for file in fileList:
        string = ""
        for char in file:
            string += str(ord(char)) + " "
        string += "
"
        print(string)

print("Content-Type: text/html\n")

printFileList(os.listdir("testDir"))

printFileList(["Ö.txt", "Ö.txt"])

As you can see, I first read the filenames form the operation system and display the code points of the characters of the file names. Then I do the same, but with strings that are written hard coded in program code.

When I run this program from the shell, I get this result:

testDir# ./test.py
Content-Type: text/html

79 776 46 116 120 116

214 46 116 120 116

79 776 46 116 120 116

214 46 116 120 116

But this script (to be more precise: a more advanced version of this script) is meant to be run as a CGI script from a webserver. My webserver is Apache 2, and when I call this script from a browser, I get this result:

79 56524 56456 46 116 120 116
56515 56470 46 116 120 116
79 776 46 116 120 116
214 46 116 120 116

The String Content-Type: text/html is part of the http protocol and will not be displayed, and
 appears as line breaks, so these parts aren't visible in a browser for good reasons. But look at the numbers!

What should be 776 is 56524 56456 in the first line, and in the second line 214 became 56515 56470. But this happened only for the filenames read form the operating system. The hard coded strings are correct.

My questions:

1) What causes this strange behavior?

2) What has to be changed, so that the correct code points (776 and 214) are shown?

addendum

I added these lines to my program:

import sys

print(sys.getfilesystemencoding())

The output of this line is:

when run from the shell:

utf-8

which is correct.

when run from apache as CGI-script:

ascii

which is wrong.

So, my new question is:

How can I tell my script, that it always should use utf-8 as file system encoding?

Body:
I am answering my own question.

I still don't have an answer to my first question ("What causes this strange behavior?"), so this still is open, and I am really curious about it.

But I have found a workaround to get correct results without really solving the original problem.

Here is a version of my test program that produced the same correct output when run from shell as well as from Apache as CGI script:

#!/usr/bin/env python3

import os

def printFileList(fileList):
    for file in fileList:
        file = file.decode("utf-8")
        string = ""
        for char in file:
            string += str(ord(char)) + " "
        string += "<br>"
        print(string)

print("Content-Type: text/html\n")

printFileList(os.listdir("testDir".encode("utf-8")))

printFileList(["Ö.txt".encode("utf-8"), "Ö.txt".encode("utf-8")])

And here is why it works:

os.listdir produces a list of unicode strings as output if it's input is a unicode string or a file descriptor. But if you feed in a sequence of bytes, the output will also be a list of byte sequences. This is well documented here: https://docs.python.org/3/library/os.html#os.listdir

But there is another difference between these two modes, that is not documented:

If the input is a sequence of bytes, python doesn't care about the encoding of the file system. It always reads the filenames as sequences of bytes and appends those sequences to the list that will be the output.

But if the input is something else (a unicode string or a file descriptor), then it also in a first step reads the bytes, but then uses the encoding that will be displayed when you call sys.getfilesystemencoding() to decode this sequence of bytes. If the byte sequence contains something, that is not conform to this encoding, this "garbage" will be replaced by surrogate characters.

This works well if sys.getfilesystemencoding() produces the correct output. (More precise: This works well if python did guess the file system encoding correctly. sys.getfilesystemencoding() doesn't make this guess, it only displays the result from this guess.) But for a reason I'm still curious about, this guess is wrong if the script is run by Apache as a CGI script. In the setting described here, the real file system encoding is utf-8 but python believes it was ascii if it was started from Apache. And so it produced an incorrect output.

The solution is to use os.listdir in that mode where it doesn't perform any encodings and conversions. And this means: bytes in, bytes out.

To do this, you have to replace

os.listdir("testDir")

by

os.listdir("testDir".encode("utf-8"))

Now os.listdir will work in byte mode, and its output will also be a list of byte sequences. To use them as unicode strings, you just need to decode the byte sequences with this line:

file = file.decode("utf-8")

(The encoding in the last line of my little program ("Ö.txt".encode("utf-8")) was only necessary because my function printFileList now no longer was able to process lists of unicode string, but only lists of byte sequences.)

But be careful: This is not a solution of the problem. This is only a workaround. If you implement it as described here, it only will work if the actual file system encoding really is utf-8.

I think that the routine within python, that tries to guess the file system encoding, has a bug. It doesn't work properly and makes a wrong guess when python is started form Apache. A real solution would be to fix this bug.

Another possibility is, that there is some wrong setting of Apache 2 that makes Python believe to work on an ascii based file system. Maybe you just need to find this setting and correct it, but I have no idea if a) there is really such an Apache setting, and b) if so, which parameter needs to be set to which value.


来源: stackexchange

问:
How to store result of simple python calculator in variable
I am a beginner to Python and have just started learning recently.

After learning about if, elif and else statements I decided to try and make a simple calculator.

Now, a few hours later I was wondering how I could improve it and make it more complex.

I am trying to store the result of the addition, subtraction, divison or multiplication of the first two numbers in a variable. After doing this I want to Re-create the calculator only I already have the first number.

I am also running into problems with my continue1 if statement, for some reason even if the user inputs "no" the script continues instead of displaying a message.

I'd really appreciate any help at all, Thank you!

Python code:

```<code>num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")

if operator == "/":
    print(num1 / num2)
elif operator == "+":
    print(num1 + num2)
elif operator == "-":
    print(num1 - num2)
elif operator == "*":
    print(num1 * num2)
else:
    print("FATAL ERROR")

num3 = num1 / num2
num3 = num1 - num2
num3 = num1 + num2
num3 = num1 * num2

continue1 =  input ("Would you like too continue? [Yes/No]")

if continue1 == "yes" or "Yes":
    operator1 = num4 = float(input("Please enter second number: "))
else:
    print("Fatal error")

input("please enter operator")

if operator == "/":
    print(num3 / num4)
elif operator == "+":
    print(num3 + num4)
elif operator == "-":
    print(num3 - num4)
elif operator == "*":
    print(num3 * num4)
else:
    print("Please press enter to close.")

input("Press Enter to Exit")
</code>```

答:
In the first part, just assign to a variable (and then print it if you want):

```<code>if operator == "/":
    num3 = num1 / num2
elif operator == "+":
    num3 = num1 + num2
elif operator == "-":
    num3 = num1 - num2
elif operator == "*":
    num3 = num1 * num2
else:
    print("FATAL ERROR")

print(num3)
</code>```

Regarding the second part of your question, in your statement:

```<code>if continue1 == "yes" or "Yes":
</code>```

this is wrong because or is an operator which will combine the two things on either side of it (typically used where each of these two things is something that evaluates to True or False), so you could have for example:

```<code>if continue1 == "yes" or continue1 == "Yes":
</code>```

You can also add brackets to control the order of execution, as shown below.  In this case they do not affect the result, because it is already the case that the == operators are evaluated before the or, but they may make it clearer to read.

```<code>if (continue1 == "yes") or (continue1 == "Yes"):
</code>```

You can also do this instead:

```<code>if continue1 in ("yes", "Yes"):
</code>```

The details of what is going wrong with your original form of the conditional statement are perhaps not important at this stage, but I mention them for sake of completeness. If you enter "No" then the whole expression will actually evaluate to "Yes" (the continue1 == "yes" evaluates to False, and then False or "Yes" evalues to "Yes"). The if statement then treats the value "Yes" (a non-empty string) as a true value and so executes the code which depends on the condition.

ContentLicense: CC BY-SA 4.0

Body:
I am a beginner to Python and have just started learning recently.

After learning about if, elif and else statements I decided to try and make a simple calculator.

Now, a few hours later I was wondering how I could improve it and make it more complex.

I am trying to store the result of the addition, subtraction, divison or multiplication of the first two numbers in a variable. After doing this I want to Re-create the calculator only I already have the first number.

I am also running into problems with my continue1 if statement, for some reason even if the user inputs "no" the script continues instead of displaying a message.

I'd really appreciate any help at all, Thank you!

Python code:

num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")

if operator == "/":
    print(num1 / num2)
elif operator == "+":
    print(num1 + num2)
elif operator == "-":
    print(num1 - num2)
elif operator == "*":
    print(num1 * num2)
else:
    print("FATAL ERROR")

num3 = num1 / num2
num3 = num1 - num2
num3 = num1 + num2
num3 = num1 * num2

continue1 =  input ("Would you like too continue? [Yes/No]")

if continue1 == "yes" or "Yes":
    operator1 = num4 = float(input("Please enter second number: "))
else:
    print("Fatal error")

input("please enter operator")

if operator == "/":
    print(num3 / num4)
elif operator == "+":
    print(num3 + num4)
elif operator == "-":
    print(num3 - num4)
elif operator == "*":
    print(num3 * num4)
else:
    print("Please press enter to close.")

input("Press Enter to Exit")

Body:
In the first part, just assign to a variable (and then print it if you want):

if operator == "/":
    num3 = num1 / num2
elif operator == "+":
    num3 = num1 + num2
elif operator == "-":
    num3 = num1 - num2
elif operator == "*":
    num3 = num1 * num2
else:
    print("FATAL ERROR")

print(num3)

Regarding the second part of your question, in your statement:

if continue1 == "yes" or "Yes":

this is wrong because or is an operator which will combine the two things on either side of it (typically used where each of these two things is something that evaluates to True or False), so you could have for example:

if continue1 == "yes" or continue1 == "Yes":

You can also add brackets to control the order of execution, as shown below.  In this case they do not affect the result, because it is already the case that the == operators are evaluated before the or, but they may make it clearer to read.

if (continue1 == "yes") or (continue1 == "Yes"):

You can also do this instead:

if continue1 in ("yes", "Yes"):

The details of what is going wrong with your original form of the conditional statement are perhaps not important at this stage, but I mention them for sake of completeness. If you enter "No" then the whole expression will actually evaluate to "Yes" (the continue1 == "yes" evaluates to False, and then False or "Yes" evalues to "Yes"). The if statement then treats the value "Yes" (a non-empty string) as a true value and so executes the code which depends on the condition.


问:
Delete directories recursively in Java
Is there a way to delete entire directories recursively in Java?

In the normal case it is possible to delete an empty directory.
However when it comes to deleting entire directories with contents, it is not that simple anymore.

How do you delete entire directories with contents in Java?

答:
Guava provides a one-liner: MoreFiles.deleteRecursively().

Unlike many of the examples shared, it accounts for symbolic links and will not (by default) delete files outside the provided path.

ContentLicense: CC BY-SA 3.0

Title: Delete directories recursively in Java


问:
No available video device' when compiling with CMake
I can compile my code using Makefile and it works fine. When I try to run same code compiled with Cmake SDL_GetError() says:

'No available video device'

I think something wrong with my CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.10)

set(CMAKE_C_STANDARD  90)
set(CMAKE_C_STANDARD_REQUIRED True)

project(RTv1)

set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)

set(SOURCES ...)

find_package(SDL2 REQUIRED)

add_executable(${PROJECT_NAME} ${SOURCES})

get_filename_component(SDL2_INCLUDE_DIR_PARENT ${SDL2_INCLUDE_DIR} DIRECTORY)

target_include_directories(${PROJECT_NAME}
        PUBLIC
        ${SDL2_INCLUDE_DIR}
        )

target_include_directories(${PROJECT_NAME}
        PUBLIC
        ${SDL2_INCLUDE_DIR_PARENT}
        )

target_include_directories(${PROJECT_NAME}
        PUBLIC
        ${PROJECT_SOURCE_DIR}/include
        )

target_link_libraries(${PROJECT_NAME} ${SDL2_LIBRARY})
</code>```

Running Linux Mint 19.1 Tessa, self-built SDL2 in project's libsdl/ folder, findSDL works fine, compilation successfull, Clion 2019.3.3

答:
I had some uninstalled dependencies, this helped:</p>

```<code>sudo apt-get install build-essential mercurial make cmake autoconf automake \
libtool libasound2-dev libpulse-dev libaudio-dev libx11-dev libxext-dev \
libxrandr-dev libxcursor-dev libxi-dev libxinerama-dev libxxf86vm-dev \
libxss-dev libgl1-mesa-dev libdbus-1-dev libudev-dev libgles2-mesa-dev \
libegl1-mesa-dev libibus-1.0-dev fcitx-libs-dev libsamplerate0-dev \
libsndio-dev libwayland-dev libxkbcommon-dev
</code>```

Body:
I can compile my code using Makefile and it works fine. When I try to run same code compiled with Cmake SDL_GetError() says:

'No available video device'

I think something wrong with my CMakeLists.txt:

cmake_minimum_required(VERSION 3.10)

set(CMAKE_C_STANDARD  90)
set(CMAKE_C_STANDARD_REQUIRED True)

project(RTv1)

set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)

set(SOURCES ...)

find_package(SDL2 REQUIRED)

add_executable(${PROJECT_NAME} ${SOURCES})

get_filename_component(SDL2_INCLUDE_DIR_PARENT ${SDL2_INCLUDE_DIR} DIRECTORY)

target_include_directories(${PROJECT_NAME}
        PUBLIC
        ${SDL2_INCLUDE_DIR}
        )

target_include_directories(${PROJECT_NAME}
        PUBLIC
        ${SDL2_INCLUDE_DIR_PARENT}
        )

target_include_directories(${PROJECT_NAME}
        PUBLIC
        ${PROJECT_SOURCE_DIR}/include
        )

target_link_libraries(${PROJECT_NAME} ${SDL2_LIBRARY})

Running Linux Mint 19.1 Tessa, self-built SDL2 in project's libsdl/ folder, findSDL works fine, compilation successfull, Clion 2019.3.3

Body:
I had some uninstalled dependencies, this helped:

sudo apt-get install build-essential mercurial make cmake autoconf automake \
libtool libasound2-dev libpulse-dev libaudio-dev libx11-dev libxext-dev \
libxrandr-dev libxcursor-dev libxi-dev libxinerama-dev libxxf86vm-dev \
libxss-dev libgl1-mesa-dev libdbus-1-dev libudev-dev libgles2-mesa-dev \
libegl1-mesa-dev libibus-1.0-dev fcitx-libs-dev libsamplerate0-dev \
libsndio-dev libwayland-dev libxkbcommon-dev


问:
Is it possible to populate a spinner in android using a JSONArray?
Just as the title says.. Is it possible to do this?  Say I have a JSON array of something like this</p>

```<code>{
    "locations": [
      {
        "id": 1,
        "loc": "miami"
      },
      {
        "id": 2,
        "loc": "manhattan"
      },
      {
        "id": 3,
        "loc": "lasVegas"
      }
    ]
  }
</code>```

答: you can convert the json to a java object. and bind the data.</p>

Body:
Just as the title says.. Is it possible to do this?  Say I have a JSON array of something like this

{
    "locations": [
      {
        "id": 1,
        "loc": "miami"
      },
      {
        "id": 2,
        "loc": "manhattan"
      },
      {
        "id": 3,
        "loc": "lasVegas"
      }
    ]
  }


问:
is there a way to read multiple excel tab/sheets from single xlsx to multiple dataframes with each dataframe named with sheet name?
I am not good in python please forgive me for this question but I need to create a function which does the following thing:

Create multiple data frames from multiple excel tab/sheet present in a single xlsx file and be named on the sheet name.

The columns' values should be concatenated and checked if there is no duplicate value.

if the concat value has a duplicate then it should be told as yes/No in another column.

all the dataframes then should be written into a single workbook as different worksheets inside.
values inside () are columns for better understanding

example:

sheet1

```<code>(a) (b) (c) (d)
a1  b1  c1  d1
a2  b2  c2  d2
</code>```

result:

```<code>(c) (d) (concate) (is duplicate)
c1  d1  c1_d1     no
c2  d2  c2_d2     no
</code>```

sheet2

```<code>(a) (b) (e) (f)
a3  b3  e1  f1
a4  b4  e1  f1
a5  b5  e2  f2
a6  b6  e4  f4
a7  a8  e4  f5
</code>```

result:

```<code>(e) (f) (concat) (has duplicate)
e1 f1 e1_f1 yes
e2 f2 e2_f2 no
e4 f4 e4_f4 no
e4 f5 e4_f5 no
</code>```

答:
Here you go:

import pandas as pd
from pandas import ExcelWriter

def detect_duplicate(group):
    group['is_duplicate'] = ['No'] + ['Yes'] * (len(group) - 1)
    return group

with ExcelWriter('output.xlsx') as output:
    for sheet_name, df in pd.read_excel('input.xlsx', sheet_name=None).items():
        df = df.drop(['a', 'b'], axis=1)
        df['concat'] = df.apply(lambda row: '_'.join(row), axis=1)
        df = df.groupby(['concat']).apply(detect_duplicate)
        df = df.drop_duplicates(keep='last', subset=['concat'])
        df.to_excel(output, sheet_name=sheet_name, index=False)
```

Check output.xlsx for the output.

Body:
I am not good in python please forgive me for this question but I need to create a function which does the following thing:

Create multiple data frames from multiple excel tab/sheet present in a single xlsx file and be named on the sheet name.

The columns' values should be concatenated and checked if there is no duplicate value.

if the concat value has a duplicate then it should be told as yes/No in another column.

all the dataframes then should be written into a single workbook as different worksheets inside.
values inside () are columns for better understanding

example:

sheet1

(a) (b) (c) (d)
a1  b1  c1  d1
a2  b2  c2  d2

result:

(c) (d) (concate) (is duplicate)
c1  d1  c1_d1     no
c2  d2  c2_d2     no

sheet2

(a) (b) (e) (f)
a3  b3  e1  f1
a4  b4  e1  f1
a5  b5  e2  f2
a6  b6  e4  f4
a7  a8  e4  f5

result:

(e) (f) (concat) (has duplicate)
e1 f1 e1_f1 yes
e2 f2 e2_f2 no
e4 f4 e4_f4 no
e4 f5 e4_f5 no

Body:
Here you go:

import pandas as pd
from pandas import ExcelWriter

def detect_duplicate(group):
    group['is_duplicate'] = ['No'] + ['Yes'] * (len(group) - 1)
    return group

with ExcelWriter('output.xlsx') as output:
    for sheet_name, df in pd.read_excel('input.xlsx', sheet_name=None).items():
        df = df.drop(['a', 'b'], axis=1)
        df['concat'] = df.apply(lambda row: '_'.join(row), axis=1)
        df = df.groupby(['concat']).apply(detect_duplicate)
        df = df.drop_duplicates(keep='last', subset=['concat'])
        df.to_excel(output, sheet_name=sheet_name, index=False)

Check output.xlsx for the output.


问:
Project explorer no longer is grouped
For Some reason.. the project Explorer seems to have grouped up..

Is this is any way I can display sheets, forms, modules, class Module..

Kindly help..

Sam

答:
Sorry I got it..

Just had to click on toggle folders

Title: Project explorer no longer is grouped


问:
Predicting Cellular Automata
I am attempting to complete an assignment for an AI course however I cannot understand a question. Unfortunately, I cannot find any information on the internet that clearly explains how to predict the next generation in a CA. I have posted a link to a screenshot of my question below.

Image

Edit:

This is my edited answer;

Edited Answer

答:
In Margolus neighborhoods, the grid is divided into 2x2 blocks. Depending on which step you are in, the division of blocks either starts from the top-left corner or is offset one cell down and one cell to the right. (See Wikipedia on Block cellular automata.) Your instructions say to start from the top-left corner.

So you need to divide up the grid into 2x2 blocks. Then, you check how the patterns in each block match the 15 possible Margolus neighborhood configurations:

For the given grid, you end up with the following. The "neighborhoods" are labeled in yellow highlighted text:

Now you look at the rules you were given: MS, D 0; 14; 11; 5; etc. These numbers after the D tell you, in order, how each configuration should change.

0th number in rule (D 0): Counting from 0, the first number tells you how the 0 (empty) configuration should change. The given number is 0, which means empty 2x2 blocks will not change in the next generation.

1st number in rule (D 0; 14;): The next number tells you how the 1 configuration (one X in upper left corner) should change. That number is 14, which means if we have any 2x2 blocks with the 1 configuration, it should morph into the 14 block. We don't have any 1 configurations, so we go to the next number in the rule.

2nd number in rule (D 0; 14; 11;): The next number tells you how the 2 configuration should change, and that number is 11. We have 2 blocks with the 2 configuration (one X in upper right corner), and the rule tells us we need to convert them to configuration 11 (2x2 block filled with X's except lower left corner).

After evaluating these first 3 rules, you end up with:

Continue for the rest of the numbers in the rule and you will have your answer. As for whether the rule is reversible, see here.

Title: Predicting Cellular Automata


问:
get mysql data where column has 2 values
I have the following mysql query:

```<code>SELECT * FROM `notifications`
WHERE `receiverUserID` = 3 AND `status` = 0 AND `typ` = 1 OR `typ` = 2
</code>```

the result:

But my query is not correct.
The result should show me only data where typ = 1 OR 2, status = 0 and the receiverUserID = 3

the row where receiverUserID = 2 should not be shown.
Where is my mistake ?

答:
Here is what your query was actually doing:

```<code>SELECT * FROM
notifications
WHERE (receiverUserID = 3 AND status = 0 AND typ = 1) OR typ = 2;
</code>```

This is due to that AND takes greater precedence than OR.  This explains why all those typ = 2 records appear in your result set.
You need to use parentheses to enforce the and/or logic you have in mind:

```<code>SELECT * FROM
notifications
WHERE receiverUserID = 3 AND status = 0 AND (typ = 1 OR typ = 2);
</code>```

Note that had used WHERE IN (...) syntax this would have been a moot point:

```<code>SELECT * FROM
notifications
WHERE receiverUserID = 3 AND status = 0 AND typ IN (1, 2);
</code>```

Body:
I have the following mysql query:

SELECT * FROM `notifications`
WHERE `receiverUserID` = 3 AND `status` = 0 AND `typ` = 1 OR `typ` = 2

the result:

But my query is not correct.
The result should show me only data where typ = 1 OR 2, status = 0 and the receiverUserID = 3

the row where receiverUserID = 2 should not be shown.
Where is my mistake ?

Body:
Here is what your query was actually doing:

SELECT * FROM
notifications
WHERE (receiverUserID = 3 AND status = 0 AND typ = 1) OR typ = 2;

This is due to that AND takes greater precedence than OR.  This explains why all those typ = 2 records appear in your result set.
You need to use parentheses to enforce the and/or logic you have in mind:

SELECT * FROM
notifications
WHERE receiverUserID = 3 AND status = 0 AND (typ = 1 OR typ = 2);

Note that had used WHERE IN (...) syntax this would have been a moot point:

SELECT * FROM
notifications
WHERE receiverUserID = 3 AND status = 0 AND typ IN (1, 2);


答:
You need to shorten down the scope of OR operator by using parenthesis. So your query should be

```<code>SELECT * FROM notifications
WHERE receiverUserID = 3 AND status = 0 AND (typ = 1 OR typ = 2 );
</code>```

Edit 1 (Helpful comment by @jBuchholz)

Here is a list of operator precedences in MySQL dev.mysql.com/doc/refman/8.0/en/operator-precedence.html AND has higher precedence than OR and is therefore executed earlier (like multiplication is executed before addition).

Title: get mysql data where column has 2 values

Body:
You need to shorten down the scope of OR operator by using parenthesis. So your query should be

SELECT * FROM notifications
WHERE receiverUserID = 3 AND status = 0 AND (typ = 1 OR typ = 2 );

Edit 1 (Helpful comment by @jBuchholz)

Here is a list of operator precedences in MySQL dev.mysql.com/doc/refman/8.0/en/operator-precedence.html AND has higher precedence than OR and is therefore executed earlier (like multiplication is executed before addition).


问:
jQuery Ajax Request without loading results
Hey all, i'm really new to ajax and all i want to do is call an ajax function that doesn't return anything. I've used

$('#myDiv').load('/ajaxScript.asp');

and that loads the results to myDiv just fine. I just want to run the ajax without returning anything at all. Just run my code. How do i do this? Also, how do i detect when it is done doing it's thing? Thanks all!

答:
You can use $.ajax instead of load; which is basically an alias of $(receiver).load();

Documentation here: http://api.jquery.com/jQuery.ajax/

Demo code here:

```<code>$.ajax({
  url: '/path/to/file',
  type: 'POST',
  dataType: 'xml/html/script/json/jsonp',
  data: {param1: 'value1'},
  complete: function(xhr, textStatus) {
    //called when complete
  },
  success: function(data, textStatus, xhr) {
    //called when successful
  },
  error: function(xhr, textStatus, errorThrown) {
    //called when there is an error
  }
});
</code>```

Body:
You can use $.ajax instead of load; which is basically an alias of $(receiver).load();

Documentation here: http://api.jquery.com/jQuery.ajax/

Demo code here:

$.ajax({
  url: '/path/to/file',
  type: 'POST',
  dataType: 'xml/html/script/json/jsonp',
  data: {param1: 'value1'},
  complete: function(xhr, textStatus) {
    //called when complete
  },
  success: function(data, textStatus, xhr) {
    //called when successful
  },
  error: function(xhr, textStatus, errorThrown) {
    //called when there is an error
  }
});


问:
Contain snippet of word in array (Python)
I don't know where to start asking but here's some rough code what am I going to do

```<code>arr = ['cat', 'dog']
if('housecat' not in arr):
        return TRUE
else return FALSE
</code>```

What I want is: it return as TRUE because 'cat' was in the array while 'housecat' contain 'cat'.

==Edit==

I've tried code suggested

```<code>arr = ['cat', 'dog']
for i in arr:
        if(i not in 'housecat'):
                return TRUE
        else return FALSE
</code>```

It return as TRUE as intended, but if there's symbol in the input (e.g: house-cat, cat.I (Only tested with those 2 symbol because input is automated)) it'll return as FALSE which should be TRUE (because there's 'cat' in house-'cat').

Edit 3: Should be return as TRUE not FALSE, my bad, edited the whole writing.

Edit 4: Case closed, bug appeared when I run the whole code and it has nothing to do with this case.

答:
try this.</p>

```<code>arr = ['cat', 'dog']
    for i in arr:
        if (i in 'housecat'):
            return false
    return true
</code>```

Body:
I don't know where to start asking but here's some rough code what am I going to do

arr = ['cat', 'dog']
if('housecat' not in arr):
        return TRUE
else return FALSE

What I want is: it return as TRUE because 'cat' was in the array while 'housecat' contain 'cat'.

==Edit==

I've tried code suggested

arr = ['cat', 'dog']
for i in arr:
        if(i not in 'housecat'):
                return TRUE
        else return FALSE

It return as TRUE as intended, but if there's symbol in the input (e.g: house-cat, cat.I (Only tested with those 2 symbol because input is automated)) it'll return as FALSE which should be TRUE (because there's 'cat' in house-'cat').

Edit 3: Should be return as TRUE not FALSE, my bad, edited the whole writing.

Edit 4: Case closed, bug appeared when I run the whole code and it has nothing to do with this case.

Body:
try this.

arr = ['cat', 'dog']
    for i in arr:
        if (i in 'housecat'):
            return false
    return true


问:
why doesn't my javascript function display my message?
So i connected a javascript file to my html file. When a button is clicked, it's supposed to display a message but for some reason it doesn't display anything. What am i doing wrong?
(p.s. i know very little about js)

function calc() {
  greeting = "hello"
  var usname = document.getElementById("name").innerHTML = greeting;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <p> BMI Calculator</p>
</header>
<div class="grid">
  <div class=input>
    <form>
      <p> Fill in the form below</p>
      Name: <br>
      <input type="text" name="name" id="name"><br> Weight: <br>
      <input type="number" name="weight"><br> Height: <br>
      <input type="number" name="height"><br>
      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <input type="radio" name="gender" value="other">Other<br>
      <br><input type="button" onclick="calc()" name="calculate" value="calculate">
    </form>
  </div>
  <div class="result">
    <p> Your Results</p>
  </div>
</div></code>```

答:
you're using a wrong property.
if you had a div like

 then the document.getElementById("name").innerHTML = "abc"; would turn it into
abc
. In your case you want to set the value of the input field, rather than populate more child components.

you can do that with document.getElementById("name").value = greeting

Body:
So i connected a javascript file to my html file. When a button is clicked, it's supposed to display a message but for some reason it doesn't display anything. What am i doing wrong?
(p.s. i know very little about js)

function calc() {
  greeting = "hello"
  var usname = document.getElementById("name").innerHTML = greeting;
}

 BMI Calculator

    <form>

 Fill in the form below

      Name:

      <input type="text" name="name" id="name">
 Weight:

      <input type="number" name="weight">
 Height:

      <input type="number" name="height">

      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <input type="radio" name="gender" value="other">Other

<input type="button" onclick="calc()" name="calculate" value="calculate">
    </form>

 Your Results

Body:
you're using a wrong property.
if you had a div like <div id="name"></div> then the document.getElementById("name").innerHTML = "abc"; would turn it into <div id="name">abc</div>. In your case you want to set the value of the input field, rather than populate more child components.

you can do that with document.getElementById("name").value = greeting


问:
mount directory to container won't work with podman
As I have fedora I tried to run the nginx example from their tutorial, i don't get nginx to show any content.

When i run the this container:

```<code>podman run --name mynginx1 -p 8080:80 -d nginx
</code>```

I get the Welcome to nginx! page.

But when i try to run the example with a directory mounted:

```<code>podman run --name mynginx2 \
  --mount type=bind,source=/home/simon/Dokumente/podman/nginx/content,target=/usr/share/nginx/html \
  -p 9080:80 -d nginx
</code>```

I also get the Welcome to nginx! page, but I have an index.html file in that source directory.

What is the problem with that container?

答:
When we bind volume it loses permission to the path /usr/share/nginx/html. It happens because of SELinux enforcement.

mynginx1

```<code>root@f3fb6ece7eba:/usr/share/nginx/html# ls
50x.html  index.html
</code>```

mynginx2

```<code>root@af0803674402:/usr/share/nginx/html# ls
ls: cannot open directory '.': Permission denied
</code>```

Check the SELinux policy of the host which runs podman.

```<code>$ getenforce
Enforcing
</code>```

If it is in Enforcing mode change it to Permissive.

```<code>$ sudo setenforce 0
$ getenforce
Permissive
</code>```

Re-run the mynginx2 container, exec and access the contents of /usr/share/nginx/html

```<code>$ podman run --name mynginx2 --mount type=bind,source=/home/tc/q2,target=/usr/share/nginx/html -p 9080:80 -d nginx
7ff2bdfb7ccfc6f90a9bd7957b08e48ea72d7c2303d47d11a412c6c8601976b6
$ podman exec -it mynginx2 bash
root@7ff2bdfb7ccf:/# cd /usr/share/nginx/html/
root@7ff2bdfb7ccf:/usr/share/nginx/html# ls
index.html

$ curl -I -s 127.0.0.1:8080
HTTP/1.1 200 OK

$ curl -I 127.0.0.1:9080
HTTP/1.1 200 OK
</code>```

Body:
As I have fedora I tried to run the nginx example from their tutorial, i don't get nginx to show any content.

When i run the this container:

podman run --name mynginx1 -p 8080:80 -d nginx

I get the Welcome to nginx! page.

But when i try to run the example with a directory mounted:

podman run --name mynginx2 \
  --mount type=bind,source=/home/simon/Dokumente/podman/nginx/content,target=/usr/share/nginx/html \
  -p 9080:80 -d nginx

I also get the Welcome to nginx! page, but I have an index.html file in that source directory.

What is the problem with that container?

Body:
When we bind volume it loses permission to the path /usr/share/nginx/html. It happens because of SELinux enforcement.

mynginx1

root@f3fb6ece7eba:/usr/share/nginx/html# ls
50x.html  index.html

mynginx2

root@af0803674402:/usr/share/nginx/html# ls
ls: cannot open directory '.': Permission denied

Check the SELinux policy of the host which runs podman.

$ getenforce
Enforcing

If it is in Enforcing mode change it to Permissive.

$ sudo setenforce 0
$ getenforce
Permissive

Re-run the mynginx2 container, exec and access the contents of /usr/share/nginx/html

$ podman run --name mynginx2 --mount type=bind,source=/home/tc/q2,target=/usr/share/nginx/html -p 9080:80 -d nginx
7ff2bdfb7ccfc6f90a9bd7957b08e48ea72d7c2303d47d11a412c6c8601976b6
$ podman exec -it mynginx2 bash
root@7ff2bdfb7ccf:/# cd /usr/share/nginx/html/
root@7ff2bdfb7ccf:/usr/share/nginx/html# ls
index.html

$ curl -I -s 127.0.0.1:8080
HTTP/1.1 200 OK

$ curl -I 127.0.0.1:9080
HTTP/1.1 200 OK


问:
Firebase push notification on new chat message
I have created an app where I have chat in it.

I would like that the users will receive a notification that they got a new message whenever they are outside of the app.

In order to do so, I'm using Firebase service.

Now, whenever a message is sent, I call this method:
I have created the following MyFirebaseMessagingService class to test when it is called:

```<code>private class MyTask extends AsyncTask<MyTaskParams, Void, Void> {
    @Override
    protected Void doInBackground(MyTaskParams... params) {
        String userDeviceIdKey = params[0].url;
        String title = params[0].title;
        String body = params[0].body;

        String authKey = "XXXXX";   // You FCM AUTH key
        String FMCurl = "https://fcm.googleapis.com/fcm/send";
        URL url;
        try {
            url = new URL(FMCurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization","key="+authKey);
            conn.setRequestProperty("Content-Type","application/json");

            JSONObject json = new JSONObject();
            json.put("to",userDeviceIdKey);
            json.put("priority","high");
            JSONObject info = new JSONObject();
            info.put("title", title);   // Notification title
            info.put("body", body); // Notification body
            info.put("var1", chatID);
            info.put("var2",receiverID);
            info.put("var3",itemID);
            json.put("data", info);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(json.toString());
            wr.flush();
            Log.w("", "getInstanceId failed" + json);

            conn.getInputStream();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
}
</code>```

and In my Service I created:

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d("TESTING_MESSAGE", "" + remoteMessage);

    }

}
</code>```

However, It seems like I never get this Log when I send a message and it doesnt look like onMessageReceived is ever called.

Is there any reason?

My next goal is to make notification inside onMessageReceived but I want to make sure first that I get there.

My manifest is:

```<code><service
    android:name=".service.MyFirebaseMessagingService"
    android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
</service>
</code>```

答:
I make a demo app with your code, and it works well and I can see that onMessageReceived function is trigged when a message arrives.

I use the firebase-messaging version 20.1.7

```<code>implementation 'com.google.firebase:firebase-messaging:20.1.7'
</code>```

so I think you should do the following checking:

check if your app is in the foreground. because you can't trigger onMessageReceived when the app is in the background. refer: https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages

check if you wrote the right device token(your field 'userDeviceIdKey') when you sent the http request.

check if your http request has some error in catch.

hope can help you.

Body:
I have created an app where I have chat in it.

I would like that the users will receive a notification that they got a new message whenever they are outside of the app.

In order to do so, I'm using Firebase service.

Now, whenever a message is sent, I call this method:
I have created the following MyFirebaseMessagingService class to test when it is called:

private class MyTask extends AsyncTask<MyTaskParams, Void, Void> {
    @Override
    protected Void doInBackground(MyTaskParams... params) {
        String userDeviceIdKey = params[0].url;
        String title = params[0].title;
        String body = params[0].body;

        String authKey = "XXXXX";   // You FCM AUTH key
        String FMCurl = "https://fcm.googleapis.com/fcm/send";
        URL url;
        try {
            url = new URL(FMCurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization","key="+authKey);
            conn.setRequestProperty("Content-Type","application/json");

            JSONObject json = new JSONObject();
            json.put("to",userDeviceIdKey);
            json.put("priority","high");
            JSONObject info = new JSONObject();
            info.put("title", title);   // Notification title
            info.put("body", body); // Notification body
            info.put("var1", chatID);
            info.put("var2",receiverID);
            info.put("var3",itemID);
            json.put("data", info);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(json.toString());
            wr.flush();
            Log.w("", "getInstanceId failed" + json);

            conn.getInputStream();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
}

and In my Service I created:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d("TESTING_MESSAGE", "" + remoteMessage);

    }

}

However, It seems like I never get this Log when I send a message and it doesnt look like onMessageReceived is ever called.

Is there any reason?

My next goal is to make notification inside onMessageReceived but I want to make sure first that I get there.

My manifest is:

<service
    android:name=".service.MyFirebaseMessagingService"
    android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
</service>

Body:
I make a demo app with your code, and it works well and I can see that onMessageReceived function is trigged when a message arrives.

I use the firebase-messaging version 20.1.7

implementation 'com.google.firebase:firebase-messaging:20.1.7'

so I think you should do the following checking:

check if your app is in the foreground. because you can't trigger onMessageReceived when the app is in the background. refer: https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages

check if you wrote the right device token(your field 'userDeviceIdKey') when you sent the http request.

check if your http request has some error in catch.

hope can help you.


问:
Class not found with composer autoload in different servers
I have a very simple PHP/Composer application with the following structure:

```<code>- src
  - content
    - test
      - Sandbox.php
</code>```

Sandbox.php has only a static function to print "test" and its namespace is

```<code>namespace MyApplication\Content\Test;
</code>```

My autoload.php has MyApplication an "autoload" property.

```<code>"autoload" : {
    "psr-4": {"MyApplication\\": "src/"}
},
</code>```

I run composer install --no-dev in an Windows environment with XAMPP and in a test.php file I do (for the sake of a very simple test):

```<code>$autoloadFile = __DIR__ . '/wp-content/plugins/sandbox/vendor/autoload.php';
require $autoloadFile;
echo 'autoload = ' . file_exists($autoloadFile);
echo '<br />';
echo 'class_exists = ' . class_exists('MyApplication\Content\Test\Sandbox');
</code>```

When I run this test.php file locally, it works perfectly. MyApplication is loading Sandbox class.

However, when I release this to my server which is a Linux based server but running on the same PHP version, Sandbox class is not found.

I made sure my /vendor/ folder is properly uploaded as well.

I'm wondering if the problem is happening because I'm running composer install on a Windows environment while it should be running the same command in my server (which I can't at the moment). Shouldn't the /vendor/ folder upload be enough to make the autoload classes work well?

答: Path to your file is src/content/test/Sandbox.php and according to PSR-4 it should be src/Content/Test/Sandbox.php - on Windows it does not matter, but on Linux it does.

Body:
I have a very simple PHP/Composer application with the following structure:

- src
  - content
    - test
      - Sandbox.php

Sandbox.php has only a static function to print "test" and its namespace is

namespace MyApplication\Content\Test;

My autoload.php has MyApplication an "autoload" property.

"autoload" : {
    "psr-4": {"MyApplication\\": "src/"}
},

I run composer install --no-dev in an Windows environment with XAMPP and in a test.php file I do (for the sake of a very simple test):

$autoloadFile = __DIR__ . '/wp-content/plugins/sandbox/vendor/autoload.php';
require $autoloadFile;
echo 'autoload = ' . file_exists($autoloadFile);
echo '
';
echo 'class_exists = ' . class_exists('MyApplication\Content\Test\Sandbox');

When I run this test.php file locally, it works perfectly. MyApplication is loading Sandbox class.

However, when I release this to my server which is a Linux based server but running on the same PHP version, Sandbox class is not found.

I made sure my /vendor/ folder is properly uploaded as well.

I'm wondering if the problem is happening because I'm running composer install on a Windows environment while it should be running the same command in my server (which I can't at the moment). Shouldn't the /vendor/ folder upload be enough to make the autoload classes work well?


问:
Pyinstaller - Python exe when run shows error "Failed to execute script pyi_rth_nltk"
I have developed a simple software in python with GUI. I'm actually working on Natural Language Processing and I've just put the whole NLP process in a GUI.

I tried to convert the whole project to a exe file in python using Pyinstaller. I successfully converted it to an exe file but when I run it , it shows an error message something like this
This is the image of my error

答: I have already solved it but by using another way of converting py to exe which is the cx_Freeze.</p>


答:
you can do this.</p>

```<code>arr = ['cat', 'dog']
for item in arr:
  if item in "housecat":
      # do something
</code>```

Title: Contain snippet of word in array (Python)

Body:
you can do this.

arr = ['cat', 'dog']
for item in arr:
  if item in "housecat":
      # do something


问:
Add negative condition in InfluxDB: AND NOT (meter_id='500' AND conso_prod='Prod')
I have this query in Influx 1.7

```<code>SELECT sum(delta) from measures
WHERE operation_id='A1'
AND time>'2020-05-19T22:00:00.000Z' AND time<'2020-05-26T22:00:00.000Z'  GROUP BY time(1d)
</code>```

I want to exclude the results when  (meter_id='500' AND conso_prod='Prod')

So, I tried to add:

```<code>AND NOT (meter_id='500' AND conso_prod='Prod')
</code>```

but it seems NOT is not supported by influx.

So, I tried to write the negative, but it seems XOR doesn't exists neither.

It seems easy, but I can't do it. Any idea how should I do ?

答:
Update your Where clause as follow:

```<code>SELECT sum(delta) from measures
WHERE operation_id='A1'
AND time>'2020-05-19T22:00:00.000Z' AND time<'2020-05-26T22:00:00.000Z'

AND ( (meter_id='500' AND conso_prod!='Prod') OR (meter_id!='500' AND conso_prod='Prod') )

GROUP BY time(1d)
</code>```

Body:
I have this query in Influx 1.7

SELECT sum(delta) from measures
WHERE operation_id='A1'
AND time>'2020-05-19T22:00:00.000Z' AND time<'2020-05-26T22:00:00.000Z'  GROUP BY time(1d)

I want to exclude the results when  (meter_id='500' AND conso_prod='Prod')

So, I tried to add:

AND NOT (meter_id='500' AND conso_prod='Prod')

but it seems NOT is not supported by influx.

So, I tried to write the negative, but it seems XOR doesn't exists neither.

It seems easy, but I can't do it. Any idea how should I do ?

Body:
Update your Where clause as follow:

SELECT sum(delta) from measures
WHERE operation_id='A1'
AND time>'2020-05-19T22:00:00.000Z' AND time<'2020-05-26T22:00:00.000Z'

AND ( (meter_id='500' AND conso_prod!='Prod') OR (meter_id!='500' AND conso_prod='Prod') )

GROUP BY time(1d)


问:
How to remove elements in ArrayList?
Below is sample code.

How to remove a specific element in ArrayList?

```<code>
import java.util.ArrayList;

class A {
    int value;

    public A(int newValue) {
        setValue(newValue);
    }

    public int getValue() {
        return value;
    }

    public void setValue(int newValue) {
        value = newValue;
    }
}

class B {

    ArrayList <A> valuesOfA = new ArrayList<>();
    valuesOfA.add(new A(5));
    System.out.println("Adding...");
    for (A value: valueOfA) {
        System.out.println(value); //prints the values added.
    }
    valuesOfA.remove(new A(5));
    System.out.println("Removed");
    for (A value: valueOfA) {
        System.out.println(value);
    }
}
</code>```

Element as still not been removed. What is the solution for this?

答:
Though you are initializing the new object of A with same value, the objects are different having different memories, so you just have to remove the existing object having that memory location only.

I would suggest you to traverse the array and find the value 5 by filtering it and then removing that element from the array.

You could just use filter method for removing the added object.
Your code would look something like this:

```<code>valuesOfA = valuesOfA.stream().filter(obj -> !obj.getValue().equals(5));
</code>```

Now your valuesOfA array is not having the object whose value was 5 that you added before

Title: How to remove elements in ArrayList?

Body:
Below is sample code.

How to remove a specific element in ArrayList?

import java.util.ArrayList;

class A {
    int value;

    public A(int newValue) {
        setValue(newValue);
    }

    public int getValue() {
        return value;
    }

    public void setValue(int newValue) {
        value = newValue;
    }
}

class B {

    ArrayList  valuesOfA = new ArrayList<>();
    valuesOfA.add(new A(5));
    System.out.println("Adding...");
    for (A value: valueOfA) {
        System.out.println(value); //prints the values added.
    }
    valuesOfA.remove(new A(5));
    System.out.println("Removed");
    for (A value: valueOfA) {
        System.out.println(value);
    }
}

Element as still not been removed. What is the solution for this?

Body:
Though you are initializing the new object of A with same value, the objects are different having different memories, so you just have to remove the existing object having that memory location only.

I would suggest you to traverse the array and find the value 5 by filtering it and then removing that element from the array.

You could just use filter method for removing the added object.
Your code would look something like this:

valuesOfA = valuesOfA.stream().filter(obj -> !obj.getValue().equals(5));

Now your valuesOfA array is not having the object whose value was 5 that you added before


问:
HTML width at 100% overflowing
I am trying to set the width of a container to 100% of the page. By itself it seems to be fine, but once I add another
 element in the container, it overflows and the page becomes scrollable. I don't know what's wrong, because I haven't changed the padding and margin settings.

EDIT: the issue only seems to happen on chrome.

EDIT #2: Some people told me that they were not experiencing the same issue on their end, so I uploaded the project files and a screenshot of what I see on my google drive:

Project files

/* this is my css: */

body {
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  background-color: steelblue;
}

#mainContainer {
  width: 100%;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  flex-direction: column;
}

.genContainer {
  width: 50%;
  display: flex;
  justify-content: center;
}

.square {
  width: 5%;
  border: 1px solid black;
}

.circle {
  width: 5%;
  border: 1px solid black;
  border-radius: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="mainContainer">

    <div class="genContainer">

      <div class="person square"></div>

    </div>

  </div>
</body></code>```

Thank you!

答:
Unset the padding or margin added by the browser. Some browsers add css by default to your HTML page.
Write this as the first style rule:

```<code>* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}
</code>```

This will reset the margin and padding of all elements to 0 and so later in css you can override it.

Title: HTML width at 100% overflowing

Body:
I am trying to set the width of a container to 100% of the page. By itself it seems to be fine, but once I add another
 element in the container, it overflows and the page becomes scrollable. I don't know what's wrong, because I haven't changed the padding and margin settings.

EDIT: the issue only seems to happen on chrome.

EDIT #2: Some people told me that they were not experiencing the same issue on their end, so I uploaded the project files and a screenshot of what I see on my google drive:

Project files

/* this is my css: */

body {
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  background-color: steelblue;
}

#mainContainer {
  width: 100%;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  flex-direction: column;
}

.genContainer {
  width: 50%;
  display: flex;
  justify-content: center;
}

.square {
  width: 5%;
  border: 1px solid black;
}

.circle {
  width: 5%;
  border: 1px solid black;
  border-radius: 50%;
}

Thank you!

Body:
Unset the padding or margin added by the browser. Some browsers add css by default to your HTML page.
Write this as the first style rule:

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

This will reset the margin and padding of all elements to 0 and so later in css you can override it.


问:
RXAndroid/RXJava2: Chain three retrofit requests and repeat the same process again
I have stared learning RxAndroid and have understood the reactive programming approach and power of different operators like flatmap, map, and xmap.

I have the following situation, I have a list of Reports say List<Reports> (obtained at runtime). I have to make 3 API calls for a report in a sequence (API 1 -> API 2 -> API 3) and repeat the same process for all reports in a sequence.

Example:
For Reports A, B, C, and D in List<Reports> make 3 API call for A and then for B and then for C and then for D. If anyone of 3 API calls fails for a report then stop the remaining call and continue for the next Report. Here the size of List<Reports> is known at runtime only.

How can I use RXjava to solve this problem?

答:
Supposing you have the 4 API calls, a combineLatest operation would ideally return type Reports.

```<code>Observable<Report> result = Observable.combineLatest(
                apiA,
                apiB,
                apiC,
                apiD,
                (respA, respB, respC, respD) -> respA + respB + respC + respD
        )
                .subscribeOn(
                ....
</code>```

To be able to achieve the sequential order, you will need to wrap them in a flatMap operation:

```<code>Observable o = Observable.just(.....)// your initial data
o
  .flatMap(value -> doCombineLatestOperation(value))
  .subscribe(resp -> //Deal with data);
</code>```

Hope that helps.

Body:
Supposing you have the 4 API calls, a combineLatest operation would ideally return type Reports.

Observable<Report> result = Observable.combineLatest(
                apiA,
                apiB,
                apiC,
                apiD,
                (respA, respB, respC, respD) -> respA + respB + respC + respD
        )
                .subscribeOn(
                ....

To be able to achieve the sequential order, you will need to wrap them in a flatMap operation:

Observable o = Observable.just(.....)// your initial data
o
  .flatMap(value -> doCombineLatestOperation(value))
  .subscribe(resp -> //Deal with data);

Hope that helps.


答:
The problem lies in this line:

var usname = document.getElementById("name").innerHTML = greeting;
```

<p>Firstly, you're using an <code>=</code> sign twice – I would not do this. There are two options you could use instead:</p>

<pre class="lang-js prettyprint-override"><code>document.getElementById("name").innerHTML = greeting;
</code>```

var usname = document.getElementById("name");
usname.innerHTML = greeting;
```

<p>I've chosen the first option.</p>

<p>The other thing is that, for <code>input</code> elements, you need to use <code>value</code> and not <code>innerHTML</code>. A <code>div</code>, <code>span</code> or similar element would have <code>innerHTML</code> and <code>innerText</code> properties, but an input does not.</p>

<p>See the snippet below for a full, working solution:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function calc() {
  greeting = "hello"
  document.getElementById("name").value = greeting;
}</code>```

 BMI Calculator

    <form>

 Fill in the form below

      Name:

      <input type="text" name="name" id="name">
 Weight:

      <input type="number" name="weight">
 Height:

      <input type="number" name="height">

      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <input type="radio" name="gender" value="other">Other

<input type="button" onclick="calc()" name="calculate" value="calculate">
    </form>

 Your Results

```

Title: why doesn't my javascript function display my message?

Body:
The problem lies in this line:

var usname = document.getElementById("name").innerHTML = greeting;

Firstly, you're using an = sign twice – I would not do this. There are two options you could use instead:

document.getElementById("name").innerHTML = greeting;

var usname = document.getElementById("name");
usname.innerHTML = greeting;

I've chosen the first option.

The other thing is that, for input elements, you need to use value and not innerHTML. A div, span or similar element would have innerHTML and innerText properties, but an input does not.

See the snippet below for a full, working solution:

function calc() {
  greeting = "hello"
  document.getElementById("name").value = greeting;
}

<header>
  <p> BMI Calculator</p>
</header>
<div class="grid">
  <div class=input>
    <form>
      <p> Fill in the form below</p>
      Name: <br>
      <input type="text" name="name" id="name"><br> Weight: <br>
      <input type="number" name="weight"><br> Height: <br>
      <input type="number" name="height"><br>
      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <input type="radio" name="gender" value="other">Other<br>
      <br><input type="button" onclick="calc()" name="calculate" value="calculate">
    </form>
  </div>
  <div class="result">
    <p> Your Results</p>
  </div>
</div>


问:
How to call other python script in another python script?
I am trying to call other python script to another python script using import but it is giving some error. Can you please help me how to do this?

Example:

case.py is my one script which have one one function generate_case('rule_id'). This function is returning some value.

final.py is my another script in which I am trying to call above script and store return value into a variable.

I am trying to do in python :

```<code>import case as f_case

qry = ''
qry += f_case.generate_case('R162')
print(qry)
</code>```

Error:

```<code>ModuleNotFoundError: No module named 'case'
</code>```

Both the scripts are available in the same location.

答: I rename the script as new_cons.py. Now it working for me. May be in script name I have added integer so it is not importing the script.

Body:
I am trying to call other python script to another python script using import but it is giving some error. Can you please help me how to do this?

Example:

case.py is my one script which have one one function generate_case('rule_id'). This function is returning some value.

final.py is my another script in which I am trying to call above script and store return value into a variable.

I am trying to do in python :

import case as f_case

qry = ''
qry += f_case.generate_case('R162')
print(qry)

Error:

ModuleNotFoundError: No module named 'case'

Both the scripts are available in the same location.


问:
WPF how to clear the texbox content in list view using MVVM
I am using below code and MVVM observable, but "Clear" button not clears the content of text boxes.

What I need to do here?

MainWindow.xaml

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="30*"/>
        <RowDefinition Height="10*"/>
    </Grid.RowDefinitions>
    <Grid>
        <ListView ItemsSource="{Binding Credentials, Mode=OneWay}">
            <ListView.View>
                <GridView>
                    <GridViewColumn  Header="User Name">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding UserName}" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn  Header="Password">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Password}" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
    <Grid Grid.Row="1" >
        <Button Grid.Column="0" Content="Clear" Command="{Binding ClearTextBoxCommand}" Width="150"/>
    </Grid>

</Grid>
</code>```

MainWindow.xaml.cs

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MyViewModel();
    }
}
</code>```

MyViewModel.cs

```<code>public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Credential> _credentials;

    public RelayCommand ClearTextBoxCommand { get; }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        var handler = PropertyChanged;
        handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public ObservableCollection<Credential> Credentials
    {
        get => _credentials;
        set
        {
            if (value == _credentials)
                return;

            _credentials = value;
            OnPropertyChanged();
        }
    }

    public MyViewModel()
    {
        var data = new List<Credential> {new Credential {UserName = "user1", Password = "password1"}};
        _credentials = new ObservableCollection<Credential>(data);

        ClearTextBoxCommand = new RelayCommand(ClearTextBox);
    }

    private void ClearTextBox()
    {
        var data = new List<Credential> { new Credential { UserName = "", Password = "" } };
        _credentials = new ObservableCollection<Credential>(data);
        MessageBox.Show("clear done!");
    }
}

public class Credential
{
    public string UserName { get; set; }
    public string Password { get; set; }
}
</code>```

答:
Using the Credentials property instead of _credentials field is mandatory. But you do not have to assign a complete new ObservableCollection. Just clear the old one and add a new Credentials object.</p>

```<code>private void ClearTextBox()
{
    Credentials.Clear();
    Credentials.Add(new Credential { UserName = "", Password = "" });
    MessageBox.Show("clear done!");
}
</code>```

Body:
I am using below code and MVVM observable, but "Clear" button not clears the content of text boxes.

What I need to do here?

MainWindow.xaml

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="30*"/>
        <RowDefinition Height="10*"/>
    </Grid.RowDefinitions>
    <Grid>
        <ListView ItemsSource="{Binding Credentials, Mode=OneWay}">
            <ListView.View>
                <GridView>
                    <GridViewColumn  Header="User Name">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding UserName}" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn  Header="Password">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Password}" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
    <Grid Grid.Row="1" >
        <Button Grid.Column="0" Content="Clear" Command="{Binding ClearTextBoxCommand}" Width="150"/>
    </Grid>

</Grid>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MyViewModel();
    }
}

MyViewModel.cs

public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Credential> _credentials;

    public RelayCommand ClearTextBoxCommand { get; }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        var handler = PropertyChanged;
        handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public ObservableCollection<Credential> Credentials
    {
        get => _credentials;
        set
        {
            if (value == _credentials)
                return;

            _credentials = value;
            OnPropertyChanged();
        }
    }

    public MyViewModel()
    {
        var data = new List<Credential> {new Credential {UserName = "user1", Password = "password1"}};
        _credentials = new ObservableCollection<Credential>(data);

        ClearTextBoxCommand = new RelayCommand(ClearTextBox);
    }

    private void ClearTextBox()
    {
        var data = new List<Credential> { new Credential { UserName = "", Password = "" } };
        _credentials = new ObservableCollection<Credential>(data);
        MessageBox.Show("clear done!");
    }
}

public class Credential
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

Body:
Using the Credentials property instead of _credentials field is mandatory. But you do not have to assign a complete new ObservableCollection. Just clear the old one and add a new Credentials object.

private void ClearTextBox()
{
    Credentials.Clear();
    Credentials.Add(new Credential { UserName = "", Password = "" });
    MessageBox.Show("clear done!");
}


问:
Trying to figure out how to get this executable containerised for docker
I am having rough time trying to create a docker image that exposes Cloudflare's Tunnel executable for linux. Thus far I got to this stage with my docker image for it (image comes from https://github.com/jakejarvis/docker-cloudflare-argo/blob/master/Dockerfile)

```<code>FROM ubuntu:18.04

LABEL maintainer="Jake Jarvis <jake@jarv.is>"

RUN apt-get update \
  && apt-get install -y --no-install-recommends wget ca-certificates \
  && rm -rf /var/lib/apt/lists/*

RUN wget -O cloudflared.tgz https://bin.equinox.io/c/VdrWdbjqyF/cloudflared-stable-linux-amd64.tgz \
  && tar -xzvf cloudflared.tgz \
  && rm cloudflared.tgz \
  && chmod +x cloudflared

ENTRYPOINT ["./cloudflared"]
</code>```

And following official documentation for their kubernetes setup I added it to my deployment as a sidecar via: (here cloudflare-argo:5 is image built from dockerfile above)

```<code>    - name: cloudflare-argo
      image: my-registry/cloudflare-argo:5
      imagePullPolicy: Always
      command: ["cloudflared", "tunnel"]
      args:
        - --url=http://localhost:8080
        - --hostname=my-website
        - --origincert=/etc/cloudflared/cert.pem
        - --no-autoupdate
      volumeMounts:
        - mountPath: /etc/cloudflared
          name: cloudflare-argo-secret
          readOnly: true
      resources:
        requests:
          cpu: "50m"
        limits:
          cpu: "200m"
  volumes:
    - name: cloudflare-argo-secret
      secret:
        secretName: my-website.com
</code>```

However once I deploy I get CrashLoopBackOff error on my pod with following kubectl describe output

Created container cloudflare-argo

Error: failed to start container "cloudflare-argo": Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"cloudflared\": executable file not found in $PATH": unknown

答:
In the dockerfile it is ./cloudflared, so that would be:

```<code>      command:
        - ./cloudflared
        - tunnel
        - --url=http://localhost:8080
        - --hostname=my-website
        - --origincert=/etc/cloudflared/cert.pem
        - --no-autoupdate
</code>```

(also there is no reason to use both command and args, just pick one, if you drop the first item then use args).

Body:
I am having rough time trying to create a docker image that exposes Cloudflare's Tunnel executable for linux. Thus far I got to this stage with my docker image for it (image comes from https://github.com/jakejarvis/docker-cloudflare-argo/blob/master/Dockerfile)

FROM ubuntu:18.04

LABEL maintainer="Jake Jarvis <jake@jarv.is>"

RUN apt-get update \
  && apt-get install -y --no-install-recommends wget ca-certificates \
  && rm -rf /var/lib/apt/lists/*

RUN wget -O cloudflared.tgz https://bin.equinox.io/c/VdrWdbjqyF/cloudflared-stable-linux-amd64.tgz \
  && tar -xzvf cloudflared.tgz \
  && rm cloudflared.tgz \
  && chmod +x cloudflared

ENTRYPOINT ["./cloudflared"]

And following official documentation for their kubernetes setup I added it to my deployment as a sidecar via: (here cloudflare-argo:5 is image built from dockerfile above)

    - name: cloudflare-argo
      image: my-registry/cloudflare-argo:5
      imagePullPolicy: Always
      command: ["cloudflared", "tunnel"]
      args:
        - --url=http://localhost:8080
        - --hostname=my-website
        - --origincert=/etc/cloudflared/cert.pem
        - --no-autoupdate
      volumeMounts:
        - mountPath: /etc/cloudflared
          name: cloudflare-argo-secret
          readOnly: true
      resources:
        requests:
          cpu: "50m"
        limits:
          cpu: "200m"
  volumes:
    - name: cloudflare-argo-secret
      secret:
        secretName: my-website.com

However once I deploy I get CrashLoopBackOff error on my pod with following kubectl describe output

Created container cloudflare-argo

Error: failed to start container "cloudflare-argo": Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"cloudflared\": executable file not found in $PATH": unknown

Body:
In the dockerfile it is ./cloudflared, so that would be:

      command:
        - ./cloudflared
        - tunnel
        - --url=http://localhost:8080
        - --hostname=my-website
        - --origincert=/etc/cloudflared/cert.pem
        - --no-autoupdate

(also there is no reason to use both command and args, just pick one, if you drop the first item then use args).


问:
ExpressJS: localhost didn’t send any data
I am writing an app, when I start the server, its working nicely, its connecting to database. But when I start http://localhost:5000 from the browser, it does not respond for a minuite then  the browser shows a message:

```<code>localhost didn’t send any data.
ERR_EMPTY_RESPONSE
</code>```

Here is my app.js:

```<code>const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
app.use(cookieParser);
app.use(express.json());

//const userRouter = require('./routes/user');
//app.use('/user', userRouter);

const startApp = async () => {
    try {
        await mongoose.connect('mongodb+srv://username:pass@cluster0-dcytp.mongodb.net/test?retryWrites=true&w=majority',
        { useUnifiedTopology: true,useNewUrlParser: true });
        console.log(`successfully connected to database`);
        const port = process.env.PORT || 5000
        app.listen(port, () => {
            console.log(`server runnin at ${port}`);
        });
    } catch (error) {
        console.log(error.message)
    }
}

startApp();

app.get('/', (req, res) => {
    console.log("I am in the root");
    res.send("hello World");
})
</code>```

Why server is not responding from the browser?

答:
try

```<code>app.use(cookieParser())
</code>```

instead of

```<code>app.use(cookieParser)
</code>```

Reference

Body:
I am writing an app, when I start the server, its working nicely, its connecting to database. But when I start http://localhost:5000 from the browser, it does not respond for a minuite then  the browser shows a message:

localhost didn’t send any data.
ERR_EMPTY_RESPONSE

Here is my app.js:

const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
app.use(cookieParser);
app.use(express.json());

//const userRouter = require('./routes/user');
//app.use('/user', userRouter);

const startApp = async () => {
    try {
        await mongoose.connect('mongodb+srv://username:pass@cluster0-dcytp.mongodb.net/test?retryWrites=true&w=majority',
        { useUnifiedTopology: true,useNewUrlParser: true });
        console.log(`successfully connected to database`);
        const port = process.env.PORT || 5000
        app.listen(port, () => {
            console.log(`server runnin at ${port}`);
        });
    } catch (error) {
        console.log(error.message)
    }
}

startApp();

app.get('/', (req, res) => {
    console.log("I am in the root");
    res.send("hello World");
})

Why server is not responding from the browser?

Body:
try

app.use(cookieParser())

instead of

app.use(cookieParser)

Reference


问:
Parsing a tab-delimited text file to replace columns with one vertical list (Python)
I'm very new to Python and I know this is a pretty basic question. I have a text file with columns of data. I want to remove the columns and make it one long list.

I have the following code:

```<code>for line in open('feddocs_2011.txt', 'r'):
    segmentedLine = line.split("/t")
    print segmentedLine
</code>```

This seems to create a separate string for each line, but I think I may need to loop through each of those new strings to split those next. I thought it would have put everything following a tab on a new line. I tried the following, but got an error message that "list" doesn't have a split function.

```<code>while segmentedLine:
    item = segmentedLine.split("\t")
    print item
</code>```

Thanks very much for any input.

答:
what about:

```<code>x = [line.split('\t') for line in open('file.txt')]
</code>```

and you can join the lists, if you want:

```<code>sum(x, [])
</code>```

[Edit]

if your file only have tabs (no spaces) you can simply do:

```<code>x = open('file.txt').read().split()
</code>```

Body:
I'm very new to Python and I know this is a pretty basic question. I have a text file with columns of data. I want to remove the columns and make it one long list.

I have the following code:

for line in open('feddocs_2011.txt', 'r'):
    segmentedLine = line.split("/t")
    print segmentedLine

This seems to create a separate string for each line, but I think I may need to loop through each of those new strings to split those next. I thought it would have put everything following a tab on a new line. I tried the following, but got an error message that "list" doesn't have a split function.

while segmentedLine:
    item = segmentedLine.split("\t")
    print item

Thanks very much for any input.

Body:
what about:

x = [line.split('\t') for line in open('file.txt')]

and you can join the lists, if you want:

sum(x, [])

[Edit]

if your file only have tabs (no spaces) you can simply do:

x = open('file.txt').read().split()


问:
Cassandra: Changing snitch property and then starting the Cassandra Node, gives error
I was trying to learn Cassandra. I got the below error (As mentioned in point 4 ), when tried to follow the below steps.

1) I had downloaded Cassandra from Datastax and made another copy of the same and named both folders into node1 and node2.

2) Changed the  endpoint_snitch to GossipingPropertyFileSnitch in Cassandra.yaml in both the nodes

3) In /home/ubuntu/node1/resources/cassandra/conf/cassandra-rackdc.properties

changed for Node1 as:
              dc=west-side
              rack=hakuna-matata

changed for Node2 as:
              dc=east-side
              rack=hakuna-matata

4) Started Node2. Getting error as below:

"Cannot start node if snitch's data center (east-side) differs from previous data center (Cassandra). Please fix the snitch configuration, decommission and rebootstrap this node or use the flag -Dcassandra.ignore_dc=true"

Steps Tried to resolve it:

1) Stopped the node and deleted the /var/lib/cassandra/data folder -- It didn't work

2) Reverted all the property changes --> It is working.

3) Tried with the steps mentioned in Cannot start Cassandra - Snitch's Datacenter Differs from Previous. --> It did not work

Please let me know, why changing the snitch properties is giving the error (as mentioned above)

答:
From what you describing, it looks like that you already started the node as-is, because Cassandra datacenter name is given when you're started the DSE with DseSimpleSnitch.

To resolve this problem, you need:

Make sure that both instances point to different data directories, have different commit log directories, hints, etc. It's better to point to 2 separate clear directories.

If you're using DSE 6 for experiments, having 2 instances on the same node will require an additional tuning, that it's better to avoid at beginning.

If you want to have multiple instances of Cassandra/DSE for experiments, use of Docker could be easier, like shown here: https://github.com/datastax/docker-images (see examples folder).  Another possibility is to  use DataStax Desktop that allows easier provision of the Docker-based instances - you can play with different versions, etc.


问:
How to pass own executors to the redis lettuce library?
I have below code to get the data from Redis asynchronously. By default get() call in lettuce library uses nio-event thread pool.

Code 1:

```<code>StatefulRedisConnection<String, String> connection = redisClient.connect();
RedisAsyncCommands<String, String> command = connection.async();
CompletionStage<String> result = command.get(id)
        .thenAccept(code ->
                     logger.log(Level.INFO, "Thread Id " + Thread.currentThread().getName());
                     //Sample code to print thread ID
</code>```

Thread Id printed is lettuce-nioEventLoop-6-2.

Code 2:

```<code>CompletionStage<String> result = command.get(id)
            .thenAcceptAsync(code -> {
                         logger.log(Level.INFO, "Thread Id " + Thread.currentThread().getName());
              //my original code
}, executors);
</code>```

Thread Id printed is pool-1-thread-1.

My questions:

Is there a way to pass my executors?

Is it recommended approach to use nio-event thread pool to get(using get() call) the data from redis?

Lettuce version: 5.2.2.RELEASE

thanks,
Ashok

答:
class io.lettuce.core.RedisClient has a creator method:

    public static RedisClient create(ClientResources clientResources, String uri) {
        assertNotNull(clientResources);
        LettuceAssert.notEmpty(uri, "URI must not be empty");
        return create(clientResources, RedisURI.create(uri));
    }
```

You can build your ClientResources by ClientResources#builder(), and pass anything you want. Refer the JavaDoc, there is something you can customize:

EventLoopGroupProvider to obtain particular EventLoopGroups

EventExecutorGroup to perform internal computation tasks

Timer for scheduling

EventBus for client event dispatching

EventPublisherOptions

CommandLatencyCollector to collect latency details. Requires the HdrHistogram library.

DnsResolver to collect latency details. Requires the LatencyUtils library.

Reconnect Delay.

Tracing to trace Redis commands.

Body:
I have below code to get the data from Redis asynchronously. By default get() call in lettuce library uses nio-event thread pool.

Code 1:

StatefulRedisConnection<String, String> connection = redisClient.connect();
RedisAsyncCommands<String, String> command = connection.async();
CompletionStage<String> result = command.get(id)
        .thenAccept(code ->
                     logger.log(Level.INFO, "Thread Id " + Thread.currentThread().getName());
                     //Sample code to print thread ID

Thread Id printed is lettuce-nioEventLoop-6-2.

Code 2:

CompletionStage<String> result = command.get(id)
            .thenAcceptAsync(code -> {
                         logger.log(Level.INFO, "Thread Id " + Thread.currentThread().getName());
              //my original code
}, executors);

Thread Id printed is pool-1-thread-1.

My questions:

Is there a way to pass my executors?

Is it recommended approach to use nio-event thread pool to get(using get() call) the data from redis?

Lettuce version: 5.2.2.RELEASE

thanks,
Ashok

Body:
class io.lettuce.core.RedisClient has a creator method:

    public static RedisClient create(ClientResources clientResources, String uri) {
        assertNotNull(clientResources);
        LettuceAssert.notEmpty(uri, "URI must not be empty");
        return create(clientResources, RedisURI.create(uri));
    }

You can build your ClientResources by ClientResources#builder(), and pass anything you want. Refer the JavaDoc, there is something you can customize:

EventLoopGroupProvider to obtain particular EventLoopGroups

EventExecutorGroup to perform internal computation tasks

Timer for scheduling

EventBus for client event dispatching

EventPublisherOptions

CommandLatencyCollector to collect latency details. Requires the HdrHistogram library.

DnsResolver to collect latency details. Requires the LatencyUtils library.

Reconnect Delay.

Tracing to trace Redis commands.


问:
Why I can't get right answer?
Code on Github

A baby programmer seeking for help, please.
What went wrong in my code if anyone can help?

A very simple python program to compare two numbers using functions

```<code>from sys import exit

def main():
    check()
    compare(x, y)

def check():
    # prompt user for two numbers
    x = input("x: ")
    y = input("y: ")

    # apply sanity check
    if x.isnumeric() == False and y.isnumeric() == False:
        print("Usage: only real numbers are accepted.")
        exit(1)
    else:
        return x, y

def compare(x, y):
    # TODO
    if x < y:
        return print("x is smaller than y")
    elif x > y:
        return print("x is greater than y")
    else:
        return print("They are the same!")

main()
</code>```

答:
If not convert x, y to int, it will compare x, y as string(dictionary order)

you should check x , y is number by or, not and

```<code>from sys import exit

def main():
    x, y = check()
    compare(x, y)

def check():
    # prompt user for two numbers
    x = input("x: ")
    y = input("y: ")

    # apply sanity check
    if x.isnumeric() is False or y.isnumeric() is False:
        print("Usage: only real numbers are accepted.")
        exit(1)
    else:
        return x, y

def compare(x, y):
    x = int(x)
    y = int(y)
    # TODO
    if x < y:
        return print("x is smaller than y")
    elif x > y:
        return print("x is greater than y")
    else:
        return print("They are the same!")

main()
</code>```

Title: Why I can't get right answer?

Body:
Code on Github

A baby programmer seeking for help, please.
What went wrong in my code if anyone can help?

A very simple python program to compare two numbers using functions

from sys import exit

def main():
    check()
    compare(x, y)

def check():
    # prompt user for two numbers
    x = input("x: ")
    y = input("y: ")

    # apply sanity check
    if x.isnumeric() == False and y.isnumeric() == False:
        print("Usage: only real numbers are accepted.")
        exit(1)
    else:
        return x, y

def compare(x, y):
    # TODO
    if x < y:
        return print("x is smaller than y")
    elif x > y:
        return print("x is greater than y")
    else:
        return print("They are the same!")

main()

Body:
If not convert x, y to int, it will compare x, y as string(dictionary order)

you should check x , y is number by or, not and

from sys import exit

def main():
    x, y = check()
    compare(x, y)

def check():
    # prompt user for two numbers
    x = input("x: ")
    y = input("y: ")

    # apply sanity check
    if x.isnumeric() is False or y.isnumeric() is False:
        print("Usage: only real numbers are accepted.")
        exit(1)
    else:
        return x, y

def compare(x, y):
    x = int(x)
    y = int(y)
    # TODO
    if x < y:
        return print("x is smaller than y")
    elif x > y:
        return print("x is greater than y")
    else:
        return print("They are the same!")

main()


问:
Artificial generation of cpu load in Java
Is there a simple way to generate a constant CPU load in Java? Like generate CPU load at 60%.</p>

答:
Have not tested this, but it might roughly work, to make your application work and sleep in the correct ratio. Something like (pseudocode): </p>

```<code>load = 60;
do forever
  time = current_system_time_ms() + load
  while (current_system_time_ms() < time)
     // just consume some time for 60 ms
  end

  SLEEP(100 - load);  // sleep for 40 ms
end
</code>```

<p>Ok, you asked for a simple way, but ... :) </p>

Body:
Have not tested this, but it might roughly work, to make your application work and sleep in the correct ratio. Something like (pseudocode):

load = 60;
do forever
  time = current_system_time_ms() + load
  while (current_system_time_ms() < time)
     // just consume some time for 60 ms
  end

  SLEEP(100 - load);  // sleep for 40 ms
end

Ok, you asked for a simple way, but ... :)