问:
React native white blank screen when load website in a webview
Bug description: The site that I directed with Webview is opened in the ios simulator, Although not working in the andorid simulator.

To Reproduce:

react-native init AwesomeProject
cd AwesomeProject
react-native run-android

&& my code

code

Expected behavior:.  Work same as ios simulator

Screenshots/Videos:

Environment:
 - OS: macOS
 - OS version: 10.15.3
 - react-native version: 0.62.2
 - react-native-webview version: 10.2.3

答:
there are several solutions that I found for myself. @mlammert

add this code snippet to

\node_modules\react-native webview\android\src\main\java\com\reactnativecommunity\webview\RNCWebViewManager.java

After that  in AndroidManifest.xml add these code snippets.

<uses-permission android:name="android.permission.INTERNET" />

and in the  add this one android:usesCleartextTraffic="true">


来源: stackexchange

问:
List location of executables within the CTest test suite
I have some source code that is compiled using CMake, with unit tests that are added to CTest via the CMake directive add_test(). I want the list of executables (absolute/relative path) that are used within this test suite.

Since tests are added as follows:

```<code>add_test(NAME ${A} COMMAND ${execA})
add_test(NAME ${B} COMMAND ${execB})
add_test(NAME ${C} COMMAND ${execA} ${addOptions})
</code>```

there are only two distinct executables (${execA}, ${execB}) for three tests (${A}, ${B}, and ${C}).

I am totally fine having duplicates and ignoring options or having options.

So, the ideal output would be the following (but I certainly can do some parsing manually if needed):

```<code> src/folder1/test/testThisFunction
 src/folder2/test/testThatFunction
 src/folder1/test/testThisFunction -WithThisFlag
</code>```

The closest I was able to get was with:

```<code>ctest -N,--show-only
</code>```

which does not run the tests, but simply shows them:

```<code>    Start 1: testA
1/3 Test #1: testA .......................   Passed    0.01 sec
    Start 2: testB
2/3 Test #2: testB .......................   Passed    0.01 sec
    Start 3: testC
3/3 Test #3: testC ........................  Passed    0.01 sec
</code>```

Unfortunately, this output does not contain the information about the path to the executable.

In this example above, it is assumed that

```<code>${execA} = testThisFunction
${execB} = testThatFunction
</code>```

where testThisFunction and testThatFunction are CMake targets (unit tests) and

```<code>${A} = "testA"
${B} = "testB"
${C} = "testC"
${addOptions} = "-WithThisFlag"
</code>```

store names of the tests and options, respectively.

While I have the access to CMakeLists.txt, I strongly prefer to do this solely on ctest level after CMake configuring and subsequent compilation are already completed (thus, not generating list of executables using CMake commands in CMakeLists.txt).

If this is relevant, I am using CTest 3.10.2, but open to upgrade.

答:
Firstly, you only need the -N or the --show-only option in the ctest command, not both. In your case, CTest silently ignored your command line option -N,--show-only because it was not recognized. The output indicates that your tests did run. To simply list them, use:

```<code>ctest --show-only
</code>```

Getting to your question: If you upgrade to CMake 3.14 or higher, you gain the JSON-formatted ctest --show-only option.

```<code>ctest --show-only=json-v1
</code>```

This will print information about each of your tests, including the arguments passed to each. Your output from this may contain something like this:

```<code>  "tests" :
  [
    {
      "backtrace" : 1,
      "command" :
      [
        "src/folder1/test/testThisFunction"
      ],
      "config" : "Debug",
      "name" : "testA",
      "properties" :
      [
        {
          "name" : "WORKING_DIRECTORY",
          "value" : "src"
        }
      ]
    },
    {
      "backtrace" : 3,
      "command" :
      [
        "src/folder2/test/testThatFunction"
      ],
      "config" : "Debug",
      "name" : "testB",
      "properties" :
      [
        {
          "name" : "WORKING_DIRECTORY",
          "value" : "src"
        }
      ]
    },
    {
      "backtrace" : 5,
      "command" :
      [
        "src/folder1/test/testThisFunction",
        "-WithThisFlag"
      ],
      "config" : "Debug",
      "name" : "testC",
      "properties" :
      [
        {
          "name" : "WORKING_DIRECTORY",
          "value" : "src"
        }
      ]
    }
  ],
</code>```

In the output, the full path to the executable and the test's command line arguments are listed after "command" :.

ContentLicense: CC BY-SA 4.0

Body:
I have some source code that is compiled using CMake, with unit tests that are added to CTest via the CMake directive add_test(). I want the list of executables (absolute/relative path) that are used within this test suite.

Since tests are added as follows:

add_test(NAME ${A} COMMAND ${execA})
add_test(NAME ${B} COMMAND ${execB})
add_test(NAME ${C} COMMAND ${execA} ${addOptions})

there are only two distinct executables (${execA}, ${execB}) for three tests (${A}, ${B}, and ${C}).

I am totally fine having duplicates and ignoring options or having options.

So, the ideal output would be the following (but I certainly can do some parsing manually if needed):

 src/folder1/test/testThisFunction
 src/folder2/test/testThatFunction
 src/folder1/test/testThisFunction -WithThisFlag

The closest I was able to get was with:

ctest -N,--show-only

which does not run the tests, but simply shows them:

    Start 1: testA
1/3 Test #1: testA .......................   Passed    0.01 sec
    Start 2: testB
2/3 Test #2: testB .......................   Passed    0.01 sec
    Start 3: testC
3/3 Test #3: testC ........................  Passed    0.01 sec

Unfortunately, this output does not contain the information about the path to the executable.

In this example above, it is assumed that

${execA} = testThisFunction
${execB} = testThatFunction

where testThisFunction and testThatFunction are CMake targets (unit tests) and

${A} = "testA"
${B} = "testB"
${C} = "testC"
${addOptions} = "-WithThisFlag"

store names of the tests and options, respectively.

While I have the access to CMakeLists.txt, I strongly prefer to do this solely on ctest level after CMake configuring and subsequent compilation are already completed (thus, not generating list of executables using CMake commands in CMakeLists.txt).

If this is relevant, I am using CTest 3.10.2, but open to upgrade.

Body:
Firstly, you only need the -N or the --show-only option in the ctest command, not both. In your case, CTest silently ignored your command line option -N,--show-only because it was not recognized. The output indicates that your tests did run. To simply list them, use:

ctest --show-only

Getting to your question: If you upgrade to CMake 3.14 or higher, you gain the JSON-formatted ctest --show-only option.

ctest --show-only=json-v1

This will print information about each of your tests, including the arguments passed to each. Your output from this may contain something like this:

  "tests" :
  [
    {
      "backtrace" : 1,
      "command" :
      [
        "src/folder1/test/testThisFunction"
      ],
      "config" : "Debug",
      "name" : "testA",
      "properties" :
      [
        {
          "name" : "WORKING_DIRECTORY",
          "value" : "src"
        }
      ]
    },
    {
      "backtrace" : 3,
      "command" :
      [
        "src/folder2/test/testThatFunction"
      ],
      "config" : "Debug",
      "name" : "testB",
      "properties" :
      [
        {
          "name" : "WORKING_DIRECTORY",
          "value" : "src"
        }
      ]
    },
    {
      "backtrace" : 5,
      "command" :
      [
        "src/folder1/test/testThisFunction",
        "-WithThisFlag"
      ],
      "config" : "Debug",
      "name" : "testC",
      "properties" :
      [
        {
          "name" : "WORKING_DIRECTORY",
          "value" : "src"
        }
      ]
    }
  ],

In the output, the full path to the executable and the test's command line arguments are listed after "command" :.


问:
Call Swift enum case within same enum function
I'm trying to get my head around Swift enums and in doing so have taken myself off a tutorial track by trying to return a string from a function within the same enum...

```<code>enum topFiveBands: Int {
    case led_zeppilin = 1, queen, rush, pink_floyd, acdc

    func printRating() {
        print("The band \(???) has been ranked no.\(self.rawValue) of all time")
    }
}

var myFavBand = topFiveBands.acdc
myFavBand.printRating()
</code>```

My code starts with a implicit assignment which lists the top 5 bands of all time (some of you may disagree with me on this..). Within the same enum I have a function which will print:

```<code>The band \(???) has been ranked no.\(self.rawValue) of all time
</code>```

I've chosen .acdc so I'm looking for the function to return:

```<code>The band acdc has been ranked no.5 of all time
</code>```

Whilst I can pull the rawValue (5) I can't seem to find a way to get the acdc into the string.

答:
Just use self:

```<code>func printRating() {
    print("The band \(self) has been ranked no.\(self.rawValue) of all time")
}
</code>```

The self is the reference to its own value which is acdc in this case.

Body:
I'm trying to get my head around Swift enums and in doing so have taken myself off a tutorial track by trying to return a string from a function within the same enum...

enum topFiveBands: Int {
    case led_zeppilin = 1, queen, rush, pink_floyd, acdc

    func printRating() {
        print("The band \(???) has been ranked no.\(self.rawValue) of all time")
    }
}

var myFavBand = topFiveBands.acdc
myFavBand.printRating()

My code starts with a implicit assignment which lists the top 5 bands of all time (some of you may disagree with me on this..). Within the same enum I have a function which will print:

The band \(???) has been ranked no.\(self.rawValue) of all time

I've chosen .acdc so I'm looking for the function to return:

The band acdc has been ranked no.5 of all time

Whilst I can pull the rawValue (5) I can't seem to find a way to get the acdc into the string.

Body:
Just use self:

func printRating() {
    print("The band \(self) has been ranked no.\(self.rawValue) of all time")
}

The self is the reference to its own value which is acdc in this case.


问:
how to count the frequency of letters in text excluding whitespace and numbers?
Use a dictionary to count the frequency of letters in the input string. Only letters should be counted, not blank spaces, numbers, or punctuation. Upper case should be considered the same as lower case. For example, count_letters("This is a sentence.") should return {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}</p>

```<code>def count_letters(text):
      result = {}
      # Go through each letter in the text
      for letter in text:
        # Check if the letter needs to be counted or not
        if letter not in result:
          result[letter.lower()] = 1
        # Add or increment the value in the dictionary
        else:
          result[letter.lower()] += 1
      return result

    print(count_letters("AaBbCc"))
    # Should be {'a': 2, 'b': 2, 'c': 2}

    print(count_letters("Math is fun! 2+2=4"))
    # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

    print(count_letters("This is a sentence."))
    # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
</code>```

答:
```<code>def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text:
    # Check if the letter needs to be counted or not
    if letter.isalpha():
      result[letter.lower()]=result.get(letter.lower(),0)+1
    # Add or increment the value in the dictionary
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
</code>```

Body:
Use a dictionary to count the frequency of letters in the input string. Only letters should be counted, not blank spaces, numbers, or punctuation. Upper case should be considered the same as lower case. For example, count_letters("This is a sentence.") should return {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}

def count_letters(text):
      result = {}
      # Go through each letter in the text
      for letter in text:
        # Check if the letter needs to be counted or not
        if letter not in result:
          result[letter.lower()] = 1
        # Add or increment the value in the dictionary
        else:
          result[letter.lower()] += 1
      return result

    print(count_letters("AaBbCc"))
    # Should be {'a': 2, 'b': 2, 'c': 2}

    print(count_letters("Math is fun! 2+2=4"))
    # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

    print(count_letters("This is a sentence."))
    # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}


问:
Script to execute 1 of 2 functions randomly?
Is it possible to modify the script below so that the value of each option is a function?

```<code><?php

$option[0] = 'html option 1';
$option[1] = 'html option 2';

echo $option[rand()%count($option)];
?>
</code>```

Obviously, this doesn't work:

```<code>function get_ads_rotation(){
    $option[0] = get_ad_option1();
    $option[1] = get_ad_option2();
   echo $option[rand()%count($option)];
</code>```

}

(Props to yes123 for the randomization script above)

答:
Here:</p>

```<code>$option[0] = 'get_ad_option1';
$option[1] = 'get_ad_option2';
echo call_user_func($option(...));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to modify the script below so that the value of each option is a function?

<?php

$option[0] = 'html option 1';
$option[1] = 'html option 2';

echo $option[rand()%count($option)];
?>

Obviously, this doesn't work:

function get_ads_rotation(){
    $option[0] = get_ad_option1();
    $option[1] = get_ad_option2();
   echo $option[rand()%count($option)];

}

(Props to yes123 for the randomization script above)

Body:
Here:

$option[0] = 'get_ad_option1';
$option[1] = 'get_ad_option2';
echo call_user_func($option(...));


问:
Errors in sorting a dictionary
This is my code to find and print values of students with the second-lowest score in the given data

```<code>room =dict()
for _ in range(int(input())):
    name = input()
    score = float(input())
    room.update({name:score})

lowest= min(room.values())
second_lowest = None
for k,v in sorted(room.items(),reverse=True):
    if v == lowest: continue
    elif second_lowest is None:
        second_lowest = v
    elif v < second_lowest:
        second_lowest = v
    if second_lowest==v and second_lowest is not lowest:
        print('name',k)
</code>```

When given a specific set of inputs it returns more than two second_lowest key, for example, for the below input it returns harsh harry and berry where it shouldn't have returned harsh. But this problem disappears if I create a separate (key, value) loop with the same

```<code>sorted(room.items(),reverse=True)
</code>```

Sample Input:

```<code>5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
</code>```

Sample Output:

```<code>name Harsh
name Harry
name Berry
</code>```

答:
I suggest sorting by the score and printing the name of the second element of the sorted array.

room =dict()
for _ in range(int(input())):
    name = input()
    score = float(input())
    room.update({name:score})

second_lowest = sorted(room.values())[1]
print('\n'.join('name: '+ result[0] for result in room.items()
                if result[1] == second_lowest))
```

Title: Errors in sorting a dictionary

Body:
This is my code to find and print values of students with the second-lowest score in the given data

room =dict()
for _ in range(int(input())):
    name = input()
    score = float(input())
    room.update({name:score})

lowest= min(room.values())
second_lowest = None
for k,v in sorted(room.items(),reverse=True):
    if v == lowest: continue
    elif second_lowest is None:
        second_lowest = v
    elif v < second_lowest:
        second_lowest = v
    if second_lowest==v and second_lowest is not lowest:
        print('name',k)

When given a specific set of inputs it returns more than two second_lowest key, for example, for the below input it returns harsh harry and berry where it shouldn't have returned harsh. But this problem disappears if I create a separate (key, value) loop with the same

sorted(room.items(),reverse=True)

Sample Input:

5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

Sample Output:

name Harsh
name Harry
name Berry


问:
How do have both count and percent on barcharts in ggplot2? R
this is my data

```<code>data <- data.frame("Name" = c("Mark", "Jenny", "Linn"),
                   "Freq" = c("5","7", "3"),
                   "Percent" = c("33%", "47%", "20%"))
</code>```

This is my plot

```<code>ggplot(data, aes(x=Name, y=Freq)) +
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label=data$Freq, vjust=-1)

</code>```

How can I have both my percent label next to my freq label preferably in parenthesis or separated by a comma?

答:
The first excellent answer uses a simple general strategy for labeling each bar, but did not work in my hands because as.numeric(Freq) returns c(2,3,1), not the expected c(5,7,3) (as a result, I could not reproduce the chart shown).  The third answer fixes the factor problem, but does not label the bars as asked in the question.  The simple solution would be to have the Freq numbers be numbers, then the first answer works:

```<code>data <- data.frame("Name" = c("Mark", "Jenny", "Linn"),
                   "Freq" = c(5,7,3),
                   "Percent" = c("33%", "47%", "20%"))
</code>```

And, once we have numbers, we can have 'R' calculate percentages:

```<code>ggplot(data, aes(x = Name, y = Freq)) +
  geom_bar(stat = "identity", color = "black", fill = "dodgerblue1") +
  geom_text(label = with(data, sprintf("%d (%.0f%%)",Freq, 100*Freq/sum(Freq))), vjust=-1)+
  ylim(0,8)
</code>```

Body:
this is my data

data <- data.frame("Name" = c("Mark", "Jenny", "Linn"),
                   "Freq" = c("5","7", "3"),
                   "Percent" = c("33%", "47%", "20%"))

This is my plot

ggplot(data, aes(x=Name, y=Freq)) +
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label=data$Freq, vjust=-1)

How can I have both my percent label next to my freq label preferably in parenthesis or separated by a comma?

Body:
The first excellent answer uses a simple general strategy for labeling each bar, but did not work in my hands because as.numeric(Freq) returns c(2,3,1), not the expected c(5,7,3) (as a result, I could not reproduce the chart shown).  The third answer fixes the factor problem, but does not label the bars as asked in the question.  The simple solution would be to have the Freq numbers be numbers, then the first answer works:

data <- data.frame("Name" = c("Mark", "Jenny", "Linn"),
                   "Freq" = c(5,7,3),
                   "Percent" = c("33%", "47%", "20%"))

And, once we have numbers, we can have 'R' calculate percentages:

ggplot(data, aes(x = Name, y = Freq)) +
  geom_bar(stat = "identity", color = "black", fill = "dodgerblue1") +
  geom_text(label = with(data, sprintf("%d (%.0f%%)",Freq, 100*Freq/sum(Freq))), vjust=-1)+
  ylim(0,8)


问:
How to use SSL with Vue CLI for local development?
I understand to use https with Vue CLI I can set "https: true" under devServer in a vue.config.js file, but I also need a self signed certificate.

I've tried generating a self signed one using OpenSSL and using the following in my vue.config.js file to target:

```<code>const fs = require('fs');

module.exports = {
    devServer: {
        port: '8081',
        https: {
            key: fs.readFileSync('./certs/server.key'),
            cert: fs.readFileSync('./certs/server.cert'),
        },
    },
};
</code>```

Chrome confirms it's using my certificate but still shows https as "Not secure"

How can I make chrome assess my self signed certificate as secure when providing it via Vue CLI?

答:
Use the network path rather than loopback or localhost. For example

https://192.168.2.210:8080/

works fine, while

https://localhost:8080/ and https://127.0.0.1:8080 balk at the certificate problem.

Body:
I understand to use https with Vue CLI I can set "https: true" under devServer in a vue.config.js file, but I also need a self signed certificate.

I've tried generating a self signed one using OpenSSL and using the following in my vue.config.js file to target:

const fs = require('fs');

module.exports = {
    devServer: {
        port: '8081',
        https: {
            key: fs.readFileSync('./certs/server.key'),
            cert: fs.readFileSync('./certs/server.cert'),
        },
    },
};

Chrome confirms it's using my certificate but still shows https as "Not secure"

How can I make chrome assess my self signed certificate as secure when providing it via Vue CLI?


问:
How to sort only selected columns in pandas dataframe
I want to sort some columns in large Pandas dataframe. Those columns are in the middle of df and in end. They start with "R"

```<code>columns_list = df.columns.tolist()
columns_list
Out[17]:
['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft', 'Planet', 'ExtraterrestialSupplier', 'R5', 'R2', 'R1', 'R4', 'R3', 'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R5S3', 'R5S2', 'R5S4','R1S4']
</code>```

I would like to re-order like that:

```<code>['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft', 'Planet', 'ExtraterrestialSupplier', 'R1', 'R2','R3', 'R4', 'R5', 'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R1S4', 'R5S2', 'R5S3','R5S4']
</code>```

Until now I did it manually:

```<code>df= df['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft', 'Planet', 'ExtraterrestialSupplier', 'R1', 'R2','R3', 'R4', 'R5', 'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R1S4', 'R5S2', 'R5S3','R5S4']
</code>```

but new input data have more R columns and in every file it is different.

I would appreciate your advice.

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

df = pd.DataFrame(np.random.rand(5, 6), columns=['x','a','c','y','b','z'])

cols = list('xacybz')

df = DataFrame(randn(10, len(cols)), columns=cols)

preordered = list('xyz')

new_order = preordered + list(df.columns - preordered)

df.reindex(columns=new_order)
</code>```

Body:
I want to sort some columns in large Pandas dataframe. Those columns are in the middle of df and in end. They start with "R"

columns_list = df.columns.tolist()
columns_list
Out[17]:
['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft', 'Planet', 'ExtraterrestialSupplier', 'R5', 'R2', 'R1', 'R4', 'R3', 'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R5S3', 'R5S2', 'R5S4','R1S4']

I would like to re-order like that:

['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft', 'Planet', 'ExtraterrestialSupplier', 'R1', 'R2','R3', 'R4', 'R5', 'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R1S4', 'R5S2', 'R5S3','R5S4']

Until now I did it manually:

df= df['Id', 'Name', 'Surname', 'Radius', 'Ship', 'Country', 'Spacecraft', 'Planet', 'ExtraterrestialSupplier', 'R1', 'R2','R3', 'R4', 'R5', 'S3', 'S2', 'S4', 'S1', 'S6', 'S5', 'R1S4', 'R5S2', 'R5S3','R5S4']

but new input data have more R columns and in every file it is different.

I would appreciate your advice.


问:
Where does credential management api store webauthn related data
WebAuthn includes an extension of the credential management api that allows you to work with public keys. I can go to the chrome settings and check managed passwords to see which username/passwords i have chosen to store in the browser using the credential management api. Few questions related to webauthn+credential management api combination.

What info does browser store when we successfully create a
credential?

Can we access this info from chrome settings (or some other way)?

答:
It's a loaded question, both answers from thangcao and mackie are to the point, here is a bit more details.

"Authenticator" is separate from browser -- just to emphasize this.

Authenticators could be "platform authenticator", built into client devices such as  Android phones and Windows Hello or "roaming authenticator", a separate/external piece of hardware, such as Yubikey that you can use on several devices.

Authenticator is the one to create and store "credentials", which is in public/private key scheme. Browsers can obtain public keys (meant to be public) from authenticators through credential management APIs, but never private keys.  Authentcation process is done inside authenticators, browsers simply pass along information between clients(users/app) and authenticators.

There is no equivalent "password management" on Chrome settings to manage your "WebAuthn private information", because credentials are not in browsers; more so, several browsers could use the same authenticator, with the same set of public/private key credentials.

Last but not least, your question: "Can we access this info from chrome settings (or some other way)?"

Answer:  Unless authenticator vendors build some backdoors. If that's the case, the backdoor is not for you, but for hackers to obtain all your private keys.


问:
Thread safety of AnsiString reference counting mechanism
My question is about AnsiString in Borland C++Builder 6.0

As you know, VCL's AnsiString uses reference counting.

Is that reference counting thread safe?

For example, suppose we have std::queue<AnsiString> asq;

We push an AnsiString value in that queue in thread#1, and then we do asq.pop() in thread#2. (The access to asq itself is synchronized.) Strings are not modified.
Is it possible I will have a memory leak when AnsiString's destructor is called when using AnsiString(s) that way?

答: Yes, the refcount is thread-safe.  The RTL places a lock on the refcount whenever it is being incremented and decremented. There will not be any memory leak in the scenario you describe.</p>


问:
How to put an Image in image with Android?
I need some help, because I am developing an application which I need to do that an image(2) is in other image(1), and when I move the image(1), the image(2) move to the same place.

Please, give me some information or anything to search. Thanks

答: I'd write a class which extends View.  You'll then need to overrode the onDraw method and the onTouchEvent to make it respond to user input.  This way you can do anything you like in the onDraw as you have access to the canvas directly.


答:
This is surprisingly challenging. I can't find a one-liner, and the easiest I can find is:</p>

```<code># find the R columns
mask = df.columns.str.match('^R\d*$')

# numpy array
columns = df.columns.values

# sort the R parts
columns[mask] = sorted(columns[mask])

# assign back
df = df.reindex(columns, axis=1)
</code>```

Title: How to sort only selected columns in pandas dataframe

Body:
This is surprisingly challenging. I can't find a one-liner, and the easiest I can find is:

# find the R columns
mask = df.columns.str.match('^R\d*$')

# numpy array
columns = df.columns.values

# sort the R parts
columns[mask] = sorted(columns[mask])

# assign back
df = df.reindex(columns, axis=1)


问:
Using variables in Nginx request_uri
Good morning programmers,
I'm trying to protect a file, and for that I just want to allow the request_uri that I define.
Example:

```<code>if ($request_uri !~* "d=123") {
return 403;
}
</code>```

In this case, that example works, but I would like to do something like this:

```<code>set $teste 123;
if ($request_uri !~* "d=$teste") {
return 403;
}
</code>```

So I want to make it via variables, is that possible? Cause I already tested a bunch of examples and none of them worked.

P.S: I'm using OpenResty (Nginx+Lua) so if there is a possible solution with lua I would accept it too.

答:
Assuming d is your query argument and 123 is it's value, you could try something like this:

```<code>set $teste 123;
if ($request_uri ~* "[?&]d=([^&]*)") { set $d $1; }
if ($d != $teste) {
    return 403;
}
</code>```

Title: Using variables in Nginx request_uri

Body:
Good morning programmers,
I'm trying to protect a file, and for that I just want to allow the request_uri that I define.
Example:

if ($request_uri !~* "d=123") {
return 403;
}

In this case, that example works, but I would like to do something like this:

set $teste 123;
if ($request_uri !~* "d=$teste") {
return 403;
}

So I want to make it via variables, is that possible? Cause I already tested a bunch of examples and none of them worked.

P.S: I'm using OpenResty (Nginx+Lua) so if there is a possible solution with lua I would accept it too.

Body:
Assuming d is your query argument and 123 is it's value, you could try something like this:

set $teste 123;
if ($request_uri ~* "[?&]d=([^&]*)") { set $d $1; }
if ($d != $teste) {
    return 403;
}


问:
Python-camelot (Error: GhostscriptNotFound while it is installed)
I am trying to extract tabular data from pdf using camelot and I am getting the following error.

Code:

```<code>tables = camelot.read_pdf(file_name)
</code>```

Error:

GhostscriptNotFound: Please make sure that Ghostscript is installed and available on the PATH environment variable

I have already installed Ghostscript and I have it available on the PATH environment variable.

Please find below version details:

Windows-10-10.0.17134-SP0

Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)]

NumPy 1.14.3

openCV 3.4.3

Camelot 0.3.2

Please help resolve this issue.

答:
I unistalled the 64bit and

Install the 32bit version

Add the following two paths on Windows Environment Variables:

C:\Program Files(x86)\gs\gs9.26\bin

C:\Program Files(x86)\gs\gs9.26\lib

and now it works

Body:
I am trying to extract tabular data from pdf using camelot and I am getting the following error.

Code:

tables = camelot.read_pdf(file_name)

Error:

GhostscriptNotFound: Please make sure that Ghostscript is installed and available on the PATH environment variable

I have already installed Ghostscript and I have it available on the PATH environment variable.

Please find below version details:

Windows-10-10.0.17134-SP0

Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)]

NumPy 1.14.3

openCV 3.4.3

Camelot 0.3.2

Please help resolve this issue.


问:
Kong-OIDC Plugin Installation Issue
I am installing Kong-OIDC plugin in a Kong docker container and get following error:

Error: Failed installing dependency: https://luarocks.org/lua-resty-openidc-1.6.0-1.src.rock - Failed installing dependency: https://luarocks.org/lua-resty-jwt-0.2.2-0.src.rock - Rockspec format 3.0 is not supported, please upgrade LuaRocks.

Seems like one of the underlying dependency "lua-jesty-jwt" is using Rockpsec format 3.0 version, which is not supported any more. Is there a way to get around this issue ?

答: The latest version of kong-oidc (1.1.0) did not work for me, but I was able to install an older version (1.0.1) without much issue. I did have to install an additional library "openssl-devel" (yum install openssl-devel).</p>

Title: Kong-OIDC Plugin Installation Issue


问:
jQuery - Image Uploader run parameter only if has class
I need this below image uploader to: only run the hasAlpha() parameter if:

form.uploader is a descendant of .checkalpha.

Otherwise I need the uploader to work without checking alpha for every instance of the form.uploader that isn't a descendant of .checkalpha.

In the snippet example:

The first uploader isn't a descendant of .checkalpha and needs to allow image uploads without checking hasAlpha

The second uploader is a descendant of .checkalpha and needs to allow image uploads with checking hasAlpha

$(function() {
  $(".file-drag").click(function(event) {
    $(this).siblings(".file-upload").click();
  });

  function ekUpload(item) {
    var form = $(this).find("form.uploader"),
      fileSelect = $(this).find(".file-upload"),
      fileDrag = $(this).find(".file-drag"),
      submitButton = $(this).find(".submit-button");

    function Init() {
      $(document).on("change", "form", function(e) {
        fileSelectHandler(e);
      });

      // Is XHR2 available?
      var xhr = new XMLHttpRequest();
      if (xhr.upload) {
        if (isAdvancedUpload) {
          $(document)
            .on(
              "drag dragstart dragend dragover dragenter dragleave",
              "form",
              function(e) {
                // fileDragHover(e);
                e.preventDefault();
                e.stopPropagation();
              }
            )
            .on("dragover dragenter", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              $(e.target).addClass("is-dragover");
            })
            .on("dragleave dragend drop", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              $(e.target).removeClass("is-dragover");
            })
            .on("drop dragover", "body", function(e) {
              e.preventDefault();
              e.stopPropagation();
            })
            .on("drop", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              fileSelectHandler(e);
            });
        }
      }
    }

    function fileDragHover(e) {
      e.stopPropagation();
      e.preventDefault();
      e.target.className =
        e.type === "dragover" ? "hover" : "modal-body file-upload";
    }

    async function fileSelectHandler(e) {
      var theForm = $(e.target).parent("form.uploader");

      var files = e.target.files || e.originalEvent.dataTransfer.files;

      // Process all File objects
      for (let i = 0; i < files.length; i++) {
        const f = files[i];
        if (await hasAlpha(f)) {
          console.log("Selected image is transparent");
          parseFile(f, theForm);
          uploadFile(f, theForm);
        } else {
          console.log("Selected image is not transparent");
          $(theForm)
            .closest(".checkalpha")
            .find(".response, .error-image")
            .removeClass("hidden");
          $(theForm).find(".file-image, .start").addClass("hidden");
          output(
            'Image background is not transparent'
          );
        }
      }
    }

    // Output
    function output(msg) {
      // Response
      var m = $(item).find(".message");
      m.html(msg);
    }

    function hasAlpha(file) {
      return new Promise((resolve, reject) => {
        let hasAlpha = false;
        const canvas = document.querySelector("canvas");
        const ctx = canvas.getContext("2d");

        const img = new Image();
        img.crossOrigin = "Anonymous";
        img.onerror = reject;
        img.onload = function() {
          canvas.width = img.width;
          canvas.height = img.height;

          ctx.drawImage(img, 0, 0);
          const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height)
            .data;

          for (let j = 0; j < imgData.length; j += 4) {
            if (imgData[j + 3] < 255) {
              hasAlpha = true;
              break;
            }
          }
          resolve(hasAlpha);
        };
        img.src = URL.createObjectURL(file);
      });
    }

    function parseFile(file, thisForm) {
      console.log(file.name);
      output("" + encodeURI(file.name) + "");

      // var fileType = file.type;
      // console.log(fileType);
      var imageName = file.name;

      var isGood = /\.(?=svg|jpg|png|jpeg)/gi.test(imageName);
      if (isGood) {
        $(thisForm).find(".start, .notimage").addClass("hidden");
        $(thisForm)
          .closest(".checkalpha")
          .find(".response")
          .addClass("hidden");
        $(thisForm).find(".error-image").addClass("hidden");
        $(thisForm)
          .find("label.has-advanced-upload")
          .removeClass("has-advanced-upload");
        $(thisForm)
          .find(".file-image")
          .removeClass("hidden")
          .attr("src", URL.createObjectURL(file));
      } else {
        $(thisForm).find(".error-image").removeClass("hidden");
        $(thisForm)
          .closest(".checkalpha")
          .find(".response, .file-image")
          .addClass("hidden");
        $(thisForm).find(".file-upload-form").trigger("reset");
        $(thisForm)
          .find('label[for="file-upload"]')
          .addClass("has-advanced-upload");
      }
    }

    function uploadFile(file, thisForm) {
      var xhr = new XMLHttpRequest(),
        fileSizeLimit = 1024; // in MB

      if (xhr.upload) {
        // Check if file is less than x MB
        if (file.size <= fileSizeLimit * 1024 * 1024) {
          // File received / failed
          xhr.onreadystatechange = function(e) {
            if (xhr.readyState == 4) {
              // Everything is good!
              console.log("everything is good");
            }
          };

          // Start upload
          xhr.open(
            "POST",
            $(thisForm).find(".file-upload-form").attr("action"),
            true
          );
          xhr.setRequestHeader("X-File-Name", file.name);
          xhr.setRequestHeader("X-File-Size", file.size);
          xhr.setRequestHeader("Content-Type", "multipart/form-data");
          xhr.send(file);
        } else {
          output("Please upload a smaller file (< " + fileSizeLimit + " MB).");
        }
      }
    }

    // Check for the various File API support.
    if (window.File && window.FileList && window.FileReader) {
      Init();
    } else {
      document.getElementById("file-drag").style.display = "none";
    }
  }

  var isAdvancedUpload = (function() {
    var div = document.createElement("div");
    return (
      ("draggable" in div || ("ondragstart" in div && "ondrop" in div)) &&
      "FormData" in window &&
      "FileReader" in window
    );
  })();

  if (isAdvancedUpload) {
    $(".file-drag").addClass("has-advanced-upload");
  }

  $(".uploader").each(function() {
    ekUpload(this);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css);
@import url("https://fonts.googleapis.com/css?family=Roboto");
body {
  padding: 2rem;
  background: #f8f8f8;
}

img.error-image {
  max-height: 160px;
}

.uploader {
  display: block;
  clear: both;
  margin: 0 auto;
  width: 100%;
  max-width: 600px;
}

.uploader label {
  float: left;
  clear: both;
  width: 100%;
  padding: 2rem 1.5rem;
  text-align: center;
  background: #fff;
  border-radius: 7px;
  border: 3px solid #eee;
  transition: all 0.2s ease;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  cursor: pointer;
}

.uploader label.has-advanced-upload {
  background-color: white;
  outline: 2px dashed lightgrey;
  outline-offset: -10px;
}

.uploader label:hover {
  border: 3px solid #454cad;
  box-shadow: inset 0 0 0 6px #eee;
}

.uploader label.is-dragover,
.uploader label.is-dragover:hover {
  background-color: #eef;
}

.uploader label:hover {
  border: 3px solid #454cad;
  box-shadow: inset 0 0 0 6px #eee;
}

.uploader label:hover .start i.fa {
  -webkit-transform: scale(0.8);
  transform: scale(0.8);
  opacity: 0.3;
}

.uploader .start {
  float: left;
  clear: both;
  width: 100%;
  pointer-events: none;
}

.uploader .start.hidden {
  display: none;
}

.uploader .start i.fa {
  font-size: 50px;
  margin-bottom: 1rem;
  transition: all 0.2s ease-in-out;
}

.uploader .response {
  float: left;
  clear: both;
  width: 100%;
}

.uploader .response.hidden {
  display: none;
}

.uploader .response .messages {
  margin-bottom: 0.5rem;
}

.uploader .file-image {
  display: inline;
  pointer-events: none;
  margin: 0 auto 0.5rem auto;
  width: auto;
  height: auto;
  max-width: 180px;
}

.uploader .file-image.hidden {
  display: none;
}

.uploader .notimage {
  display: block;
  float: left;
  clear: both;
  width: 100%;
}

.uploader .notimage.hidden {
  display: none;
}

.uploader progress,
.uploader .progress {
  display: inline;
  clear: both;
  margin: 0 auto;
  width: 100%;
  max-width: 180px;
  height: 8px;
  border: 0;
  border-radius: 4px;
  background-color: #eee;
  overflow: hidden;
}

.uploader .progress[value]::-webkit-progress-bar {
  border-radius: 4px;
  background-color: #eee;
}

.uploader .progress[value]::-webkit-progress-value {
  background: linear-gradient(to right, #393f90 0%, #454cad 50%);
  border-radius: 4px;
}

.uploader .progress[value]::-moz-progress-bar {
  background: linear-gradient(to right, #393f90 0%, #454cad 50%);
  border-radius: 4px;
}

.uploader input[type="file"] {
  display: none;
}

.uploader div {
  margin: 0 0 0.5rem 0;
  color: #5f6982;
}

.uploader .btn {
  display: inline-block;
  margin: 0.5rem 0.5rem 1rem 0.5rem;
  clear: both;
  font-family: inherit;
  font-weight: 700;
  font-size: 14px;
  text-decoration: none;
  text-transform: initial;
  border: none;
  border-radius: 0.2rem;
  outline: none;
  padding: 0 1rem;
  height: 36px;
  line-height: 36px;
  color: #fff;
  transition: all 0.2s ease-in-out;
  box-sizing: border-box;
  background: #454cad;
  border-color: #454cad;
  cursor: pointer;
}

.uploader input[type="file"],
.hidden {
  display: none;
}

input[type="file"].hidden {
  display: block;
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}

.warning {
  color: red;
  font-weight: bold;
}

canvas {
  position: absolute;
  top: -2000px;
}</code>```

  <form class="file-upload-form uploader">
    <input class="file-upload" type="file" name="fileUpload" accept="image/*" />

Select a file or drag here

Please select an image

  </form>

  <canvas></canvas>

  <form class="file-upload-form uploader">
    <input class="file-upload" type="file" name="fileUpload" accept="image/*" />

Select a file or drag here

Please select an image

  </form>

  <canvas></canvas>

```

答:
Check if doesn't have parent .checkalpha using .closest

```<code>    if (theForm.closest('.checkalpha').length === 0 || await hasAlpha(f)) {
</code>```

$(function() {
  $(".file-drag").click(function(event) {
    $(this).siblings(".file-upload").click();
  });

  function ekUpload(item) {
    var form = $(this).find("form.uploader"),
      fileSelect = $(this).find(".file-upload"),
      fileDrag = $(this).find(".file-drag"),
      submitButton = $(this).find(".submit-button");

    function Init() {
      $(document).on("change", "form", function(e) {
        fileSelectHandler(e);
      });

      // Is XHR2 available?
      var xhr = new XMLHttpRequest();
      if (xhr.upload) {
        if (isAdvancedUpload) {
          $(document)
            .on(
              "drag dragstart dragend dragover dragenter dragleave",
              "form",
              function(e) {
                // fileDragHover(e);
                e.preventDefault();
                e.stopPropagation();
              }
            )
            .on("dragover dragenter", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              $(e.target).addClass("is-dragover");
            })
            .on("dragleave dragend drop", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              $(e.target).removeClass("is-dragover");
            })
            .on("drop dragover", "body", function(e) {
              e.preventDefault();
              e.stopPropagation();
            })
            .on("drop", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              fileSelectHandler(e);
            });
        }
      }
    }

    function fileDragHover(e) {
      e.stopPropagation();
      e.preventDefault();
      e.target.className =
        e.type === "dragover" ? "hover" : "modal-body file-upload";
    }

    async function fileSelectHandler(e) {
      var theForm = $(e.target).parent("form.uploader");

      var files = e.target.files || e.originalEvent.dataTransfer.files;

      // Process all File objects
      for (let i = 0; i < files.length; i++) {
        const f = files[i];
        if (theForm.closest('.checkalpha').length === 0 || await hasAlpha(f)) {
          console.log("Selected image is transparent");
          parseFile(f, theForm);
          uploadFile(f, theForm);
        } else {
          console.log("Selected image is not transparent");
          $(theForm)
            .closest(".checkalpha")
            .find(".response, .error-image")
            .removeClass("hidden");
          $(theForm).find(".file-image, .start").addClass("hidden");
          output(
            'Image background is not transparent'
          );
        }
      }
    }

    // Output
    function output(msg) {
      // Response
      var m = $(item).find(".message");
      m.html(msg);
    }

    function hasAlpha(file) {
      console.log('hasAlpha');
      return new Promise((resolve, reject) => {
        let hasAlpha = false;
        const canvas = document.querySelector("canvas");
        const ctx = canvas.getContext("2d");

        const img = new Image();
        img.crossOrigin = "Anonymous";
        img.onerror = reject;
        img.onload = function() {
          canvas.width = img.width;
          canvas.height = img.height;

          ctx.drawImage(img, 0, 0);
          const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height)
            .data;

          for (let j = 0; j < imgData.length; j += 4) {
            if (imgData[j + 3] < 255) {
              hasAlpha = true;
              break;
            }
          }
          resolve(hasAlpha);
        };
        img.src = URL.createObjectURL(file);
      });
    }

    function parseFile(file, thisForm) {
      console.log(file.name);
      output("" + encodeURI(file.name) + "");

      // var fileType = file.type;
      // console.log(fileType);
      var imageName = file.name;

      var isGood = /\.(?=svg|jpg|png|jpeg)/gi.test(imageName);
      if (isGood) {
        $(thisForm).find(".start, .notimage").addClass("hidden");
        $(thisForm)
          .closest(".checkalpha")
          .find(".response")
          .addClass("hidden");
        $(thisForm).find(".error-image").addClass("hidden");
        $(thisForm)
          .find("label.has-advanced-upload")
          .removeClass("has-advanced-upload");
        $(thisForm)
          .find(".file-image")
          .removeClass("hidden")
          .attr("src", URL.createObjectURL(file));
      } else {
        $(thisForm).find(".error-image").removeClass("hidden");
        $(thisForm)
          .closest(".checkalpha")
          .find(".response, .file-image")
          .addClass("hidden");
        $(thisForm).find(".file-upload-form").trigger("reset");
        $(thisForm)
          .find('label[for="file-upload"]')
          .addClass("has-advanced-upload");
      }
    }

    function uploadFile(file, thisForm) {
      var xhr = new XMLHttpRequest(),
        fileSizeLimit = 1024; // in MB

      if (xhr.upload) {
        // Check if file is less than x MB
        if (file.size <= fileSizeLimit * 1024 * 1024) {
          // File received / failed
          xhr.onreadystatechange = function(e) {
            if (xhr.readyState == 4) {
              // Everything is good!
              console.log("everything is good");
            }
          };

          // Start upload
          xhr.open(
            "POST",
            $(thisForm).find(".file-upload-form").attr("action"),
            true
          );
          xhr.setRequestHeader("X-File-Name", file.name);
          xhr.setRequestHeader("X-File-Size", file.size);
          xhr.setRequestHeader("Content-Type", "multipart/form-data");
          xhr.send(file);
        } else {
          output("Please upload a smaller file (< " + fileSizeLimit + " MB).");
        }
      }
    }

    // Check for the various File API support.
    if (window.File && window.FileList && window.FileReader) {
      Init();
    } else {
      document.getElementById("file-drag").style.display = "none";
    }
  }

  var isAdvancedUpload = (function() {
    var div = document.createElement("div");
    return (
      ("draggable" in div || ("ondragstart" in div && "ondrop" in div)) &&
      "FormData" in window &&
      "FileReader" in window
    );
  })();

  if (isAdvancedUpload) {
    $(".file-drag").addClass("has-advanced-upload");
  }

  $(".uploader").each(function() {
    ekUpload(this);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css);
@import url("https://fonts.googleapis.com/css?family=Roboto");
body {
  padding: 2rem;
  background: #f8f8f8;
}

img.error-image {
  max-height: 160px;
}

.uploader {
  display: block;
  clear: both;
  margin: 0 auto;
  width: 100%;
  max-width: 600px;
}

.uploader label {
  float: left;
  clear: both;
  width: 100%;
  padding: 2rem 1.5rem;
  text-align: center;
  background: #fff;
  border-radius: 7px;
  border: 3px solid #eee;
  transition: all 0.2s ease;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  cursor: pointer;
}

.uploader label.has-advanced-upload {
  background-color: white;
  outline: 2px dashed lightgrey;
  outline-offset: -10px;
}

.uploader label:hover {
  border: 3px solid #454cad;
  box-shadow: inset 0 0 0 6px #eee;
}

.uploader label.is-dragover,
.uploader label.is-dragover:hover {
  background-color: #eef;
}

.uploader label:hover {
  border: 3px solid #454cad;
  box-shadow: inset 0 0 0 6px #eee;
}

.uploader label:hover .start i.fa {
  -webkit-transform: scale(0.8);
  transform: scale(0.8);
  opacity: 0.3;
}

.uploader .start {
  float: left;
  clear: both;
  width: 100%;
  pointer-events: none;
}

.uploader .start.hidden {
  display: none;
}

.uploader .start i.fa {
  font-size: 50px;
  margin-bottom: 1rem;
  transition: all 0.2s ease-in-out;
}

.uploader .response {
  float: left;
  clear: both;
  width: 100%;
}

.uploader .response.hidden {
  display: none;
}

.uploader .response .messages {
  margin-bottom: 0.5rem;
}

.uploader .file-image {
  display: inline;
  pointer-events: none;
  margin: 0 auto 0.5rem auto;
  width: auto;
  height: auto;
  max-width: 180px;
}

.uploader .file-image.hidden {
  display: none;
}

.uploader .notimage {
  display: block;
  float: left;
  clear: both;
  width: 100%;
}

.uploader .notimage.hidden {
  display: none;
}

.uploader progress,
.uploader .progress {
  display: inline;
  clear: both;
  margin: 0 auto;
  width: 100%;
  max-width: 180px;
  height: 8px;
  border: 0;
  border-radius: 4px;
  background-color: #eee;
  overflow: hidden;
}

.uploader .progress[value]::-webkit-progress-bar {
  border-radius: 4px;
  background-color: #eee;
}

.uploader .progress[value]::-webkit-progress-value {
  background: linear-gradient(to right, #393f90 0%, #454cad 50%);
  border-radius: 4px;
}

.uploader .progress[value]::-moz-progress-bar {
  background: linear-gradient(to right, #393f90 0%, #454cad 50%);
  border-radius: 4px;
}

.uploader input[type="file"] {
  display: none;
}

.uploader div {
  margin: 0 0 0.5rem 0;
  color: #5f6982;
}

.uploader .btn {
  display: inline-block;
  margin: 0.5rem 0.5rem 1rem 0.5rem;
  clear: both;
  font-family: inherit;
  font-weight: 700;
  font-size: 14px;
  text-decoration: none;
  text-transform: initial;
  border: none;
  border-radius: 0.2rem;
  outline: none;
  padding: 0 1rem;
  height: 36px;
  line-height: 36px;
  color: #fff;
  transition: all 0.2s ease-in-out;
  box-sizing: border-box;
  background: #454cad;
  border-color: #454cad;
  cursor: pointer;
}

.uploader input[type="file"],
.hidden {
  display: none;
}

input[type="file"].hidden {
  display: block;
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}

.warning {
  color: red;
  font-weight: bold;
}

canvas {
  position: absolute;
  top: -2000px;
}</code>```

  <form class="file-upload-form uploader">
    <input class="file-upload" type="file" name="fileUpload" accept="image/*" />

Select a file or drag here

Please select an image

  </form>

  <canvas></canvas>

  <form class="file-upload-form uploader">
    <input class="file-upload" type="file" name="fileUpload" accept="image/*" />

Select a file or drag here

Please select an image

  </form>

  <canvas></canvas>

```

Body:
I need this below image uploader to: only run the hasAlpha() parameter if:

form.uploader is a descendant of .checkalpha.

Otherwise I need the uploader to work without checking alpha for every instance of the form.uploader that isn't a descendant of .checkalpha.

In the snippet example:

The first uploader isn't a descendant of .checkalpha and needs to allow image uploads without checking hasAlpha

The second uploader is a descendant of .checkalpha and needs to allow image uploads with checking hasAlpha

$(function() {
  $(".file-drag").click(function(event) {
    $(this).siblings(".file-upload").click();
  });

  function ekUpload(item) {
    var form = $(this).find("form.uploader"),
      fileSelect = $(this).find(".file-upload"),
      fileDrag = $(this).find(".file-drag"),
      submitButton = $(this).find(".submit-button");

    function Init() {
      $(document).on("change", "form", function(e) {
        fileSelectHandler(e);
      });

      // Is XHR2 available?
      var xhr = new XMLHttpRequest();
      if (xhr.upload) {
        if (isAdvancedUpload) {
          $(document)
            .on(
              "drag dragstart dragend dragover dragenter dragleave",
              "form",
              function(e) {
                // fileDragHover(e);
                e.preventDefault();
                e.stopPropagation();
              }
            )
            .on("dragover dragenter", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              $(e.target).addClass("is-dragover");
            })
            .on("dragleave dragend drop", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              $(e.target).removeClass("is-dragover");
            })
            .on("drop dragover", "body", function(e) {
              e.preventDefault();
              e.stopPropagation();
            })
            .on("drop", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              fileSelectHandler(e);
            });
        }
      }
    }

    function fileDragHover(e) {
      e.stopPropagation();
      e.preventDefault();
      e.target.className =
        e.type === "dragover" ? "hover" : "modal-body file-upload";
    }

    async function fileSelectHandler(e) {
      var theForm = $(e.target).parent("form.uploader");

      var files = e.target.files || e.originalEvent.dataTransfer.files;

      // Process all File objects
      for (let i = 0; i < files.length; i++) {
        const f = files[i];
        if (await hasAlpha(f)) {
          console.log("Selected image is transparent");
          parseFile(f, theForm);
          uploadFile(f, theForm);
        } else {
          console.log("Selected image is not transparent");
          $(theForm)
            .closest(".checkalpha")
            .find(".response, .error-image")
            .removeClass("hidden");
          $(theForm).find(".file-image, .start").addClass("hidden");
          output(
            'Image background is not transparent'
          );
        }
      }
    }

    // Output
    function output(msg) {
      // Response
      var m = $(item).find(".message");
      m.html(msg);
    }

    function hasAlpha(file) {
      return new Promise((resolve, reject) => {
        let hasAlpha = false;
        const canvas = document.querySelector("canvas");
        const ctx = canvas.getContext("2d");

        const img = new Image();
        img.crossOrigin = "Anonymous";
        img.onerror = reject;
        img.onload = function() {
          canvas.width = img.width;
          canvas.height = img.height;

          ctx.drawImage(img, 0, 0);
          const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height)
            .data;

          for (let j = 0; j < imgData.length; j += 4) {
            if (imgData[j + 3] < 255) {
              hasAlpha = true;
              break;
            }
          }
          resolve(hasAlpha);
        };
        img.src = URL.createObjectURL(file);
      });
    }

    function parseFile(file, thisForm) {
      console.log(file.name);
      output("" + encodeURI(file.name) + "");

      // var fileType = file.type;
      // console.log(fileType);
      var imageName = file.name;

      var isGood = /\.(?=svg|jpg|png|jpeg)/gi.test(imageName);
      if (isGood) {
        $(thisForm).find(".start, .notimage").addClass("hidden");
        $(thisForm)
          .closest(".checkalpha")
          .find(".response")
          .addClass("hidden");
        $(thisForm).find(".error-image").addClass("hidden");
        $(thisForm)
          .find("label.has-advanced-upload")
          .removeClass("has-advanced-upload");
        $(thisForm)
          .find(".file-image")
          .removeClass("hidden")
          .attr("src", URL.createObjectURL(file));
      } else {
        $(thisForm).find(".error-image").removeClass("hidden");
        $(thisForm)
          .closest(".checkalpha")
          .find(".response, .file-image")
          .addClass("hidden");
        $(thisForm).find(".file-upload-form").trigger("reset");
        $(thisForm)
          .find('label[for="file-upload"]')
          .addClass("has-advanced-upload");
      }
    }

    function uploadFile(file, thisForm) {
      var xhr = new XMLHttpRequest(),
        fileSizeLimit = 1024; // in MB

      if (xhr.upload) {
        // Check if file is less than x MB
        if (file.size <= fileSizeLimit * 1024 * 1024) {
          // File received / failed
          xhr.onreadystatechange = function(e) {
            if (xhr.readyState == 4) {
              // Everything is good!
              console.log("everything is good");
            }
          };

          // Start upload
          xhr.open(
            "POST",
            $(thisForm).find(".file-upload-form").attr("action"),
            true
          );
          xhr.setRequestHeader("X-File-Name", file.name);
          xhr.setRequestHeader("X-File-Size", file.size);
          xhr.setRequestHeader("Content-Type", "multipart/form-data");
          xhr.send(file);
        } else {
          output("Please upload a smaller file (< " + fileSizeLimit + " MB).");
        }
      }
    }

    // Check for the various File API support.
    if (window.File && window.FileList && window.FileReader) {
      Init();
    } else {
      document.getElementById("file-drag").style.display = "none";
    }
  }

  var isAdvancedUpload = (function() {
    var div = document.createElement("div");
    return (
      ("draggable" in div || ("ondragstart" in div && "ondrop" in div)) &&
      "FormData" in window &&
      "FileReader" in window
    );
  })();

  if (isAdvancedUpload) {
    $(".file-drag").addClass("has-advanced-upload");
  }

  $(".uploader").each(function() {
    ekUpload(this);
  });
});

@import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css);
@import url("https://fonts.googleapis.com/css?family=Roboto");
body {
  padding: 2rem;
  background: #f8f8f8;
}

img.error-image {
  max-height: 160px;
}

.uploader {
  display: block;
  clear: both;
  margin: 0 auto;
  width: 100%;
  max-width: 600px;
}

.uploader label {
  float: left;
  clear: both;
  width: 100%;
  padding: 2rem 1.5rem;
  text-align: center;
  background: #fff;
  border-radius: 7px;
  border: 3px solid #eee;
  transition: all 0.2s ease;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  cursor: pointer;
}

.uploader label.has-advanced-upload {
  background-color: white;
  outline: 2px dashed lightgrey;
  outline-offset: -10px;
}

.uploader label:hover {
  border: 3px solid #454cad;
  box-shadow: inset 0 0 0 6px #eee;
}

.uploader label.is-dragover,
.uploader label.is-dragover:hover {
  background-color: #eef;
}

.uploader label:hover {
  border: 3px solid #454cad;
  box-shadow: inset 0 0 0 6px #eee;
}

.uploader label:hover .start i.fa {
  -webkit-transform: scale(0.8);
  transform: scale(0.8);
  opacity: 0.3;
}

.uploader .start {
  float: left;
  clear: both;
  width: 100%;
  pointer-events: none;
}

.uploader .start.hidden {
  display: none;
}

.uploader .start i.fa {
  font-size: 50px;
  margin-bottom: 1rem;
  transition: all 0.2s ease-in-out;
}

.uploader .response {
  float: left;
  clear: both;
  width: 100%;
}

.uploader .response.hidden {
  display: none;
}

.uploader .response .messages {
  margin-bottom: 0.5rem;
}

.uploader .file-image {
  display: inline;
  pointer-events: none;
  margin: 0 auto 0.5rem auto;
  width: auto;
  height: auto;
  max-width: 180px;
}

.uploader .file-image.hidden {
  display: none;
}

.uploader .notimage {
  display: block;
  float: left;
  clear: both;
  width: 100%;
}

.uploader .notimage.hidden {
  display: none;
}

.uploader progress,
.uploader .progress {
  display: inline;
  clear: both;
  margin: 0 auto;
  width: 100%;
  max-width: 180px;
  height: 8px;
  border: 0;
  border-radius: 4px;
  background-color: #eee;
  overflow: hidden;
}

.uploader .progress[value]::-webkit-progress-bar {
  border-radius: 4px;
  background-color: #eee;
}

.uploader .progress[value]::-webkit-progress-value {
  background: linear-gradient(to right, #393f90 0%, #454cad 50%);
  border-radius: 4px;
}

.uploader .progress[value]::-moz-progress-bar {
  background: linear-gradient(to right, #393f90 0%, #454cad 50%);
  border-radius: 4px;
}

.uploader input[type="file"] {
  display: none;
}

.uploader div {
  margin: 0 0 0.5rem 0;
  color: #5f6982;
}

.uploader .btn {
  display: inline-block;
  margin: 0.5rem 0.5rem 1rem 0.5rem;
  clear: both;
  font-family: inherit;
  font-weight: 700;
  font-size: 14px;
  text-decoration: none;
  text-transform: initial;
  border: none;
  border-radius: 0.2rem;
  outline: none;
  padding: 0 1rem;
  height: 36px;
  line-height: 36px;
  color: #fff;
  transition: all 0.2s ease-in-out;
  box-sizing: border-box;
  background: #454cad;
  border-color: #454cad;
  cursor: pointer;
}

.uploader input[type="file"],
.hidden {
  display: none;
}

input[type="file"].hidden {
  display: block;
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}

.warning {
  color: red;
  font-weight: bold;
}

canvas {
  position: absolute;
  top: -2000px;
}

  <form class="file-upload-form uploader">
    <input class="file-upload" type="file" name="fileUpload" accept="image/*" />

Select a file or drag here

Please select an image

  </form>

  <canvas></canvas>

  <form class="file-upload-form uploader">
    <input class="file-upload" type="file" name="fileUpload" accept="image/*" />

Select a file or drag here

Please select an image

  </form>

  <canvas></canvas>

Body:
Check if doesn't have parent .checkalpha using .closest

    if (theForm.closest('.checkalpha').length === 0 || await hasAlpha(f)) {

$(function() {
  $(".file-drag").click(function(event) {
    $(this).siblings(".file-upload").click();
  });

  function ekUpload(item) {
    var form = $(this).find("form.uploader"),
      fileSelect = $(this).find(".file-upload"),
      fileDrag = $(this).find(".file-drag"),
      submitButton = $(this).find(".submit-button");

    function Init() {
      $(document).on("change", "form", function(e) {
        fileSelectHandler(e);
      });

      // Is XHR2 available?
      var xhr = new XMLHttpRequest();
      if (xhr.upload) {
        if (isAdvancedUpload) {
          $(document)
            .on(
              "drag dragstart dragend dragover dragenter dragleave",
              "form",
              function(e) {
                // fileDragHover(e);
                e.preventDefault();
                e.stopPropagation();
              }
            )
            .on("dragover dragenter", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              $(e.target).addClass("is-dragover");
            })
            .on("dragleave dragend drop", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              $(e.target).removeClass("is-dragover");
            })
            .on("drop dragover", "body", function(e) {
              e.preventDefault();
              e.stopPropagation();
            })
            .on("drop", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              fileSelectHandler(e);
            });
        }
      }
    }

    function fileDragHover(e) {
      e.stopPropagation();
      e.preventDefault();
      e.target.className =
        e.type === "dragover" ? "hover" : "modal-body file-upload";
    }

    async function fileSelectHandler(e) {
      var theForm = $(e.target).parent("form.uploader");

      var files = e.target.files || e.originalEvent.dataTransfer.files;

      // Process all File objects
      for (let i = 0; i < files.length; i++) {
        const f = files[i];
        if (theForm.closest('.checkalpha').length === 0 || await hasAlpha(f)) {
          console.log("Selected image is transparent");
          parseFile(f, theForm);
          uploadFile(f, theForm);
        } else {
          console.log("Selected image is not transparent");
          $(theForm)
            .closest(".checkalpha")
            .find(".response, .error-image")
            .removeClass("hidden");
          $(theForm).find(".file-image, .start").addClass("hidden");
          output(
            '<strong class="warning">Image background is not transparent</strong>'
          );
        }
      }
    }

    // Output
    function output(msg) {
      // Response
      var m = $(item).find(".message");
      m.html(msg);
    }

    function hasAlpha(file) {
      console.log('hasAlpha');
      return new Promise((resolve, reject) => {
        let hasAlpha = false;
        const canvas = document.querySelector("canvas");
        const ctx = canvas.getContext("2d");

        const img = new Image();
        img.crossOrigin = "Anonymous";
        img.onerror = reject;
        img.onload = function() {
          canvas.width = img.width;
          canvas.height = img.height;

          ctx.drawImage(img, 0, 0);
          const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height)
            .data;

          for (let j = 0; j < imgData.length; j += 4) {
            if (imgData[j + 3] < 255) {
              hasAlpha = true;
              break;
            }
          }
          resolve(hasAlpha);
        };
        img.src = URL.createObjectURL(file);
      });
    }

    function parseFile(file, thisForm) {
      console.log(file.name);
      output("<strong>" + encodeURI(file.name) + "</strong>");

      // var fileType = file.type;
      // console.log(fileType);
      var imageName = file.name;

      var isGood = /\.(?=svg|jpg|png|jpeg)/gi.test(imageName);
      if (isGood) {
        $(thisForm).find(".start, .notimage").addClass("hidden");
        $(thisForm)
          .closest(".checkalpha")
          .find(".response")
          .addClass("hidden");
        $(thisForm).find(".error-image").addClass("hidden");
        $(thisForm)
          .find("label.has-advanced-upload")
          .removeClass("has-advanced-upload");
        $(thisForm)
          .find(".file-image")
          .removeClass("hidden")
          .attr("src", URL.createObjectURL(file));
      } else {
        $(thisForm).find(".error-image").removeClass("hidden");
        $(thisForm)
          .closest(".checkalpha")
          .find(".response, .file-image")
          .addClass("hidden");
        $(thisForm).find(".file-upload-form").trigger("reset");
        $(thisForm)
          .find('label[for="file-upload"]')
          .addClass("has-advanced-upload");
      }
    }

    function uploadFile(file, thisForm) {
      var xhr = new XMLHttpRequest(),
        fileSizeLimit = 1024; // in MB

      if (xhr.upload) {
        // Check if file is less than x MB
        if (file.size <= fileSizeLimit * 1024 * 1024) {
          // File received / failed
          xhr.onreadystatechange = function(e) {
            if (xhr.readyState == 4) {
              // Everything is good!
              console.log("everything is good");
            }
          };

          // Start upload
          xhr.open(
            "POST",
            $(thisForm).find(".file-upload-form").attr("action"),
            true
          );
          xhr.setRequestHeader("X-File-Name", file.name);
          xhr.setRequestHeader("X-File-Size", file.size);
          xhr.setRequestHeader("Content-Type", "multipart/form-data");
          xhr.send(file);
        } else {
          output("Please upload a smaller file (< " + fileSizeLimit + " MB).");
        }
      }
    }

    // Check for the various File API support.
    if (window.File && window.FileList && window.FileReader) {
      Init();
    } else {
      document.getElementById("file-drag").style.display = "none";
    }
  }

  var isAdvancedUpload = (function() {
    var div = document.createElement("div");
    return (
      ("draggable" in div || ("ondragstart" in div && "ondrop" in div)) &&
      "FormData" in window &&
      "FileReader" in window
    );
  })();

  if (isAdvancedUpload) {
    $(".file-drag").addClass("has-advanced-upload");
  }

  $(".uploader").each(function() {
    ekUpload(this);
  });
});

@import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css);
@import url("https://fonts.googleapis.com/css?family=Roboto");
body {
  padding: 2rem;
  background: #f8f8f8;
}

img.error-image {
  max-height: 160px;
}

.uploader {
  display: block;
  clear: both;
  margin: 0 auto;
  width: 100%;
  max-width: 600px;
}

.uploader label {
  float: left;
  clear: both;
  width: 100%;
  padding: 2rem 1.5rem;
  text-align: center;
  background: #fff;
  border-radius: 7px;
  border: 3px solid #eee;
  transition: all 0.2s ease;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  cursor: pointer;
}

.uploader label.has-advanced-upload {
  background-color: white;
  outline: 2px dashed lightgrey;
  outline-offset: -10px;
}

.uploader label:hover {
  border: 3px solid #454cad;
  box-shadow: inset 0 0 0 6px #eee;
}

.uploader label.is-dragover,
.uploader label.is-dragover:hover {
  background-color: #eef;
}

.uploader label:hover {
  border: 3px solid #454cad;
  box-shadow: inset 0 0 0 6px #eee;
}

.uploader label:hover .start i.fa {
  -webkit-transform: scale(0.8);
  transform: scale(0.8);
  opacity: 0.3;
}

.uploader .start {
  float: left;
  clear: both;
  width: 100%;
  pointer-events: none;
}

.uploader .start.hidden {
  display: none;
}

.uploader .start i.fa {
  font-size: 50px;
  margin-bottom: 1rem;
  transition: all 0.2s ease-in-out;
}

.uploader .response {
  float: left;
  clear: both;
  width: 100%;
}

.uploader .response.hidden {
  display: none;
}

.uploader .response .messages {
  margin-bottom: 0.5rem;
}

.uploader .file-image {
  display: inline;
  pointer-events: none;
  margin: 0 auto 0.5rem auto;
  width: auto;
  height: auto;
  max-width: 180px;
}

.uploader .file-image.hidden {
  display: none;
}

.uploader .notimage {
  display: block;
  float: left;
  clear: both;
  width: 100%;
}

.uploader .notimage.hidden {
  display: none;
}

.uploader progress,
.uploader .progress {
  display: inline;
  clear: both;
  margin: 0 auto;
  width: 100%;
  max-width: 180px;
  height: 8px;
  border: 0;
  border-radius: 4px;
  background-color: #eee;
  overflow: hidden;
}

.uploader .progress[value]::-webkit-progress-bar {
  border-radius: 4px;
  background-color: #eee;
}

.uploader .progress[value]::-webkit-progress-value {
  background: linear-gradient(to right, #393f90 0%, #454cad 50%);
  border-radius: 4px;
}

.uploader .progress[value]::-moz-progress-bar {
  background: linear-gradient(to right, #393f90 0%, #454cad 50%);
  border-radius: 4px;
}

.uploader input[type="file"] {
  display: none;
}

.uploader div {
  margin: 0 0 0.5rem 0;
  color: #5f6982;
}

.uploader .btn {
  display: inline-block;
  margin: 0.5rem 0.5rem 1rem 0.5rem;
  clear: both;
  font-family: inherit;
  font-weight: 700;
  font-size: 14px;
  text-decoration: none;
  text-transform: initial;
  border: none;
  border-radius: 0.2rem;
  outline: none;
  padding: 0 1rem;
  height: 36px;
  line-height: 36px;
  color: #fff;
  transition: all 0.2s ease-in-out;
  box-sizing: border-box;
  background: #454cad;
  border-color: #454cad;
  cursor: pointer;
}

.uploader input[type="file"],
.hidden {
  display: none;
}

input[type="file"].hidden {
  display: block;
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}

.warning {
  color: red;
  font-weight: bold;
}

canvas {
  position: absolute;
  top: -2000px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Upload  -->
<div class="">
  <form class="file-upload-form uploader">
    <input class="file-upload" type="file" name="fileUpload" accept="image/*" />
    <label for="file-upload" class="file-drag">
      <img class="file-image hidden" src="#" alt="Preview">
      <img class="error-image hidden" src="https://cdn3.iconfinder.com/data/icons/online-states/150/Snooze-512.png">
      <div class="start">
        <i class="fa fa-download" aria-hidden="true"></i>
        <div>Select a file or drag here</div>
        <div class="notimage hidden">Please select an image</div>
      </div>
      <div class="response hidden">
        <div class="message"></div>
      </div>
    </label>
  </form>
  <div class="filename"></div>
  <canvas></canvas>
</div>
<div class="checkalpha">
  <form class="file-upload-form uploader">
    <input class="file-upload" type="file" name="fileUpload" accept="image/*" />
    <label for="file-upload" class="file-drag">
      <img class="file-image hidden" src="#" alt="Preview">
      <img class="error-image hidden" src="https://cdn3.iconfinder.com/data/icons/online-states/150/Snooze-512.png">
      <div class="start">
        <i class="fa fa-download" aria-hidden="true"></i>
        <div>Select a file or drag here</div>
        <div class="notimage hidden">Please select an image</div>
      </div>
      <div class="response hidden">
        <div class="message"></div>
      </div>
    </label>
  </form>
  <div class="filename"></div>
  <canvas></canvas>
</div>


问:
Using TryGetComponent to return Child of <T>
I am writing a component script for a Unity project using c#. I want to be able get a component or any inheriting child component from a gameobject. I have been using the following:

```<code>if(Buffets[index].TryGetComponent(out Fruit fruit))
{
    ...
}
</code>```

where Buffets is a List<GameObject> which has elements in it.

The problem I have is if the GameObject element has a banana component, which inherits from fruit, the TryGetComponent will return false and also not make fruit the banana.

I was wondering if there is a function or way to get any fruit children components this way. And examples would be appreciated.

答:
var fruit = Buffets[index].GetComponent<Fruit>()
// If fruit is not null
if (!fruit)
{

}
```

Body:
I am writing a component script for a Unity project using c#. I want to be able get a component or any inheriting child component from a gameobject. I have been using the following:

if(Buffets[index].TryGetComponent(out Fruit fruit))
{
    ...
}

where Buffets is a List<GameObject> which has elements in it.

The problem I have is if the GameObject element has a banana component, which inherits from fruit, the TryGetComponent will return false and also not make fruit the banana.

I was wondering if there is a function or way to get any fruit children components this way. And examples would be appreciated.


问:
Spring Rest Controller Return Specific Fields
I've been going through my head the best way to design a JSON API using Spring MVC. As we all know IO is expensive, and thus I don't want to make the client make several API calls to get what they need. However at the same time I don't necessarily want to return the kitchen sink.

As an example I was working on a game API similar to IMDB but for video games instead.

If I returned everything connected to Game it would look something like this.

/api/game/1

```<code>{
    "id": 1,
    "title": "Call of Duty Advanced Warfare",
    "release_date": "2014-11-24",
    "publishers": [
        {
            "id": 1,
            "name": "Activision"
        }
    ],
    "developers": [
        {
            "id": 1,
            "name": "Sledge Hammer"
        }
    ],
    "platforms": [
        {
            "id": 1,
            "name": "Xbox One",
            "manufactorer": "Microsoft",
            "release_date": "2013-11-11"
        },
        {
            "id": 2,
            "name": "Playstation 4",
            "manufactorer": "Sony",
            "release_date": "2013-11-18"
        },
        {
            "id": 3,
            "name": "Xbox 360",
            "manufactorer": "Microsoft",
            "release_date": "2005-11-12"
        }
    ],
    "esrbRating": {
        "id": 1,
        "code": "T",
        "name": "Teen",
        "description": "Content is generally suitable for ages 13 and up. May contain violence, suggestive themes, crude humor, minimal blood, simulated gambling and/or infrequent use of strong language."
    },
    "reviews": [
        {
            "id": 1,
            "user_id": 111,
            "rating": 4.5,
            "description": "This game is awesome"
        }
    ]
}
</code>```

However they may not need all this information, but then again they might. Making calls for everything seems like a bad idea from I/O and performance.

I thought about doing it by specifying include parameter in the requests.

Now for example if you did not specify any includes all you would get back is the following.

```<code>{
    "id": 1,
    "title": "Call of Duty Advanced Warfare",
    "release_date": "2014-11-24"
}
</code>```

However it you want all the information your requests would look something like this.

```<code>/api/game/1?include=publishers,developers,platforms,reviews,esrbRating
</code>```

This way the client has the ability to specify how much information they want. However I'm kind of at a loss the best way to implement this using Spring MVC.

I'm thinking the controller would look something like this.

```<code>public @ResponseBody Game getGame(@PathVariable("id") long id,
    @RequestParam(value = "include", required = false) String include)) {

        // check which include params are present

        // then someone do the filtering?
}
</code>```

I'm not sure how you would optionally serialize the Game object. Is this even possible. What is the best way to approach this in Spring MVC?

FYI, I am using Spring Boot which includes Jackson for serialization.

答:
This can be done by Spring Projections. Also works fine with Kotlin.
Take a look here: https://www.baeldung.com/spring-data-jpa-projections

Body:
I've been going through my head the best way to design a JSON API using Spring MVC. As we all know IO is expensive, and thus I don't want to make the client make several API calls to get what they need. However at the same time I don't necessarily want to return the kitchen sink.

As an example I was working on a game API similar to IMDB but for video games instead.

If I returned everything connected to Game it would look something like this.

/api/game/1

{
    "id": 1,
    "title": "Call of Duty Advanced Warfare",
    "release_date": "2014-11-24",
    "publishers": [
        {
            "id": 1,
            "name": "Activision"
        }
    ],
    "developers": [
        {
            "id": 1,
            "name": "Sledge Hammer"
        }
    ],
    "platforms": [
        {
            "id": 1,
            "name": "Xbox One",
            "manufactorer": "Microsoft",
            "release_date": "2013-11-11"
        },
        {
            "id": 2,
            "name": "Playstation 4",
            "manufactorer": "Sony",
            "release_date": "2013-11-18"
        },
        {
            "id": 3,
            "name": "Xbox 360",
            "manufactorer": "Microsoft",
            "release_date": "2005-11-12"
        }
    ],
    "esrbRating": {
        "id": 1,
        "code": "T",
        "name": "Teen",
        "description": "Content is generally suitable for ages 13 and up. May contain violence, suggestive themes, crude humor, minimal blood, simulated gambling and/or infrequent use of strong language."
    },
    "reviews": [
        {
            "id": 1,
            "user_id": 111,
            "rating": 4.5,
            "description": "This game is awesome"
        }
    ]
}

However they may not need all this information, but then again they might. Making calls for everything seems like a bad idea from I/O and performance.

I thought about doing it by specifying include parameter in the requests.

Now for example if you did not specify any includes all you would get back is the following.

{
    "id": 1,
    "title": "Call of Duty Advanced Warfare",
    "release_date": "2014-11-24"
}

However it you want all the information your requests would look something like this.

/api/game/1?include=publishers,developers,platforms,reviews,esrbRating

This way the client has the ability to specify how much information they want. However I'm kind of at a loss the best way to implement this using Spring MVC.

I'm thinking the controller would look something like this.

public @ResponseBody Game getGame(@PathVariable("id") long id,
    @RequestParam(value = "include", required = false) String include)) {

        // check which include params are present

        // then someone do the filtering?
}

I'm not sure how you would optionally serialize the Game object. Is this even possible. What is the best way to approach this in Spring MVC?

FYI, I am using Spring Boot which includes Jackson for serialization.


问:
easy Qt widget to draw lines and shapes (like the tkinter canvas)?
I used to create GUIs with tkinter but i am trying to switch to PySide2 (which is way more customisable) but a can't find any PySide2 widget to replace the tkinter.canvas that i was using with tkinter.

I tried to use the QtGui.Qpainter widget but it seems very complicated compared to the tkinter canvas and I can't figure out how it works.

Did someone know an easy to use pyside widget which let me draw lines and shapes on it ?

答:
Something similar to Tkinter Canvas Widget is Qt Graphics Framework that uses QGraphicsItems similar to Canvas Items. Since you don't ask for a specific example I will implement an example from the Tkinter docs to Qt:

```<code>try:
    from Tkinter import *
except ImportError:
    from tkinter import *

master = Tk()

w = Canvas(master, width=200, height=100)
w.pack()

w.create_line(0, 0, 200, 100)
w.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))

w.create_rectangle(50, 25, 150, 75, fill="blue")

mainloop()
</code>```

```<code>import sys

from PySide2 import QtCore, QtGui, QtWidgets

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    scene = QtWidgets.QGraphicsScene(QtCore.QRectF(0, 0, 200, 100))
    view = QtWidgets.QGraphicsView(
        scene, alignment=QtCore.Qt.AlignTop | QtCore.Qt.AlignHCenter
    )
    view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
    view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
    view.setBackgroundBrush(
        QtWidgets.QApplication.style()
        .standardPalette()
        .brush(QtGui.QPalette.Background)
    )
    view.setWindowTitle("Qt")

    line1 = scene.addLine(0, 0, 200, 100)
    line2 = scene.addLine(0, 100, 200, 0)
    pen = QtGui.QPen()
    pen.setDashPattern((4, 4))
    pen.setColor(QtGui.QColor("red"))
    line2.setPen(pen)

    rect = scene.addRect(QtCore.QRectF(QtCore.QPointF(50, 25), QtCore.QPointF(150, 75)))
    rect.setBrush(QtGui.QColor("blue"))

    view.resize(200, 100)
    view.show()

    sys.exit(app.exec_())
</code>```

Equivalent items

```<code>| Tk Items  | Qt Items                                                      |
|-----------|---------------------------------------------------------------|
| arc       | QGraphicsEllipseItem, QGraphicsPathItem                       |
| bitmap    | QGraphicsPixmapItem                                           |
| image     | QGraphicsPixmapItem                                           |
| line      | QGraphicsLineItem, QGraphicsPathItem                          |
| oval      | QGraphicsEllipseItem, QGraphicsPathItem                       |
| polygon   | QGraphicsPolygonItem, QGraphicsPathItem                       |
| rectangle | QGraphicsRectItem, QGraphicsPathItem                          |
| text      | QGraphicsSimpleTextItem, QGraphicsTextItem, QGraphicsPathItem |
| window    | QGraphicsProxyWidget                                          |
</code>```

Body:
Something similar to Tkinter Canvas Widget is Qt Graphics Framework that uses QGraphicsItems similar to Canvas Items. Since you don't ask for a specific example I will implement an example from the Tkinter docs to Qt:

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

master = Tk()

w = Canvas(master, width=200, height=100)
w.pack()

w.create_line(0, 0, 200, 100)
w.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))

w.create_rectangle(50, 25, 150, 75, fill="blue")

mainloop()

import sys

from PySide2 import QtCore, QtGui, QtWidgets

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    scene = QtWidgets.QGraphicsScene(QtCore.QRectF(0, 0, 200, 100))
    view = QtWidgets.QGraphicsView(
        scene, alignment=QtCore.Qt.AlignTop | QtCore.Qt.AlignHCenter
    )
    view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
    view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
    view.setBackgroundBrush(
        QtWidgets.QApplication.style()
        .standardPalette()
        .brush(QtGui.QPalette.Background)
    )
    view.setWindowTitle("Qt")

    line1 = scene.addLine(0, 0, 200, 100)
    line2 = scene.addLine(0, 100, 200, 0)
    pen = QtGui.QPen()
    pen.setDashPattern((4, 4))
    pen.setColor(QtGui.QColor("red"))
    line2.setPen(pen)

    rect = scene.addRect(QtCore.QRectF(QtCore.QPointF(50, 25), QtCore.QPointF(150, 75)))
    rect.setBrush(QtGui.QColor("blue"))

    view.resize(200, 100)
    view.show()

    sys.exit(app.exec_())

Equivalent items

| Tk Items  | Qt Items                                                      |
|-----------|---------------------------------------------------------------|
| arc       | QGraphicsEllipseItem, QGraphicsPathItem                       |
| bitmap    | QGraphicsPixmapItem                                           |
| image     | QGraphicsPixmapItem                                           |
| line      | QGraphicsLineItem, QGraphicsPathItem                          |
| oval      | QGraphicsEllipseItem, QGraphicsPathItem                       |
| polygon   | QGraphicsPolygonItem, QGraphicsPathItem                       |
| rectangle | QGraphicsRectItem, QGraphicsPathItem                          |
| text      | QGraphicsSimpleTextItem, QGraphicsTextItem, QGraphicsPathItem |
| window    | QGraphicsProxyWidget                                          |


答:
Direct answer to the question: variables can store anonymous functions since PHP 5.3 only. It would be like this:

```<code>$option[1] = function($args) { /* do something here with $args */ };
</code>```

However in preceding versions you could achieve something similar with call_user_func(), by storing function names in your options, and then passing the chosen option as the first argument. E.g.

```<code>$option[1] = 'functionOne';
// ...
call_user_func($option[1], /* other parameters if needed */);
</code>```

However, it has a security hole, if the value is taken from user input.

Hence, more secure option would be to manually call the function depending on the chosen option with a switch statement:

```<code>switch ($option[rand()%count($option)]) {
    case 'html option 1' : functionOne(); break;
    case 'html option 2' : functionTwo(); break;
    case 'html option 3' : functionThree(); break;
    // ....
    default :  break;
}
</code>```

Title: Script to execute 1 of 2 functions randomly?

Body:
Direct answer to the question: variables can store anonymous functions since PHP 5.3 only. It would be like this:

$option[1] = function($args) { /* do something here with $args */ };

However in preceding versions you could achieve something similar with call_user_func(), by storing function names in your options, and then passing the chosen option as the first argument. E.g.

$option[1] = 'functionOne';
// ...
call_user_func($option[1], /* other parameters if needed */);

However, it has a security hole, if the value is taken from user input.

Hence, more secure option would be to manually call the function depending on the chosen option with a switch statement:

switch ($option[rand()%count($option)]) {
    case 'html option 1' : functionOne(); break;
    case 'html option 2' : functionTwo(); break;
    case 'html option 3' : functionThree(); break;
    // ....
    default :  break;
}


问:
Will a commit on a git branch follow if I do a push from another branch?
I have a git branch that I have just committed a large project on. I want to retain that project's committed work, but go make a change to a single file on another branch and push only that change up. When I do I 'git log' on the second branch though, it's still showing me the commit I did from the first branch. If I make a change to a file on the second branch and commit and push that, will my push also contain my first branch's commit as well? (Very undesired!)

Thanks!

答:
Yes, if the log shows the original commit, it's there. If you don't want that, you can

checkout the main branch.

run git checkout HEAD~1 to checkout the commit before your last commit.

check out a new branch git checkout -b my-new-branch (which will now be based on the commit-before-the-one-you-just-made) and put your other file changes on that.


问:
pandas unique values with condition
I am working with a pandas DataFrame and I need to loop trough the unique values of a column.
Such columns might contain values that i dont want to loop through, for instance ''

normally I do:

```<code>edges = [edge for edge in estados['EDGE'].unique() if edge != '']
for edge in edges:
    pass
</code>```

my question is if there is a more pandonic way to build up the list different than the conprehension list.

like:

```<code>estados['EDGE'].unique().exclude('')
</code>```

THANKS

Note:
I looked for solutions like in:
nunique excluding some values in pandas
Python pandas unique value ignoring NaN
but these solutions are even less concise as mine.

答:
You can use pd.Series.mask with pd.Series.dropna and pd.Series.unique

```<code>m = estados['EDGE']==''
estados['EDGE'].mask(m).dropna().unique()
</code>```

Or with pd.Series.notna

```<code>m = (estados['EDGE']!='') & (estados['EDGE'].notna())

estados['EDGE'][m]
</code>```

Title: pandas unique values with condition

Body:
I am working with a pandas DataFrame and I need to loop trough the unique values of a column.
Such columns might contain values that i dont want to loop through, for instance ''

normally I do:

edges = [edge for edge in estados['EDGE'].unique() if edge != '']
for edge in edges:
    pass

my question is if there is a more pandonic way to build up the list different than the conprehension list.

like:

estados['EDGE'].unique().exclude('')

THANKS

Note:
I looked for solutions like in:
nunique excluding some values in pandas
Python pandas unique value ignoring NaN
but these solutions are even less concise as mine.

Body:
You can use pd.Series.mask with pd.Series.dropna and pd.Series.unique

m = estados['EDGE']==''
estados['EDGE'].mask(m).dropna().unique()

Or with pd.Series.notna

m = (estados['EDGE']!='') & (estados['EDGE'].notna())

estados['EDGE'][m]


问:
Json-glib serialize a boolean with value false when using gobject_serialize
I'm trying to serialize the class below:

```<code>public class Person : GLib.Object {
    public string name { get; set; }
    public int age { get; set; }
    public bool alive { get; set; }

    public Person (string name, int age, bool alive = true) {
        Object (
            name: name,
            age: age,
            alive: alive
        );
    }
}

public int main () {
    var person = new Person ("mike", 33, false);
    var node = Json.gobject_serialize (person);

    string obj = Json.to_string (node, true);
    print (obj+"\n");

    return 0;
}
</code>```

While i expect the output be...

```<code>{
    "name": "mike",
    "age": 32,
    "alive": false
}
</code>```

I'm getting...

```<code>{
  "name": "mike",
  "age": 32
}
</code>```

How do i get the Boolean serialized even if the value is false?

答:
The default serialization function of json-glib doesn't serialize a property if it contains its default value. For boolean properties, this is false, unless explicitly specified otherwise.

To make sure that serialization does happen in this case, you should explicitly implement the Serializable.serialize_property() method yourself.

Body:
I'm trying to serialize the class below:

public class Person : GLib.Object {
    public string name { get; set; }
    public int age { get; set; }
    public bool alive { get; set; }

    public Person (string name, int age, bool alive = true) {
        Object (
            name: name,
            age: age,
            alive: alive
        );
    }
}

public int main () {
    var person = new Person ("mike", 33, false);
    var node = Json.gobject_serialize (person);

    string obj = Json.to_string (node, true);
    print (obj+"\n");

    return 0;
}

While i expect the output be...

{
    "name": "mike",
    "age": 32,
    "alive": false
}

I'm getting...

{
  "name": "mike",
  "age": 32
}

How do i get the Boolean serialized even if the value is false?


问:
PyMongo & Pandas - Update multiple records in MongoDB collection from dataframe by matching id
Is it possible to update multiple records in MongoDB collection from dataframe by matching id?

dataframe

```<code>    _id                                      text                            sentiment
0   5ec299fa905e038dec3c8e93    Kederi Yusof· basikal salah Najib.Tayar pa...   1
1   5ec49452bfcd4786382fe21f    Serindik.com·2 laaa mimpi UMNO.... XPM7 pul...  0
2   5ec40e8d28fb32986041df16    Newpaper24·4m1MDB: Najib Razak’s court, accuse...   -1
3   5ec44c0b255995f0522fe1ec    falseprophet· low pesuruh najib. Budak des...   1
4   5ed2ab347d23a5d56d59a730    Kamaluddin 阿列克斯 தீன்·11m-anak-najib-dalam-sena...   0
</code>```

code

```<code>updates = []
for document in db.twitter.find():
    for index, row in document.iterrows():
        if(row['_id']==a['_id']):
            updates.append(UpdateOne({'_id': row['_id']}, {'$set': {'sentiment': row['sentiment']}}, upsert=True))
            break

db.twitter.bulk_write(updates)
</code>```

But I got AttributeError: 'dict' object has no attribute 'iterrows' error message

答:
You don't need the find loop, just use iterrows() to get the data and UpdateOne to perform the upsert.

```<code>from pymongo import MongoClient, UpdateOne
import pandas as pd

db = MongoClient()['mydatabase']

data = [['ec299fa905e038dec3c8e93', 'Kederi Yusof· basikal salah Najib.Tayar pa...', 1],
        ['ec49452bfcd4786382fe21f', 'Serindik.com·2 laaa mimpi UMNO.... XPM7 pul...', 0]]

df = pd.DataFrame(data, columns=['_id', 'text', 'sentiment'])

updates = []

for _, row in df.iterrows():
    updates.append(UpdateOne({'_id': row.get('_id')}, {'$set': {'sentiment': row.get('sentiment')}}, upsert=True))

db.twitter.bulk_write(updates)
</code>```

Body:
Is it possible to update multiple records in MongoDB collection from dataframe by matching id?

dataframe

    _id                                      text                            sentiment
0   5ec299fa905e038dec3c8e93    Kederi Yusof· basikal salah Najib.Tayar pa...   1
1   5ec49452bfcd4786382fe21f    Serindik.com·2 laaa mimpi UMNO.... XPM7 pul...  0
2   5ec40e8d28fb32986041df16    Newpaper24·4m1MDB: Najib Razak’s court, accuse...   -1
3   5ec44c0b255995f0522fe1ec    falseprophet· low pesuruh najib. Budak des...   1
4   5ed2ab347d23a5d56d59a730    Kamaluddin 阿列克斯 தீன்·11m-anak-najib-dalam-sena...   0

code

updates = []
for document in db.twitter.find():
    for index, row in document.iterrows():
        if(row['_id']==a['_id']):
            updates.append(UpdateOne({'_id': row['_id']}, {'$set': {'sentiment': row['sentiment']}}, upsert=True))
            break

db.twitter.bulk_write(updates)

But I got AttributeError: 'dict' object has no attribute 'iterrows' error message

Body:
You don't need the find loop, just use iterrows() to get the data and UpdateOne to perform the upsert.

from pymongo import MongoClient, UpdateOne
import pandas as pd

db = MongoClient()['mydatabase']

data = [['ec299fa905e038dec3c8e93', 'Kederi Yusof· basikal salah Najib.Tayar pa...', 1],
        ['ec49452bfcd4786382fe21f', 'Serindik.com·2 laaa mimpi UMNO.... XPM7 pul...', 0]]

df = pd.DataFrame(data, columns=['_id', 'text', 'sentiment'])

updates = []

for _, row in df.iterrows():
    updates.append(UpdateOne({'_id': row.get('_id')}, {'$set': {'sentiment': row.get('sentiment')}}, upsert=True))

db.twitter.bulk_write(updates)