问:
how to set cluster dns to using coredns
I am deployed coredns in kubernetes cluster, but the mysql pod(ip:10.244.8.43) in the slave node is not using coredns ip as name server, I login to mysql pods and find the nameserver:

```<code>root@apollo-mysql-85fd475fc9-sjfhg:/# cat /etc/resolv.conf
nameserver 10.96.0.10
search sre.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
</code>```

but the coredns (v1.6.7) pod's ip is: 10.244.6.34, where is the problem? what should I do to make coredns work to my cluster pods? and this is my pod define :

```<code>kind: Deployment
apiVersion: apps/v1
metadata:
  name: apollo-mysql
  namespace: sre
  selfLink: /apis/apps/v1/namespaces/sre/deployments/apollo-mysql
  uid: b7a2f852-894d-4686-816c-21737535dbea
  resourceVersion: '498210'
  generation: 42
  creationTimestamp: '2020-05-30T11:27:09Z'
  annotations:
    deployment.kubernetes.io/revision: '4'
    kubectl.kubernetes.io/last-applied-configuration: >
      {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"name":"apollo-mysql","namespace":"sre"},"spec":{"selector":{"matchLabels":{"app":"apollo-mysql"}},"strategy":{"type":"Recreate"},"template":{"metadata":{"labels":{"app":"apollo-mysql"}},"spec":{"containers":[{"env":[{"name":"MYSQL_ROOT_PASSWORD","value":"gl4LucnXwLeLwAd29QqJn4"}],"image":"mysql:5.7","name":"mysql","ports":[{"containerPort":3306,"name":"mysql"}],"volumeMounts":[{"mountPath":"/var/lib/mysql","name":"apollo-mysql-persistent-storage"}]}],"volumes":[{"name":"apollo-mysql-persistent-storage","persistentVolumeClaim":{"claimName":"apollo-mysql-pv-claim"}}]}}}}
spec:
  replicas: 1
  selector:
    matchLabels:
      app: apollo-mysql
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: apollo-mysql
    spec:
      volumes:
        - name: apollo-mysql-persistent-storage
          persistentVolumeClaim:
            claimName: apollo-mysql-pv-claim
      containers:
        - name: mysql
          image: 'mysql:5.7'
          ports:
            - name: mysql
              containerPort: 3306
              protocol: TCP
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: gl4LucnXwLeLwAd29QqJn4
          resources: {}
          volumeMounts:
            - name: apollo-mysql-persistent-storage
              mountPath: /var/lib/mysql
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      dnsPolicy: ClusterFirst
      securityContext: {}
      schedulerName: default-scheduler
  strategy:
    type: Recreate
  revisionHistoryLimit: 10
  progressDeadlineSeconds: 600
status:
  observedGeneration: 42
  replicas: 1
  updatedReplicas: 1
  readyReplicas: 1
  availableReplicas: 1
  conditions:
    - type: Progressing
      status: 'True'
      lastUpdateTime: '2020-05-31T03:34:11Z'
      lastTransitionTime: '2020-05-30T11:38:19Z'
      reason: NewReplicaSetAvailable
      message: ReplicaSet "apollo-mysql-5f5c49c448" has successfully progressed.
    - type: Available
      status: 'True'
      lastUpdateTime: '2020-05-31T08:34:56Z'
      lastTransitionTime: '2020-05-31T08:34:56Z'
      reason: MinimumReplicasAvailable
      message: Deployment has minimum availability.
</code>```

答:
When we spin up a pod on Kubernetes Kubelet writes kube-dns service IP (not pod IP) in container's <code>/etc/resolv.conf</code> file. </p>

```<code>kubectl get svc -n kube-system
NAME       TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)                  AGE
kube-dns   ClusterIP   10.96.0.10   <none>        53/UDP,53/TCP,9153/TCP   29d
</code>```

Title: how to set cluster dns to using coredns

Body:
I am deployed coredns in kubernetes cluster, but the mysql pod(ip:10.244.8.43) in the slave node is not using coredns ip as name server, I login to mysql pods and find the nameserver:

root@apollo-mysql-85fd475fc9-sjfhg:/# cat /etc/resolv.conf
nameserver 10.96.0.10
search sre.svc.cluster.local svc.cluster.local cluster.local
options ndots:5

but the coredns (v1.6.7) pod's ip is: 10.244.6.34, where is the problem? what should I do to make coredns work to my cluster pods? and this is my pod define :

kind: Deployment
apiVersion: apps/v1
metadata:
  name: apollo-mysql
  namespace: sre
  selfLink: /apis/apps/v1/namespaces/sre/deployments/apollo-mysql
  uid: b7a2f852-894d-4686-816c-21737535dbea
  resourceVersion: '498210'
  generation: 42
  creationTimestamp: '2020-05-30T11:27:09Z'
  annotations:
    deployment.kubernetes.io/revision: '4'
    kubectl.kubernetes.io/last-applied-configuration: >
      {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"name":"apollo-mysql","namespace":"sre"},"spec":{"selector":{"matchLabels":{"app":"apollo-mysql"}},"strategy":{"type":"Recreate"},"template":{"metadata":{"labels":{"app":"apollo-mysql"}},"spec":{"containers":[{"env":[{"name":"MYSQL_ROOT_PASSWORD","value":"gl4LucnXwLeLwAd29QqJn4"}],"image":"mysql:5.7","name":"mysql","ports":[{"containerPort":3306,"name":"mysql"}],"volumeMounts":[{"mountPath":"/var/lib/mysql","name":"apollo-mysql-persistent-storage"}]}],"volumes":[{"name":"apollo-mysql-persistent-storage","persistentVolumeClaim":{"claimName":"apollo-mysql-pv-claim"}}]}}}}
spec:
  replicas: 1
  selector:
    matchLabels:
      app: apollo-mysql
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: apollo-mysql
    spec:
      volumes:
        - name: apollo-mysql-persistent-storage
          persistentVolumeClaim:
            claimName: apollo-mysql-pv-claim
      containers:
        - name: mysql
          image: 'mysql:5.7'
          ports:
            - name: mysql
              containerPort: 3306
              protocol: TCP
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: gl4LucnXwLeLwAd29QqJn4
          resources: {}
          volumeMounts:
            - name: apollo-mysql-persistent-storage
              mountPath: /var/lib/mysql
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      dnsPolicy: ClusterFirst
      securityContext: {}
      schedulerName: default-scheduler
  strategy:
    type: Recreate
  revisionHistoryLimit: 10
  progressDeadlineSeconds: 600
status:
  observedGeneration: 42
  replicas: 1
  updatedReplicas: 1
  readyReplicas: 1
  availableReplicas: 1
  conditions:
    - type: Progressing
      status: 'True'
      lastUpdateTime: '2020-05-31T03:34:11Z'
      lastTransitionTime: '2020-05-30T11:38:19Z'
      reason: NewReplicaSetAvailable
      message: ReplicaSet "apollo-mysql-5f5c49c448" has successfully progressed.
    - type: Available
      status: 'True'
      lastUpdateTime: '2020-05-31T08:34:56Z'
      lastTransitionTime: '2020-05-31T08:34:56Z'
      reason: MinimumReplicasAvailable
      message: Deployment has minimum availability.

Body:
When we spin up a pod on Kubernetes Kubelet writes kube-dns service IP (not pod IP) in container's /etc/resolv.conf file.

kubectl get svc -n kube-system
NAME       TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)                  AGE
kube-dns   ClusterIP   10.96.0.10   <none>        53/UDP,53/TCP,9153/TCP   29d


来源: stackexchange

问:
Postgresql | How to attribute index updation time in Sql Inserts
How can we attribute time taken in index updation process while executing an insert statement in postgresql?</p>

答:
You can use
EXPLAIN (ANALYZE)
Be carefull, as this is sql query will be executed
If you don't want it - use ROLLBACK like this:</p>

```<code>BEGIN;

EXPLAIN ANALYZE <query>

ROLLBACK;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use
EXPLAIN (ANALYZE)
Be carefull, as this is sql query will be executed
If you don't want it - use ROLLBACK like this:

BEGIN;

EXPLAIN ANALYZE <query>

ROLLBACK;


问:
How can I scrape "view" count of a comment with BeautifulSoup?
I'm trying to scrape customer complaint data on a website. I can get the headline and date but cannot figure out how to get the view count.

This is the code to get the headline:

```<code>headers = {'User-Agent':'Mozilla/5.0'}

complaints = []
time = []

for i in range(100):
  r = requests.get(f'https://www.sikayetvar.com/sikayetler?brand=bosch&page={i}')
  soup = bs(r.content, 'html.parser')
  complaints += soup.find_all('h5', {"class":"card-title"})
  time += soup.find_all('span', {"class":"info-icn time-tooltip"})
</code>```

The count of the complaints:

I try to get the number "479" with this code:

```<code>site = 'https://www.sikayetvar.com/sikayetler?brand=bosch'

r = requests.get(site)
soup = bs(r.content, 'html.parser')
time = soup.find_all('span', {"class":"count"})
</code>```

It returns:

```<code>print(time[0])
<span class="count">-</span>

print(time[0].text)
-
</code>```

I just get "-" instead of "479". Can anyone tell me what I'm doing wrong or a way to get that number?

Thanks in advance

答: Probably there are other elements with the class count. Try using the {"class": "js-view-count"} to get the elements. This will have a span in it which has the count.

Body:
I'm trying to scrape customer complaint data on a website. I can get the headline and date but cannot figure out how to get the view count.

This is the code to get the headline:

headers = {'User-Agent':'Mozilla/5.0'}

complaints = []
time = []

for i in range(100):
  r = requests.get(f'https://www.sikayetvar.com/sikayetler?brand=bosch&page={i}')
  soup = bs(r.content, 'html.parser')
  complaints += soup.find_all('h5', {"class":"card-title"})
  time += soup.find_all('span', {"class":"info-icn time-tooltip"})

The count of the complaints:

I try to get the number "479" with this code:

site = 'https://www.sikayetvar.com/sikayetler?brand=bosch'

r = requests.get(site)
soup = bs(r.content, 'html.parser')
time = soup.find_all('span', {"class":"count"})

It returns:

print(time[0])
-

print(time[0].text)
-

I just get "-" instead of "479". Can anyone tell me what I'm doing wrong or a way to get that number?

Thanks in advance


问:
How to add numbers for a string sentence in Java?
I want to add numbers using Java.

For example, the sentence is given String: "My age is 50, and your age is under 30." If I want to add 5 to the sentence, it should be like
"My age is 55, and your age is under 35."

The restriction is the sentence is given, so you need to extract numbers from the sentence and add the numbers to the original sentence.

I was trying to split by space (" ") and try to add numbers after that.
But I don't know how to substitute numbers with the original sentence.

I am confused since it has comma when I am trying to split by " " and even if you can extract all the numbers from the sentence, I am not sure how can I get back to numbers to string.

```<code>public class Main {

public static Pattern pattern = Pattern.compile("\\d+");

public static String addNumber(String str, int n) {

    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        String theAge = matcher.group(0);
        int newAge = Integer.parseInt(theAge) + n;
    }

    String addSentence = str;

    return addSentence;
}

public static void main(String[] args) {
    String testString = "My age is 50, and your age is under 30.";
    String testString2 = "My age is 50, and your age is under 30 and my friend age is 44.";

    String newSent = addNumber(testString, 5);
    // -> should be "My age is 55, and your age is under 35.
    String newSent2 = addNumber(testString2, 10);
    // -> should be "My age is 60, and your age is under 40 and my friend age is 54.";

}
</code>```

}
enter code here

答:
You can format your string using printf(),

```<code>int myAge = 50;
int yourAge = 30;

System.out.printf("My age is %d, and your age is under %d.", myAge, yourAge);

// add five
myAge += 5;
yourAge += 5;

System.out.printf("My age is %d, and your age is under %d.", myAge, yourAge);
</code>```

The output will be,

```<code>"My age is 50, and your age is under 30."
"My age is 55, and your age is under 35."
</code>```

Body:
I want to add numbers using Java.

For example, the sentence is given String: "My age is 50, and your age is under 30." If I want to add 5 to the sentence, it should be like
"My age is 55, and your age is under 35."

The restriction is the sentence is given, so you need to extract numbers from the sentence and add the numbers to the original sentence.

I was trying to split by space (" ") and try to add numbers after that.
But I don't know how to substitute numbers with the original sentence.

I am confused since it has comma when I am trying to split by " " and even if you can extract all the numbers from the sentence, I am not sure how can I get back to numbers to string.

public class Main {

public static Pattern pattern = Pattern.compile("\\d+");

public static String addNumber(String str, int n) {

    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        String theAge = matcher.group(0);
        int newAge = Integer.parseInt(theAge) + n;
    }

    String addSentence = str;

    return addSentence;
}

public static void main(String[] args) {
    String testString = "My age is 50, and your age is under 30.";
    String testString2 = "My age is 50, and your age is under 30 and my friend age is 44.";

    String newSent = addNumber(testString, 5);
    // -> should be "My age is 55, and your age is under 35.
    String newSent2 = addNumber(testString2, 10);
    // -> should be "My age is 60, and your age is under 40 and my friend age is 54.";

}

}
enter code here

Body:
You can format your string using printf(),

int myAge = 50;
int yourAge = 30;

System.out.printf("My age is %d, and your age is under %d.", myAge, yourAge);

// add five
myAge += 5;
yourAge += 5;

System.out.printf("My age is %d, and your age is under %d.", myAge, yourAge);

The output will be,

"My age is 50, and your age is under 30."
"My age is 55, and your age is under 35."


问:
Send put request with array of dictionaries with Alamofire
I am trying to send JSON put body request with the following. When I entered the JSON by hand as a string, it worked, but when I try to create it through code, it fails:

```<code>struct Item: Codable {
    let name: String
    let price: Float
}

struct User: Codable {
    let username: String
    let fullName: String
}

let item = Item(name: "pen", price: 0)
let itemData = try! JSONEncoder().encode(item)
let itemString = String(data: itemData, encoding: .utf8)!

let user = User(username: "Dave", fullName: "Dave Grohl")
let userData = try! JSONEncoder().encode(user)
let userString = String(data: userData, encoding: .utf8)!

let parametersJson: [String: Any] = [
    "item": itemString,
    "user": userString
]
</code>```

The Alamofire request is as follows:

```<code>AF.request("http://127.0.0.1:8000/items/10",
       method: .put,
       parameters: parametersJson,
       encoding: JSONEncoding.default)
.response { (response) in
    debugPrint(response)
</code>```

What I get as a response:

```<code>[Response Body]:
{"detail":[{"loc":["body","item"],"msg":"value is not a valid dict","type":"type_error.dict"},{"loc":["body","user"],"msg":"value is not a valid dict","type":"type_error.dict"}]}
</code>```

At the same time, when I use the following as parameters, it works fine:

```<code>let parameters: [String: [String:String]] = [
"item": [
    "name": "pen",
    "price": "0"
],
"user": [
    "username": "dave",
    "full_name": "Dave Grohl"
]
</code>```

Any help is really appreciated.

#

As per Frankenstein comment, I have changed the User struct to correct for the mismatch between fullName and full_name, but still get the same error. When I debug print the request I get the following:

```<code>[Request Body]:
{"user":"{\"username\":\"Dave\",\"full_name\":\"Dave Grohl\"}","item":"{\"name\":\"pen\",\"price\":0}"}
</code>```

And this is what I get, when parameters (as defined above as a string) are used:

```<code>[Request Body]:
{"item":{"name":"pen","price":"0"},"user":{"username":"dave","full_name":"Dave Grohl"}}
</code>```

答:
Update: The major issue here is that you're not formatting your JSON properly, Here is what you need to do:

struct Item: Codable {
    let name: String
    let price: Float
}
struct User: Codable {
    let username: String
    let fullName: String

    enum CodingKeys: String, CodingKey {
        case username
        case fullName = "full_name"
    }
}
struct Parameter: Codable {
    let user: User
    let item: Item
}
let item = Item(name: "pen", price: 0)
let user = User(username: "Dave", fullName: "Dave Grohl")
let parameter = Parameter(user: user, item: item)

let data = try! JSONEncoder().encode(parameter)

var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.httpBody = data
AF.request(request).response { (response) in
    debugPrint(response)
    //...
}
```

<p>Previous Answer: It's because your parameters have a mismatch in <code>User</code>. You can fix it by just modifying the <code>User</code> struct as follows:</p>

<pre class="lang-swift prettyprint-override"><code>struct User: Codable {
    let username: String
    let fullName: String

    enum CodingKeys: String, CodingKey {
        case username
        case fullName = "full_name"
    }
}
</code>```

An alternate approach is to use a custom JSONDecoder and set it's keyEncodingStrategy to convertToSnakeCase, like this:

let user = User(username: "Dave", fullName: "Dave Grohl")
let decoder = JSONEncoder()
decoder.keyEncodingStrategy = .convertToSnakeCase
let userData = try! decoder.encode(user)
let userString = String(data: userData, encoding: .utf8)!
```

Note: Usually the JSON format contains both snake-case and camel-case and hence using the first approach is the better choice in my opinion. But both would work.

Body:
I am trying to send JSON put body request with the following. When I entered the JSON by hand as a string, it worked, but when I try to create it through code, it fails:

struct Item: Codable {
    let name: String
    let price: Float
}

struct User: Codable {
    let username: String
    let fullName: String
}

let item = Item(name: "pen", price: 0)
let itemData = try! JSONEncoder().encode(item)
let itemString = String(data: itemData, encoding: .utf8)!

let user = User(username: "Dave", fullName: "Dave Grohl")
let userData = try! JSONEncoder().encode(user)
let userString = String(data: userData, encoding: .utf8)!

let parametersJson: [String: Any] = [
    "item": itemString,
    "user": userString
]

The Alamofire request is as follows:

AF.request("http://127.0.0.1:8000/items/10",
       method: .put,
       parameters: parametersJson,
       encoding: JSONEncoding.default)
.response { (response) in
    debugPrint(response)

What I get as a response:

[Response Body]:
{"detail":[{"loc":["body","item"],"msg":"value is not a valid dict","type":"type_error.dict"},{"loc":["body","user"],"msg":"value is not a valid dict","type":"type_error.dict"}]}

At the same time, when I use the following as parameters, it works fine:

let parameters: [String: [String:String]] = [
"item": [
    "name": "pen",
    "price": "0"
],
"user": [
    "username": "dave",
    "full_name": "Dave Grohl"
]

Any help is really appreciated.

#

As per Frankenstein comment, I have changed the User struct to correct for the mismatch between fullName and full_name, but still get the same error. When I debug print the request I get the following:

[Request Body]:
{"user":"{\"username\":\"Dave\",\"full_name\":\"Dave Grohl\"}","item":"{\"name\":\"pen\",\"price\":0}"}

And this is what I get, when parameters (as defined above as a string) are used:

[Request Body]:
{"item":{"name":"pen","price":"0"},"user":{"username":"dave","full_name":"Dave Grohl"}}

Body:
Update: The major issue here is that you're not formatting your JSON properly, Here is what you need to do:

struct Item: Codable {
    let name: String
    let price: Float
}
struct User: Codable {
    let username: String
    let fullName: String

    enum CodingKeys: String, CodingKey {
        case username
        case fullName = "full_name"
    }
}
struct Parameter: Codable {
    let user: User
    let item: Item
}
let item = Item(name: "pen", price: 0)
let user = User(username: "Dave", fullName: "Dave Grohl")
let parameter = Parameter(user: user, item: item)

let data = try! JSONEncoder().encode(parameter)

var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.httpBody = data
AF.request(request).response { (response) in
    debugPrint(response)
    //...
}

Previous Answer: It's because your parameters have a mismatch in User. You can fix it by just modifying the User struct as follows:

struct User: Codable {
    let username: String
    let fullName: String

    enum CodingKeys: String, CodingKey {
        case username
        case fullName = "full_name"
    }
}

An alternate approach is to use a custom JSONDecoder and set it's keyEncodingStrategy to convertToSnakeCase, like this:

let user = User(username: "Dave", fullName: "Dave Grohl")
let decoder = JSONEncoder()
decoder.keyEncodingStrategy = .convertToSnakeCase
let userData = try! decoder.encode(user)
let userString = String(data: userData, encoding: .utf8)!

Note: Usually the JSON format contains both snake-case and camel-case and hence using the first approach is the better choice in my opinion. But both would work.


问:
Slicing a multiindex on Pandas
I've got a dataframe with a multiindex of the form:

```<code>(label, date)
</code>```

where label is a string and date is a DateTimeIndex.

I want to slice my dataframe by date; say for example, I want to get all the rows between 2007 and 2009:

```<code>df.loc[:, '2007':'2009']
</code>```

It seems like the second part (where I've put the date) is actually slicing the column.

How do I slice on date?

Title: Slicing a multiindex on Pandas

Body:
I've got a dataframe with a multiindex of the form:

(label, date)

where label is a string and date is a DateTimeIndex.

I want to slice my dataframe by date; say for example, I want to get all the rows between 2007 and 2009:

df.loc[:, '2007':'2009']

It seems like the second part (where I've put the date) is actually slicing the column.

How do I slice on date?

Body:
You can check partial string indexing:

DatetimeIndex partial string indexing also works on a DataFrame with a MultiIndex:

df = pd.DataFrame(np.random.randn(20, 1),
                  columns=['A'],
                  index=pd.MultiIndex.from_product(
                            [['a', 'b'], pd.date_range('20050101', periods=10, freq='10M'),
                             ]))
idx = pd.IndexSlice
df1 = df.loc[idx[:, '2007':'2009'], :]
print (df1)
                     A
a 2007-07-31  0.325027
  2008-05-31 -1.307117
  2009-03-31 -0.556454
b 2007-07-31  1.808920
  2008-05-31  1.245404
  2009-03-31 -0.425046

Another idea is use loc with axis=0 parameter:

df1 = df.loc(axis=0)[:, '2007':'2009']
print (df1)
                     A
a 2007-07-31  0.325027
  2008-05-31 -1.307117
  2009-03-31 -0.556454
b 2007-07-31  1.808920
  2008-05-31  1.245404
  2009-03-31 -0.425046


问:
How to enable Apple Sign in for existing app? "Provisioning profile doesn't support the Sign In with Apple capability"
I am trying to enable Apple Sign in for existing app, but am getting "Provisioning profile doesn't support the Sign In with Apple capability" and "Provisioning profile doesn't include the com.apple.developer.applesignin entitlement."

Following Apple docs and other sources I've attempted several things.  In Xcode I tried:

and then in the Apple Developer Account for our app I tried enabling Sign In for our App ID under the Identifiers section.

So a major issue seems to be that I cannot designate an App ID as the primary app.  Something else recommended to try in docs is to create a Key that in the Developer Account, but I don't think this is required. I attempt this like so:

I guess my immediate issue is how to resolve the error listed for my provisioning profiles in Xcode.  My app builds fine until I try to add the Capability for "Sign in with Apple".  But it looks like the reason that may fail is because there is no Primary App ID, and assigning one is disabled.

Notice this Stack Overflow question which does directly address one of my issues, but the answers are not effective for me.

UPDATE:

By turning on "Automatically manage signing" in the Signing & Capabilities section of my project in Xcode I was able to get different Provisioning profile errors than seen in the first pic, errors I was able to resolve by deleting the profiles, generating new ones, and modifying other settings in the project, and then was able to successfully turn on Apple Sign in as a capability.  If you have a better solution, feel free to provide an answer before Bounty deadline expires.

答:
If you are enabling it for existing app and none of the other Apple IDs in your developer portal is enabled with Sign In With Apple, can only enable it for primary App ID. I think you got confused with the UI, when you were trying to Edit your App ID Configuration and checked Sign In With Apple you don't have to click on Edit, just need to scroll up to the page and click save.

Because it's your first app id that you are going to enable this feature. It will always be Enable as primary App Id and yes UI is confusing and it will let you click on Edit button and then both options are disabled on the next page.

Now Sign In With Apple is enabled for one of your app id, so if you try to enable it for any other app id in your developer portal and click on Edit button you will see both options enabled Enable as primary App Id and Group with existing app id.


问:
How to change the iOS system dialogs like location permission to Portuguese in Flutter?
We developed an app using Flutter and Apple refused it because the app is in Brazilian Portuguese language but the permission dialogs like use location permission or notifications permissions are in English.

We tried installing the flutter_localizations package and changing the info.plist. These are the changes we made:

```<code>Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'My App',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: AppStateContainer.of(context).page,
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [Locale('pt', 'BR'),],
    );
  }
</code>```

On info.plist:

```<code><key>CFBundleLocalizations</key>
    <array>
        <string>pt_BR</string>
    </array>
</code>```

None of these steps worked. On iOS the permission dialogs are still in English. The iOS device that we are testing is in Portuguese and the region is Brazil.

答:
Few easy steps:

Open Xcode

Create a Strings file in ios/Runner called "InfoPlist.strings"

Click on Runner then info. Here you see "Localizations", add Brazilian Portuguese and select the new file you created before. This will generate two different files under InfoPlist.strings, one for English and one for Brazilian Portuguese.

Now in each of these file you have to add the KEY and the VALUE in that language, for example in InfoPlist.strings (English):

```<code>NSCameraUsageDescription = "Need to upload image for your profile image";

NSLocationAlwaysUsageDescription = "Need to access to location to show you near venues";
</code>```

Then iOS will automatically look into these files for the localized values. You don't need to do nothing more, so simply look in Info.plist what keys you need to localize and copy those in the new files.

Body:
We developed an app using Flutter and Apple refused it because the app is in Brazilian Portuguese language but the permission dialogs like use location permission or notifications permissions are in English.

We tried installing the flutter_localizations package and changing the info.plist. These are the changes we made:

Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'My App',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: AppStateContainer.of(context).page,
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [Locale('pt', 'BR'),],
    );
  }

On info.plist:

<key>CFBundleLocalizations</key>
    <array>
        <string>pt_BR</string>
    </array>

None of these steps worked. On iOS the permission dialogs are still in English. The iOS device that we are testing is in Portuguese and the region is Brazil.

Body:
Few easy steps:

Open Xcode

Create a Strings file in ios/Runner called "InfoPlist.strings"

Click on Runner then info. Here you see "Localizations", add Brazilian Portuguese and select the new file you created before. This will generate two different files under InfoPlist.strings, one for English and one for Brazilian Portuguese.

Now in each of these file you have to add the KEY and the VALUE in that language, for example in InfoPlist.strings (English):

NSCameraUsageDescription = "Need to upload image for your profile image";

NSLocationAlwaysUsageDescription = "Need to access to location to show you near venues";

Then iOS will automatically look into these files for the localized values. You don't need to do nothing more, so simply look in Info.plist what keys you need to localize and copy those in the new files.


问:
Hiding Systembar in android 3.0(honeycomb)
How do I hide the system bar in android 3.0(honeycomb)?</p>

答:
I tested some ways to kill system bar:

Kill by adb shell: - su; ps, look for com.android.systemui; kill  - success, sys-bar removed.

Settings, "Sytem UI" force stop - success, sys-bar removed.

Root explorer, delete /system/app/systemui.apk - got circle of error messages "com.android.systemui crashed, blabla...". Reboot, tablet started without system bar, no any errors, so success.

My app:
Code:
android.os.Process.killProcess(android.os.Process.getUidForName("com.android.systemui"));
failed, as expected, because my app can not kill process started by another app.

My app:
permission - android.permission.KILL_BACKGROUND_PROCESSES
Code:
final Context context =  getApplicationContext();

servMng = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

servMng.killBackgroundProcesses("com.android.systemui");

Failed, no idea why.

Run script in my app to execute "ps", look for PID and execute "kill", not tested.

ContentLicense: CC BY-SA 3.0


问:
How to replace characters by strtok function - C?
I really want to change all spaces ' ' in my char array for NULL -

```<code>#include <string.h>

void ReplaceCharactersInString(char *pcString, char *cOldChar, char *cNewChar) {
    char *p = strtok(pcString, cOldChar);
    strcpy(pcString, p);
    while (p != NULL) {
        strcat(pcString, p);
        p = strtok(cNewChar, cOldChar);
    }
}

int main() {
    char pcString[] = "I am testing";
    ReplaceCharactersInString(pcString, " ", NULL);
    printf(pcString);
}
</code>```

OUTPUT: Iamtesting

If I simply put the printf(p) function before:

```<code>p = strtok(cNewChar, cOldChar);
</code>```

In the result I  have what I need - but the problem is how to store it in pcString (directly)?

Or there is maybe a better solution to simply do it?

答:
strcat strcpy should not be used when the source and destination overlap in memory.

Iterate through the array and replace the matching character with the desired character.

Since zeros are part of the string, printf will stop at the first zero and strlen can't be used for the length to print. sizeof can be used as pcString is defined in the same scope.

Note that ReplaceCharactersInString would not work a second time as it would stop at the first zero. The function could be written to accept a length parameter and loop using the length.

```<code>#include <stdio.h>
#include <stdlib.h>

void ReplaceCharactersInString(char *pcString, char cOldChar,char cNewChar){
    while ( pcString && *pcString) {//not NULL and not zero
        if ( *pcString == cOldChar) {//match
            *pcString = cNewChar;//replace
        }
        ++pcString;//advance to next character
    }
}

int main ( void) {
    char pcString[] = "I am testing";
    ReplaceCharactersInString ( pcString, ' ', '\0');
    for ( int each = 0; each < sizeof pcString; ++each) {
        printf ( "pcString[%02d] = int:%-4d char:%c\n", each, pcString[each], pcString[each]);
    }
    return 0;
}
</code>```

Body:
I really want to change all spaces ' ' in my char array for NULL -

#include <string.h>

void ReplaceCharactersInString(char *pcString, char *cOldChar, char *cNewChar) {
    char *p = strtok(pcString, cOldChar);
    strcpy(pcString, p);
    while (p != NULL) {
        strcat(pcString, p);
        p = strtok(cNewChar, cOldChar);
    }
}

int main() {
    char pcString[] = "I am testing";
    ReplaceCharactersInString(pcString, " ", NULL);
    printf(pcString);
}

OUTPUT: Iamtesting

If I simply put the printf(p) function before:

p = strtok(cNewChar, cOldChar);

In the result I  have what I need - but the problem is how to store it in pcString (directly)?

Or there is maybe a better solution to simply do it?

Body:
strcat strcpy should not be used when the source and destination overlap in memory.

Iterate through the array and replace the matching character with the desired character.

Since zeros are part of the string, printf will stop at the first zero and strlen can't be used for the length to print. sizeof can be used as pcString is defined in the same scope.

Note that ReplaceCharactersInString would not work a second time as it would stop at the first zero. The function could be written to accept a length parameter and loop using the length.

#include <stdio.h>
#include <stdlib.h>

void ReplaceCharactersInString(char *pcString, char cOldChar,char cNewChar){
    while ( pcString && *pcString) {//not NULL and not zero
        if ( *pcString == cOldChar) {//match
            *pcString = cNewChar;//replace
        }
        ++pcString;//advance to next character
    }
}

int main ( void) {
    char pcString[] = "I am testing";
    ReplaceCharactersInString ( pcString, ' ', '\0');
    for ( int each = 0; each < sizeof pcString; ++each) {
        printf ( "pcString[%02d] = int:%-4d char:%c\n", each, pcString[each], pcString[each]);
    }
    return 0;
}


问:
what is the default pingTimeout and pingInterval in socket.io
I just want to know what is the default value of pingTimeout and PingInterval in socket.io? I read in the docs the values to be:

```<code>  pingTimeout (Number): how many ms without a pong packet to consider the connection closed (60000)
  pingInterval (Number): how many ms before sending a new ping packet (25000).
</code>```

are these the default values?

答: For "socket.io": "^2.1.1",  pingInterval is 60 sec and latest chrome is also becoming ideal at 60 sec so if you have old socket.io package at server then u need to set pingInterval set as 25 sec to work it correctly</p>

Body:
I just want to know what is the default value of pingTimeout and PingInterval in socket.io? I read in the docs the values to be:

  pingTimeout (Number): how many ms without a pong packet to consider the connection closed (60000)
  pingInterval (Number): how many ms before sending a new ping packet (25000).

are these the default values?


问:
marker in the osm Map with osmdroid
I am trying to display a marquer in OSM, but can't. I can display the OSM map and the location of my phone, but nothing else.

Here is my code:

```<code>public class Carte2Activity extends Activity implements LocationListener {
    MapView mapView;
    MapController myMapController;
    MyLocationOverlay location = null;
    double lat;
    double lng;
    LocationManager lm;
    LocationListener ll;

    ArrayList<OverlayItem> anotherOverlayItemArray;
    String[] sources;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView)findViewById(R.id.openmapview);
        mapView.setBuiltInZoomControls(true);
        mapView.setMultiTouchControls(true);

        lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        ll = new Myll();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,ll);

        myMapController = mapView.getController();
        myMapController.setZoom(10);
        myMapController.setCenter(new GeoPoint((int)(48.785152*1E6), (int)(2.285156*1E6)));

        location = new MyLocationOverlay(getApplicationContext(), mapView);

       //ajouter la loc
        mapView.getOverlays().add(location);
        //afficher
        location.enableMyLocation();

    }

    private class Myll implements LocationListener{

    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        lat = location.getLatitude();
        lng = location.getLongitude();
        run();
    }

    public void run() {
        // TODO Auto-generated method stub
        location.runOnFirstFix(new Runnable() { public void run() {
            mapView.getController().animateTo(location.getMyLocation());
            }});
    }

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}

    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
    }

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }
}
</code>```

androidManifest :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="comparateur.carte"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".Carte2Activity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

I don't see how I can do that. Can somebody help me?

答:
```<code> public void showOnMap(double lat , double lon){
    map = (MapView) root.findViewById(R.id.map);
    map.setTileSource(TileSourceFactory.MAPNIK);
    map.setBuiltInZoomControls(true);
    map.setMultiTouchControls(true);
    mapController = map.getController();
    myLocationoverlay = new MyLocationNewOverlay(map);
    myLocationoverlay.setEnabled(true);
    map.getOverlays().add(myLocationoverlay);
    GeoPoint startPoint = new GeoPoint(lat, lon);
    mapController.animateTo(startPoint);
    mapController.setZoom(16.0);
    Marker startMarker = new Marker(map);
    startMarker.setIcon(getResources().getDrawable(R.drawable.location));
    startMarker.setPosition(startPoint);
    map.getOverlays().add(startMarker);

}
</code>```

Title: marker in the osm Map with osmdroid

Body:
I am trying to display a marquer in OSM, but can't. I can display the OSM map and the location of my phone, but nothing else.

Here is my code:

public class Carte2Activity extends Activity implements LocationListener {
    MapView mapView;
    MapController myMapController;
    MyLocationOverlay location = null;
    double lat;
    double lng;
    LocationManager lm;
    LocationListener ll;

    ArrayList<OverlayItem> anotherOverlayItemArray;
    String[] sources;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView)findViewById(R.id.openmapview);
        mapView.setBuiltInZoomControls(true);
        mapView.setMultiTouchControls(true);

        lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        ll = new Myll();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,ll);

        myMapController = mapView.getController();
        myMapController.setZoom(10);
        myMapController.setCenter(new GeoPoint((int)(48.785152*1E6), (int)(2.285156*1E6)));

        location = new MyLocationOverlay(getApplicationContext(), mapView);

       //ajouter la loc
        mapView.getOverlays().add(location);
        //afficher
        location.enableMyLocation();

    }

    private class Myll implements LocationListener{

    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        lat = location.getLatitude();
        lng = location.getLongitude();
        run();
    }

    public void run() {
        // TODO Auto-generated method stub
        location.runOnFirstFix(new Runnable() { public void run() {
            mapView.getController().animateTo(location.getMyLocation());
            }});
    }

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}

    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
    }

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }
}

androidManifest :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="comparateur.carte"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".Carte2Activity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

I don't see how I can do that. Can somebody help me?


答:
You can do this, adjusted to reflect the desired output in a bit more detail, although getting median line is a bit of a hack:

library(ggplot2)
library(tibble)

ggplot(a, aes(x = factor(Month, month.name[c(7:12, 1:6)]))) +
  geom_boxplot(aes(
    lower = Q1,
    upper = Q3,
    middle = Med,
    ymin = Min,
    ymax = Max,
    fill = "25% - 75%"),
    stat = "identity")+
  geom_point(aes(y = mean, shape = "Mean"))+
  geom_line(aes(y = Med, colour = "Median"), size = 1)+
  guides(linetype = guide_legend(override.aes = list(linetype = 1)))+
  scale_fill_manual(values = "green")+
  scale_colour_manual(values = "black")+
  labs(y = "Energy Consumption (kWh/km)",
       x = NULL,
       fill = NULL,
       shape = NULL,
       colour = NULL)+
  theme_bw()+
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1 ),
        legend.position = c(0.9, 0.9),
        legend.justification = c(1, 1))

```

Created on 2020-05-31 by the reprex package (v0.3.0)

Title: Generating numbers from given mean, median, SD, maximum and minimum values using R

Body:
I have a list of temperature data which shows mean, median, SD, maximum , minimum and IQR of temperatures for different months. I wanted to generate a set of numbers using the above given values. is it possible in R ?

The smaple data :

a <- tribble( ~"Month",~"year", ~"mean", ~"SD", ~"Min", ~"Q1", ~"Med", ~"Q3", ~"Max", "July", 2018, 1.13, 0.07, 0.98, 1.09, 1.13, 1.18, 1.27, "August", 2018, 1.16, 0.08, 1.04, 1.10, 1.16, 1.22 ,1.39, "September", 2018, 1.08, 0.08, 0.97, 1.00, 1.08, 1.12, 1.29, "October", 2018, 1.16, 0.11, 0.94, 1.07, 1.16, 1.23, 1.42, "November", 2018, 1.48, 0.25, 1.02, 1.34, 1.48, 1.60, 1.93, "December", 2018, 1.82, 0.17,1.52, 1.69, 1.82, 1.92, 2.20, "January", 2019, 1.91, 0.19, 1.56, 1.76, 1.89, 2.02, 2.26, "February", 2019, 1.59, 0.17, 1.33, 1.44, 1.59, 1.77, 1.90, "March", 2019, 1.35, 0.18, 1.10, 1.20, 1.33, 1.45, 1.67, "April", 2019, 1.34, 0.10, 1.16, 1.27, 1.34, 1.41, 1.47, "May", 2019 ,1.31, 0.07, 1.14, 1.24, 1.31, 1.35, 1.43, "June", 2019, 1.31, 0.06, 1.19, 1.26, 1.31, 1.35,1.43 )

what i actually want is some boxplot like this as an output from it :

Body:
You can do this, adjusted to reflect the desired output in a bit more detail, although getting median line is a bit of a hack:

library(ggplot2)
library(tibble)

ggplot(a, aes(x = factor(Month, month.name[c(7:12, 1:6)]))) +
  geom_boxplot(aes(
    lower = Q1,
    upper = Q3,
    middle = Med,
    ymin = Min,
    ymax = Max,
    fill = "25% - 75%"),
    stat = "identity")+
  geom_point(aes(y = mean, shape = "Mean"))+
  geom_line(aes(y = Med, colour = "Median"), size = 1)+
  guides(linetype = guide_legend(override.aes = list(linetype = 1)))+
  scale_fill_manual(values = "green")+
  scale_colour_manual(values = "black")+
  labs(y = "Energy Consumption (kWh/km)",
       x = NULL,
       fill = NULL,
       shape = NULL,
       colour = NULL)+
  theme_bw()+
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1 ),
        legend.position = c(0.9, 0.9),
        legend.justification = c(1, 1))

Created on 2020-05-31 by the reprex package (v0.3.0)


问:
socket.io client receiving multiple calls to same event in react native
Whenver the user login into the application. he joins to its own userId in server via

```<code>socket.join(uid)
</code>```

whereas the nodejs endpoint looks like

```<code>router.post("/secured/postmessage", (req,res)=>{
  const { message, receiverId } = req.body;

 io.to(receiverId).emit("newMessage", {
      msgBody: message,
      sender: req.currentUser,
    });
})
</code>```

now the RN part:

Chat screen functional Component looks like

```<code>export default function Chat({ navigation }) {

//receiveing the socket as props from previous screen
  const { contact, socket } = navigation.state.params;
  // console.log("in conversation contact is ", contact);

  const [data, setData] = useState([
    {
      id: 8,
      date: "9:50 am",
      type: "in",
      message: "Lorem ipsum dolor sit a met",
    },
  ]);

//this gets fired multiple times <--------
socket.on("newMessage", ({ msgBody, sender }) => {
    setData((oldMessages) => [...oldMessages, msgBody]);
  });

//handleSubmit gets fired when user types message and press SEND
const handleSubmit(){
//sending the post request to server with message
 axios.post(baseUrl + "/secured/postmessage", {
    message: message,
    receiverId: contact._id,
    })
}
return(
  ...
  )
</code>```

whereas the nodejs endpoint looks like

```<code>router.post("/secured/postmessage", (req,res)=>{
 io.to(receiverId).emit("newMessage", {
      msgBody: messageResult,
      sender: req.currentUser,
    });
})
</code>```

socket.on('newMessage') in Chat screen is getting fired multiple times, I dont know why

答:
I think you can try adding socket event handler only when your Chat component mounted.

In functional component, you can use React.useEffect().

refer to below

```<code>React.useEffect(() => {
    socket.on("newMessage", ({ msgBody, sender }) => {
        setData((oldMessages) => [...oldMessages, msgBody]);
    });
},[]);
</code>```

Body:
Whenver the user login into the application. he joins to its own userId in server via

socket.join(uid)

whereas the nodejs endpoint looks like

router.post("/secured/postmessage", (req,res)=>{
  const { message, receiverId } = req.body;

 io.to(receiverId).emit("newMessage", {
      msgBody: message,
      sender: req.currentUser,
    });
})

now the RN part:

Chat screen functional Component looks like

export default function Chat({ navigation }) {

//receiveing the socket as props from previous screen
  const { contact, socket } = navigation.state.params;
  // console.log("in conversation contact is ", contact);

  const [data, setData] = useState([
    {
      id: 8,
      date: "9:50 am",
      type: "in",
      message: "Lorem ipsum dolor sit a met",
    },
  ]);

//this gets fired multiple times <--------
socket.on("newMessage", ({ msgBody, sender }) => {
    setData((oldMessages) => [...oldMessages, msgBody]);
  });

//handleSubmit gets fired when user types message and press SEND
const handleSubmit(){
//sending the post request to server with message
 axios.post(baseUrl + "/secured/postmessage", {
    message: message,
    receiverId: contact._id,
    })
}
return(
  ...
  )

whereas the nodejs endpoint looks like

router.post("/secured/postmessage", (req,res)=>{
 io.to(receiverId).emit("newMessage", {
      msgBody: messageResult,
      sender: req.currentUser,
    });
})

socket.on('newMessage') in Chat screen is getting fired multiple times, I dont know why

Body:
I think you can try adding socket event handler only when your Chat component mounted.

In functional component, you can use React.useEffect().

refer to below

React.useEffect(() => {
    socket.on("newMessage", ({ msgBody, sender }) => {
        setData((oldMessages) => [...oldMessages, msgBody]);
    });
},[]);


问:
how Kotlin interpret {} or () by a run example
```<code>fun main (){
    run(::topLevel)
    run{::topLevel}
    run{topLevel()}
    run(topLevel())
    }
fun topLevel() = println("print something")
</code>```

1,2 run will execute the fun
3- will not execute
4- is an error

By this example i find that () and {} have different meaning.
Would appreciate a lot if some one will explain how Kotlin interpret this 4 cases.

答:
If you see the declaration of the run function,

public inline fun <R> run(block: () -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}
```

<p>It takes a block (a lambda) of signature <code>() -> R</code>. And the curly parenthesis (<code>{}</code>) create a lambda of that signature.</p>

<p>For instance <code>{}</code> has signature <code>() -> Unit</code>, <code>{ 4 }</code> has signature <code>() -> Int</code>. These are compatible with the run function.</p>

<p>What essentially happens when you call run is:</p>

<pre class="lang-kotlin prettyprint-override"><code>run { topLevel() }

// is equivalent to
run() { topLevel() }

// is equivalent to
run({ topLevel })
</code>```

Hope-fully you understood the lambdas, which are created by curly braces {} and can be put outside the invokation of the function.

Now if you talk about :: operator, it returns a reference of the function which is itself a lambda signature.

For example, ::topLevel will return () -> Unit as it takes no argument and returns nothing (which is Unit).

Second and fourth will not work because.

In second: run{::topLevel} this passes passes () -> () -> Unit to the run. i.e. it passes a function which returns a reference to function topLevel. And hence to make it work, you have to write:

run{::topLevel}()
```

What it does is return the ::topLevel on which we invoke using () that calls topLevel.

The fourth one won't compile because you are passing Unit (return type) of the topLevel function returned by calling it there like topLevel()

Body:
fun main (){
    run(::topLevel)
    run{::topLevel}
    run{topLevel()}
    run(topLevel())
    }
fun topLevel() = println("print something")

1,2 run will execute the fun
3- will not execute
4- is an error

By this example i find that () and {} have different meaning.
Would appreciate a lot if some one will explain how Kotlin interpret this 4 cases.

Body:
If you see the declaration of the run function,

public inline fun <R> run(block: () -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}

It takes a block (a lambda) of signature () -> R. And the curly parenthesis ({}) create a lambda of that signature.

For instance {} has signature () -> Unit, { 4 } has signature () -> Int. These are compatible with the run function.

What essentially happens when you call run is:

run { topLevel() }

// is equivalent to
run() { topLevel() }

// is equivalent to
run({ topLevel })

Hope-fully you understood the lambdas, which are created by curly braces {} and can be put outside the invokation of the function.

Now if you talk about :: operator, it returns a reference of the function which is itself a lambda signature.

For example, ::topLevel will return () -> Unit as it takes no argument and returns nothing (which is Unit).

Second and fourth will not work because.

In second: run{::topLevel} this passes passes () -> () -> Unit to the run. i.e. it passes a function which returns a reference to function topLevel. And hence to make it work, you have to write:

run{::topLevel}()

What it does is return the ::topLevel on which we invoke using () that calls topLevel.

The fourth one won't compile because you are passing Unit (return type) of the topLevel function returned by calling it there like topLevel()


问:
Error handling with POST signals from axios to Django Rest Server
I use React + Django, when user signup from frontend the axios in React send POST signal to Django, if form is invalid it shows below response

```<code>xhr.js:178 POST http://localhost:8000/account/users/
signup.js:120 Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:61)
</code>```

If I do same POST with invalid fields in Django browsable API or Postman I get below error and it is useful to display error to users

```<code>{
    "email": [
        "This field may not be blank."
    ],
    "username": [
        "This field may not be blank."
    ]
}

</code>```

If user type invalid details in form and after form submission, How can I get same error message from axios ?

Please note that if user type correct information in form, axios responds with sufficient details.

Axios function

```<code> axios.post('/account/users/',{data}).then(res=>console.log(res)).catch(err=>console.log(err)
</code>```

答:
It's needles to say that the response is exactly the same in both cases, an HTTP response with status 400 (Bad Request) and with the body you see in postman. Your issue is related to how Axios provides you the response. If you want to access the response body when Axios gets an error response, you have it in error.response.data:

```<code>axios.post('/account/users/'{data})
.then(res=>console.log(res))
.catch(err=>console.log('Response body', err.response.data)
</code>```

Body:
I use React + Django, when user signup from frontend the axios in React send POST signal to Django, if form is invalid it shows below response

xhr.js:178 POST http://localhost:8000/account/users/
signup.js:120 Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:61)

If I do same POST with invalid fields in Django browsable API or Postman I get below error and it is useful to display error to users

{
    "email": [
        "This field may not be blank."
    ],
    "username": [
        "This field may not be blank."
    ]
}

If user type invalid details in form and after form submission, How can I get same error message from axios ?

Please note that if user type correct information in form, axios responds with sufficient details.

Axios function

 axios.post('/account/users/',{data}).then(res=>console.log(res)).catch(err=>console.log(err)

Body:
It's needles to say that the response is exactly the same in both cases, an HTTP response with status 400 (Bad Request) and with the body you see in postman. Your issue is related to how Axios provides you the response. If you want to access the response body when Axios gets an error response, you have it in error.response.data:

axios.post('/account/users/'{data})
.then(res=>console.log(res))
.catch(err=>console.log('Response body', err.response.data)


问:
Looping through list of columns
I have a large data frame, one column shows the province where the respondent is coming from. I would like to see differences of values between respondents from provinces in some columns, based on column name (e.g. for the columns Hope, Responsibility, Efficacy).

```<code>Province  Hope  Responsibility  Efficacy Age
   A       4         3            2      24
   A       2         1            4      23
   C       5         3            5      20
   B       3         2            3      29
   A       1         1            4      23
   B       3         3            2      25
</code>```

So far I looped through differences between all combinations of provinces for each column:

```<code>list1 = list('A', 'B', 'C', 'D' 'E', 'F')
list2 = list('B', 'C', 'D' 'E', 'F')

for (i in list1){
  for (j in list2){
    t <- t.test(dt[Province == i, Hope], dt[Province == j, Hope])
    if (t$p.value <= 0.05){
      print(paste("Results:",i,"and",j))
      print(t)
    }}}
</code>```

How can I create a loop that loops through a list of columns based on the column name, e.g. something like this (which does not work).

THIS PART IS EDITED

```<code>list1 = list('A', 'B', 'C', 'D' 'E', 'F')
list2 = list('B', 'C', 'D' 'E', 'F')
list3 = list('Hope', 'Responsibility', 'Efficacy')

for (c in list3){
  for (i in list1){
    for (j in list2){
      t <- t.test(dt[Province == i, c], dt[Province == j, c])
      if (t$p.value <= 0.05){
        print(paste("Results:",i,"and",j))
        print(t)
      }}}}
</code>```

Title: Looping through list of columns

Body:
I have a large data frame, one column shows the province where the respondent is coming from. I would like to see differences of values between respondents from provinces in some columns, based on column name (e.g. for the columns Hope, Responsibility, Efficacy).

Province  Hope  Responsibility  Efficacy Age
   A       4         3            2      24
   A       2         1            4      23
   C       5         3            5      20
   B       3         2            3      29
   A       1         1            4      23
   B       3         3            2      25

So far I looped through differences between all combinations of provinces for each column:

list1 = list('A', 'B', 'C', 'D' 'E', 'F')
list2 = list('B', 'C', 'D' 'E', 'F')

for (i in list1){
  for (j in list2){
    t <- t.test(dt[Province == i, Hope], dt[Province == j, Hope])
    if (t$p.value <= 0.05){
      print(paste("Results:",i,"and",j))
      print(t)
    }}}

How can I create a loop that loops through a list of columns based on the column name, e.g. something like this (which does not work).

THIS PART IS EDITED

list1 = list('A', 'B', 'C', 'D' 'E', 'F')
list2 = list('B', 'C', 'D' 'E', 'F')
list3 = list('Hope', 'Responsibility', 'Efficacy')

for (c in list3){
  for (i in list1){
    for (j in list2){
      t <- t.test(dt[Province == i, c], dt[Province == j, c])
      if (t$p.value <= 0.05){
        print(paste("Results:",i,"and",j))
        print(t)
      }}}}

Body:
You can first get unique values of Province and use lapply to iterate over the column names of dt and use outer to get p-values of t.test for every combination.

list1 <- unique(dt$Province)

apply_t_test <- function(x, y, col) {
        t.test(dt[dt$Province == x, col], dt[dt$Province == y, col])$p.value
}
apply_t_test <- Vectorize(apply_t_test)
cols <- c('Hope', 'Responsibility', 'Efficacy')

result <- sapply(cols, function(column) outer(list1, list1, function(x, y)
               apply_t_test(x, y, column)), simplify = FALSE)

The result would look something like this :

#$Hope
#           [,1]       [,2]       [,3]
#[1,] 1.00000000 0.01146182 0.77720749
#[2,] 0.01146182 1.00000000 0.02880269
#[3,] 0.77720749 0.02880269 1.00000000

#$Responsibility
#          [,1]      [,2]      [,3]
#[1,] 1.0000000 0.8624039 0.5206825
#[2,] 0.8624039 1.0000000 0.3795635
#[3,] 0.5206825 0.3795635 1.0000000

#$Efficacy
#          [,1]      [,2]      [,3]
#[1,] 1.0000000 0.6411564 0.5822007
#[2,] 0.6411564 1.0000000 0.9467599
#[3,] 0.5822007 0.9467599 1.0000000


问:
Why we actually need runtime polymorphism?
I'm trying to understand a polymorphism but I don't understand why we need runtime polymorphism if static polymorphism works fine for calling members of a class.

Like, suppose this was a problem.

```<code>#include <bits/stdc++.h>
using namespace std;
class base{
    public:
        virtual void fun(){
            cout<<"base called"<<endl;
        }
};
class derived:public base{
    public:
        void fun(){
            cout<<"derived called"<<endl;
        }
};
int main() {

    base b,*b1;
    derived d;
    b1 = &d;
    b1->fun();
    // b.fun();
    // d.fun();
}
</code>```

suppose this was my code and I want to access the function of derived or base class and I was able to do it by simply creating an object of that class so if there is no problem then why we try to call the object using references (runtime polymorphism).
Can someone explain the actual need for runtime polymorphism or if it is possible can you explain it by using any real-life scenarios??

答:
Polymorphism is considered as one of the important features of Object-Oriented Programming. In C++ polymorphism is mainly divided into two types:

Compile-time Polymorphism: This type of polymorphism is achieved by function overloading or operator overloading.

Runtime Polymorphism: This type of polymorphism is achieved by Function Overriding.

Now consider the following scenario.

Suppose we have a base class named Shape which has the following interface.

class Shape {
public:
    Shape(int init_x, int init_y);
    virtual ~Shape() = default;

    virtual void scale(int s) = 0;
protected:
    int x;
    int y;
};
```

<p>Now we want to inherit two other classes named <code>Rectangle</code> and <code>Circle</code> from it.</p>

<pre class="lang-cpp prettyprint-override"><code>class Rectangle : public Shape {
public:
    Rectangle(int init_x, int init_y, int w, int h);
    void scale(int s) override;
private:
    int width;
    int height;
};
</code>```

class Circle : public Shape {
public:
    Circle(int init_x, int init_y, int r);
    void scale(int s) override;
private:
    int radius;
};
```

As you may know, circle and rectangle shapes, have different implementation for their scale method, so I can't implement that in the Shape class.

Now suppose we have a program that stores all the shapes in a container like vector<Shape*> (e.g. it gets all the shapes from the user once and store them in this container).

If we want to use scale method on one of the shapes, we don't know actually which kind of shape we are dealing with, but it will bind our scale method call to its appropriate implementation.

Body:
I'm trying to understand a polymorphism but I don't understand why we need runtime polymorphism if static polymorphism works fine for calling members of a class.

Like, suppose this was a problem.

#include <bits/stdc++.h>
using namespace std;
class base{
    public:
        virtual void fun(){
            cout<<"base called"<<endl;
        }
};
class derived:public base{
    public:
        void fun(){
            cout<<"derived called"<<endl;
        }
};
int main() {

    base b,*b1;
    derived d;
    b1 = &d;
    b1->fun();
    // b.fun();
    // d.fun();
}

suppose this was my code and I want to access the function of derived or base class and I was able to do it by simply creating an object of that class so if there is no problem then why we try to call the object using references (runtime polymorphism).
Can someone explain the actual need for runtime polymorphism or if it is possible can you explain it by using any real-life scenarios??

Body:
Polymorphism is considered as one of the important features of Object-Oriented Programming. In C++ polymorphism is mainly divided into two types:

Compile-time Polymorphism: This type of polymorphism is achieved by function overloading or operator overloading.

Runtime Polymorphism: This type of polymorphism is achieved by Function Overriding.

Now consider the following scenario.

Suppose we have a base class named Shape which has the following interface.

class Shape {
public:
    Shape(int init_x, int init_y);
    virtual ~Shape() = default;

    virtual void scale(int s) = 0;
protected:
    int x;
    int y;
};

Now we want to inherit two other classes named Rectangle and Circle from it.

class Rectangle : public Shape {
public:
    Rectangle(int init_x, int init_y, int w, int h);
    void scale(int s) override;
private:
    int width;
    int height;
};

class Circle : public Shape {
public:
    Circle(int init_x, int init_y, int r);
    void scale(int s) override;
private:
    int radius;
};

As you may know, circle and rectangle shapes, have different implementation for their scale method, so I can't implement that in the Shape class.

Now suppose we have a program that stores all the shapes in a container like vector<Shape*> (e.g. it gets all the shapes from the user once and store them in this container).

If we want to use scale method on one of the shapes, we don't know actually which kind of shape we are dealing with, but it will bind our scale method call to its appropriate implementation.


问:
Invariant Violation using react-native-svg
I have the following error when I try to use react-native-svg:

I use react-native-svg like this in my code:

and I call the component like this

```<code>import BarChart from './BarChart'

// ...
</code>```

I am using react-native-svg : 9.13.3 and expo : 36
I installed react-native-svg with expo install react-native-svg and I already try to relaunch with reset cache.....
save me please lol
have a nice day !

答:
The issue is most probably coming from how you import your Svg.

From the documentation I found if you are using Expo, then you need to import as:

```<code>/* Use this if you are using Expo */

import * as Svg from 'react-native-svg';
const { Circle, Rect } = Svg;
</code>```

Instead of your example:

```<code>import Svg, { Circle, Rect } from 'react-native-svg';
</code>```

See under Usage section.

Body:
I have the following error when I try to use react-native-svg:

I use react-native-svg like this in my code:

and I call the component like this

import BarChart from './BarChart'

// ...

I am using react-native-svg : 9.13.3 and expo : 36
I installed react-native-svg with expo install react-native-svg and I already try to relaunch with reset cache.....
save me please lol
have a nice day !

Body:
The issue is most probably coming from how you import your Svg.

From the documentation I found if you are using Expo, then you need to import as:

/* Use this if you are using Expo */

import * as Svg from 'react-native-svg';
const { Circle, Rect } = Svg;

Instead of your example:

import Svg, { Circle, Rect } from 'react-native-svg';

See under Usage section.


问:
Folder structure within an R project to include .bib file
I am working on a R project

My file structure is as follows. The Rmd file is within the analysis` folder.

```<code>Rproj
analysis
    -file.rmd
data
    -data.csv
</code>```

I want to include my references.bib file in the root directory.
The Yaml on my Rmd is as follows:

```<code>output:
  Templates::report:
    fig_caption: yes
    fig_height: 5
    fig_width: 8
    includes:
      in_header: preamble.tex
    keep_tex: yes
    number_sections: yes
    citation_package: biblatex
    toc: false
</code>```

However my references don't seem to work with my .bib file in the root directory, but works when in the "analysis" folder.

答:
You should include the .bib file in your YAML header. If it's in the parent folder of your Rmd file, I think something like this should work:

```<code>output:
  Templates::report:
    fig_caption: yes
    fig_height: 5
    fig_width: 8
    includes:
      in_header: preamble.tex
    keep_tex: yes
    number_sections: yes
    citation_package: biblatex
    toc: false
bibliography: ../references.bib
</code>```

https://bookdown.org/yihui/rmarkdown-cookbook/bibliography.html

Body:
I am working on a R project

My file structure is as follows. The Rmd file is within the analysis` folder.

Rproj
analysis
    -file.rmd
data
    -data.csv

I want to include my references.bib file in the root directory.
The Yaml on my Rmd is as follows:

output:
  Templates::report:
    fig_caption: yes
    fig_height: 5
    fig_width: 8
    includes:
      in_header: preamble.tex
    keep_tex: yes
    number_sections: yes
    citation_package: biblatex
    toc: false

However my references don't seem to work with my .bib file in the root directory, but works when in the "analysis" folder.

Body:
You should include the .bib file in your YAML header. If it's in the parent folder of your Rmd file, I think something like this should work:

output:
  Templates::report:
    fig_caption: yes
    fig_height: 5
    fig_width: 8
    includes:
      in_header: preamble.tex
    keep_tex: yes
    number_sections: yes
    citation_package: biblatex
    toc: false
bibliography: ../references.bib

https://bookdown.org/yihui/rmarkdown-cookbook/bibliography.html


问:
How to avoid writing same code over again in UIViewController in Swift?
I have the following piece of code that I write in every UIViewController:

```<code>var navBar = self.navigationController?.navigationBar
    navBar?.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
</code>```

I don't want to write these in every UIViewController that I create. I am lazy and I don't want to repeat myself. I can't add it in extension. So what can I do to not have to write this piece of code when I create UIViewController?

答:
1.Use a base UIViewController such as BaseViewController and put this code inside viewDidLoad and replace UIViewController with BaseViewController.

2.You may not want to do anything to UIViewController.Then,you may come across the term AOP.for example Java use AOP a lot.

You can use AOP framework like Aspects.

Body:
I have the following piece of code that I write in every UIViewController:

var navBar = self.navigationController?.navigationBar
    navBar?.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]

I don't want to write these in every UIViewController that I create. I am lazy and I don't want to repeat myself. I can't add it in extension. So what can I do to not have to write this piece of code when I create UIViewController?


问:
Mongoose schema + nodejs
I'm kinda new in mongodb and i'm in trouble
I can't reach a data from my mongo database

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

const Team = new mongoose.Schema({
    name: String,
});

const MatchsSchema = new mongoose.Schema({
    begin_at: Date,
    number_of_games: Number,
    name: String,
    tournament: {
        name: String,
    },
    opponents: {
        type: [Team],
        default: undefined
    },
});

const Matchs = mongoose.model('matchs', MatchsSchema);

module.exports = Matchs;
</code>```

I am trying to access with this code witch is return my "data" :

```<code>console.log(element.opponents[0]);
</code>```

data returned

but when i want to access with .name the value is undefined

```<code>console.log(element.opponents[0].name);
</code>```

database schema : db

I have an collection named "teams" in my db.
What is the problems ? I think i'm not that far...

答:
db answer

My schema was not correct, with a modification that worked fine

Title: Mongoose schema + nodejs

Body:
I'm kinda new in mongodb and i'm in trouble
I can't reach a data from my mongo database

const mongoose = require('mongoose');

const Team = new mongoose.Schema({
    name: String,
});

const MatchsSchema = new mongoose.Schema({
    begin_at: Date,
    number_of_games: Number,
    name: String,
    tournament: {
        name: String,
    },
    opponents: {
        type: [Team],
        default: undefined
    },
});

const Matchs = mongoose.model('matchs', MatchsSchema);

module.exports = Matchs;

I am trying to access with this code witch is return my "data" :

console.log(element.opponents[0]);

data returned

but when i want to access with .name the value is undefined

console.log(element.opponents[0].name);

database schema : db

I have an collection named "teams" in my db.
What is the problems ? I think i'm not that far...


问:
How to add numbers for a string sentence in Java?
I want to add numbers using Java.

For example, the sentence is given String: "My age is 50, and your age is under 30." If I want to add 5 to the sentence, it should be like
"My age is 55, and your age is under 35."

The restriction is the sentence is given, so you need to extract numbers from the sentence and add the numbers to the original sentence.

I was trying to split by space (" ") and try to add numbers after that.
But I don't know how to substitute numbers with the original sentence.

I am confused since it has comma when I am trying to split by " " and even if you can extract all the numbers from the sentence, I am not sure how can I get back to numbers to string.

```<code>public class Main {

public static Pattern pattern = Pattern.compile("\\d+");

public static String addNumber(String str, int n) {

    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        String theAge = matcher.group(0);
        int newAge = Integer.parseInt(theAge) + n;
    }

    String addSentence = str;

    return addSentence;
}

public static void main(String[] args) {
    String testString = "My age is 50, and your age is under 30.";
    String testString2 = "My age is 50, and your age is under 30 and my friend age is 44.";

    String newSent = addNumber(testString, 5);
    // -> should be "My age is 55, and your age is under 35.
    String newSent2 = addNumber(testString2, 10);
    // -> should be "My age is 60, and your age is under 40 and my friend age is 54.";

}
</code>```

}
enter code here

答:
```<code>int myAge = 50;
int yourAge = 30;
String msgStr = "My age is %d, and your age is under %d.";
System.out.printLn(String.format(msgStr, myAge, yourAge));
System.out.printLn(String.format(msgStr, myAge+5, yourAge+5));
</code>```

Body:
I want to add numbers using Java.

For example, the sentence is given String: "My age is 50, and your age is under 30." If I want to add 5 to the sentence, it should be like
"My age is 55, and your age is under 35."

The restriction is the sentence is given, so you need to extract numbers from the sentence and add the numbers to the original sentence.

I was trying to split by space (" ") and try to add numbers after that.
But I don't know how to substitute numbers with the original sentence.

I am confused since it has comma when I am trying to split by " " and even if you can extract all the numbers from the sentence, I am not sure how can I get back to numbers to string.

public class Main {

public static Pattern pattern = Pattern.compile("\\d+");

public static String addNumber(String str, int n) {

    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        String theAge = matcher.group(0);
        int newAge = Integer.parseInt(theAge) + n;
    }

    String addSentence = str;

    return addSentence;
}

public static void main(String[] args) {
    String testString = "My age is 50, and your age is under 30.";
    String testString2 = "My age is 50, and your age is under 30 and my friend age is 44.";

    String newSent = addNumber(testString, 5);
    // -> should be "My age is 55, and your age is under 35.
    String newSent2 = addNumber(testString2, 10);
    // -> should be "My age is 60, and your age is under 40 and my friend age is 54.";

}

}
enter code here


问:
In Gatsby.js, specific style for a component only on a specific page
I have a Header component that is used on a Layout component, which is used to structure the pages on my Gatsby site. There's a specific page where I need to give my header a different background-color. The problem is that there's no header component on that page, just the layout component. I've ended up making this work by adding a background-color prop to the header and to the layout. And I'm passing down the color down first to the layout which then passes it down to the Header...Is this the best approach? It doesn't feel great.</p>

答:
You could simply use react-helmet to add a class to your body on that specific page only. Let's say "dark-header", something like:

<Helmet>

</Helmet>
```

<p>Then, in your css code you could do something like:</p>

<pre class="lang-css prettyprint-override"><code>.header { background-color: #FFFFFF; }

body.dark-header {
    .header { background-color: #000000; }
}
</code>```

Body:
You could simply use react-helmet to add a class to your body on that specific page only. Let's say "dark-header", something like:

<Helmet>
    <body class='dark-header' />
</Helmet>

Then, in your css code you could do something like:

.header { background-color: #FFFFFF; }

body.dark-header {
    .header { background-color: #000000; }
}


问:
Error: java.io.IOException: Failed to dynamically deploy this plugin, on jenkins in docker
I have installed docker then java image then jenkins image, now installing its dependencies, gives following error in logs, any Idea how can it be resolved, as I am from rails background so don't have much knowledge about java error and exceptions, please provide suggestions.

```<code>May 31, 2020 9:41:30 AM hudson.model.UpdateCenter$DownloadJob run
INFO: Starting the installation of Pipeline: Job on behalf of admin
May 31, 2020 9:41:32 AM hudson.model.UpdateCenter$UpdateCenterConfiguration download
INFO: Downloading Pipeline: Job
May 31, 2020 9:41:33 AM hudson.PluginManager dynamicLoad
INFO: Attempting to dynamic load /var/jenkins_home/plugins/workflow-job.jpi
May 31, 2020 9:41:33 AM hudson.model.UpdateCenter$DownloadJob run
SEVERE: Failed to install Pipeline: Job
java.io.IOException: Failed to dynamically deploy this plugin
    at hudson.model.UpdateCenter$InstallationJob._run(UpdateCenter.java:1893)
    at hudson.model.UpdateCenter$DownloadJob.run(UpdateCenter.java:1651)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.AtmostOneThreadExecutor$Worker.run(AtmostOneThreadExecutor.java:110)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: Failed to install workflow-job plugin
    at hudson.PluginManager.dynamicLoad(PluginManager.java:874)
    at hudson.PluginManager.dynamicLoad(PluginManager.java:813)
    at hudson.model.UpdateCenter$InstallationJob._run(UpdateCenter.java:1889)
    ... 5 more
Caused by: java.io.IOException: Pipeline: Job v2.39 failed to load.
 - You must update Jenkins from v2.60.3 to v2.138.4 or later to run this plugin.
 - Pipeline: API v2.40 failed to load. Fix this plugin first.
    at hudson.PluginWrapper.resolvePluginDependencies(PluginWrapper.java:626)
    at hudson.PluginManager.dynamicLoad(PluginManager.java:864)
    ... 7 more
</code>```

答:
Which Jenkins version did you install?

It seems like plugins not supporting on outdated Jenkins version.

Try to skip plugin installation from 'Getting Started' and install them later.

Also, you can try to use official Jenkins docker images.

https://www.jenkins.io/blog/2018/12/10/the-official-Docker-image/

Body:
I have installed docker then java image then jenkins image, now installing its dependencies, gives following error in logs, any Idea how can it be resolved, as I am from rails background so don't have much knowledge about java error and exceptions, please provide suggestions.

May 31, 2020 9:41:30 AM hudson.model.UpdateCenter$DownloadJob run
INFO: Starting the installation of Pipeline: Job on behalf of admin
May 31, 2020 9:41:32 AM hudson.model.UpdateCenter$UpdateCenterConfiguration download
INFO: Downloading Pipeline: Job
May 31, 2020 9:41:33 AM hudson.PluginManager dynamicLoad
INFO: Attempting to dynamic load /var/jenkins_home/plugins/workflow-job.jpi
May 31, 2020 9:41:33 AM hudson.model.UpdateCenter$DownloadJob run
SEVERE: Failed to install Pipeline: Job
java.io.IOException: Failed to dynamically deploy this plugin
    at hudson.model.UpdateCenter$InstallationJob._run(UpdateCenter.java:1893)
    at hudson.model.UpdateCenter$DownloadJob.run(UpdateCenter.java:1651)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.AtmostOneThreadExecutor$Worker.run(AtmostOneThreadExecutor.java:110)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: Failed to install workflow-job plugin
    at hudson.PluginManager.dynamicLoad(PluginManager.java:874)
    at hudson.PluginManager.dynamicLoad(PluginManager.java:813)
    at hudson.model.UpdateCenter$InstallationJob._run(UpdateCenter.java:1889)
    ... 5 more
Caused by: java.io.IOException: Pipeline: Job v2.39 failed to load.
 - You must update Jenkins from v2.60.3 to v2.138.4 or later to run this plugin.
 - Pipeline: API v2.40 failed to load. Fix this plugin first.
    at hudson.PluginWrapper.resolvePluginDependencies(PluginWrapper.java:626)
    at hudson.PluginManager.dynamicLoad(PluginManager.java:864)
    ... 7 more


问:
How do I populate an array in C++?
Okay so I have a textfile with only 2 lines of doubles that are comma separated. This will always be the case. Each line will have to go into its own separate array of type double where I will later have to use a linear search to find one array in the other.
example of the textfile:

```<code>2.5,6.7,3.4,7,6.7,6,4,5,83.6
6.4,7,8,5.3,9,76
</code>```

So far I have managed to extract the first line, remove the delimiter and convert it from a string to type double BUT I am having difficulty putting it into an array.
I have tried using while loops, for loops (sometimes nested) but they all do not work. I know there is meant to be a simple solution but I can't seem to grasp it or the concept of arrays.

The furthest I am able to code (without messing up) is to simply display it. but I need it in an array. My code follows. Thank you in advance.

```<code>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main ()
{
    double array[10];
    int count = 0 ;
    string values;
    int I =0;
    ifstream inputfile.open("numbers.txt");
    if (!inputfile.is_open())
    {
        cout<<"error opening file"<<endl;
    }

    if (inputfile.good())
    {
        string line;
        string num;
        getline(inputfile,line);
        values= slime;
        string stream ss(values);
        while (getline (ss,num ,','))
        {
            cout<<stod(num)<<" ";
            //HOW DO I PUT THIS INTO THE ARRAY INSTEAD PLEASE??
        }
    }

    inputfile.close();
    return 0;
}
</code>```

答:
few things - one try not to use using namespace std
  second - you check inputfile.good() only relevant after reading
  third - you need an index to run over the array so I added the I that increment with the loop, But I didn't check if it counts more then thy array length so if it relevet add a check for that to.

```<code>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

int main ()
{
    double array[10];
    int count = 0 ;
    string values;
    int I =0;
    ifstream inputfile.open("numbers.txt");
    if (!inputfile.is_open())
    {
        cout<<"error opening file"<<endl;
    }

    string line;
    string num;
    getline(inputfile,line);
    values= slime;
    string stream ss(values);
    int i=0;
    while (getline (ss,num ,','),)
    {
        cout<<stod(num)<<" ";
        array[i] = stod(num);
        ++i;
    }
    inputfile.close();
    return 0;
}
</code>```

Title: How do I populate an array in C++?

Body:
Okay so I have a textfile with only 2 lines of doubles that are comma separated. This will always be the case. Each line will have to go into its own separate array of type double where I will later have to use a linear search to find one array in the other.
example of the textfile:

2.5,6.7,3.4,7,6.7,6,4,5,83.6
6.4,7,8,5.3,9,76

So far I have managed to extract the first line, remove the delimiter and convert it from a string to type double BUT I am having difficulty putting it into an array.
I have tried using while loops, for loops (sometimes nested) but they all do not work. I know there is meant to be a simple solution but I can't seem to grasp it or the concept of arrays.

The furthest I am able to code (without messing up) is to simply display it. but I need it in an array. My code follows. Thank you in advance.

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main ()
{
    double array[10];
    int count = 0 ;
    string values;
    int I =0;
    ifstream inputfile.open("numbers.txt");
    if (!inputfile.is_open())
    {
        cout<<"error opening file"<<endl;
    }

    if (inputfile.good())
    {
        string line;
        string num;
        getline(inputfile,line);
        values= slime;
        string stream ss(values);
        while (getline (ss,num ,','))
        {
            cout<<stod(num)<<" ";
            //HOW DO I PUT THIS INTO THE ARRAY INSTEAD PLEASE??
        }
    }

    inputfile.close();
    return 0;
}

Body:
few things - one try not to use using namespace std
  second - you check inputfile.good() only relevant after reading
  third - you need an index to run over the array so I added the I that increment with the loop, But I didn't check if it counts more then thy array length so if it relevet add a check for that to.

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

int main ()
{
    double array[10];
    int count = 0 ;
    string values;
    int I =0;
    ifstream inputfile.open("numbers.txt");
    if (!inputfile.is_open())
    {
        cout<<"error opening file"<<endl;
    }

    string line;
    string num;
    getline(inputfile,line);
    values= slime;
    string stream ss(values);
    int i=0;
    while (getline (ss,num ,','),)
    {
        cout<<stod(num)<<" ";
        array[i] = stod(num);
        ++i;
    }
    inputfile.close();
    return 0;
}


问:
OSM android does not show map tile
I have implemented a app using Open Street Map and I used OSM android as a library for that. I worked well before but I run the app lately, it did not display map tile at all. I changed tile provider several times but it did not work.

Here is my code:

```<code>public class OsmMapActivity extends SherlockActivity {

protected MapView mapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());

        initialiseMap();
    }

    protected void initialiseMap(){
        mapView = (MapView)findViewById(R.id.mapView);
        mapView.setTileSource(TileSourceFactory.MAPQUESTOSM); //Mapink and other providers do not work
        mapView.setMultiTouchControls(true);
    }
}
</code>```

In additional, does OSM android support third party provider? I have my own OSM tile server and it works well when I display map using Javascript but it does not work in Android code.

```<code>OnlineTileSourceBase tileSource = new XYTileSource("MyOSM", null, 1, 19, 256, ".png", new String[]{"http://tactile.myserver.com/osm_tiles"});
TileSourceFactory.addTileSource(tileSource);
mapView.setTileSource("MyOSM");
</code>```

Your answer would be appreciated. Thanks.

EDIT:
I'm using
osmdroid-android-4.2.jar
Android 4.0.3

When I see it more closely, I could see the map tile very short time and then another layer overrides on it. I removed other layers except base layer from the map but nothing changed.

答:
```<code>    MapController mapController;
    MapView map = (MapView) root.findViewById(R.id.map);
    map.setTileSource(TileSourceFactory.MAPQUESTOSM);
    map.setBuiltInZoomControls(true);
    map.setMultiTouchControls(true);
    mapController = map.getController();
    myLocationoverlay = new MyLocationNewOverlay(map);
    myLocationoverlay.setEnabled(true);
    map.getOverlays().add(myLocationoverlay);
    mapController.setZoom(9.5);
    GeoPoint startPoint = new GeoPoint(35.744198, 51.4285752);
    mapController.setCenter(startPoint);
</code>```

Title: OSM android does not show map tile

Body:
I have implemented a app using Open Street Map and I used OSM android as a library for that. I worked well before but I run the app lately, it did not display map tile at all. I changed tile provider several times but it did not work.

Here is my code:

public class OsmMapActivity extends SherlockActivity {

protected MapView mapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());

        initialiseMap();
    }

    protected void initialiseMap(){
        mapView = (MapView)findViewById(R.id.mapView);
        mapView.setTileSource(TileSourceFactory.MAPQUESTOSM); //Mapink and other providers do not work
        mapView.setMultiTouchControls(true);
    }
}

In additional, does OSM android support third party provider? I have my own OSM tile server and it works well when I display map using Javascript but it does not work in Android code.

OnlineTileSourceBase tileSource = new XYTileSource("MyOSM", null, 1, 19, 256, ".png", new String[]{"http://tactile.myserver.com/osm_tiles"});
TileSourceFactory.addTileSource(tileSource);
mapView.setTileSource("MyOSM");

Your answer would be appreciated. Thanks.

EDIT:
I'm using
osmdroid-android-4.2.jar
Android 4.0.3

When I see it more closely, I could see the map tile very short time and then another layer overrides on it. I removed other layers except base layer from the map but nothing changed.


问:
Explanation for this assembly code
```<code>void* curbrk;

__asm__ __volatile__(
    "mov .curbrk, %%rax;"
    "mov %%rax, %0"
        : "=r" (curbrk)
        :: "%rax"
);
</code>```

Can anyone explain what this simple assembly code does? Thanks.

答:
It copies the value of a symbol .curbrk, probably defined somewhere on assembly or a linker script into the C variable curbrk, clobbering the RAX register in the process.

.curbrk probably points to the current end of the data segment. Glibc appears to define a similar symbol __curbrk, you are probably using some other libc (BSD?). In any case, sbrk(0) would be a more portable way of accessing that value.

After looking at the FreeBSD crossreference, I can say it indeed points to the current end of the data segment: it is used both in brk() and sbrk(), using the HIDENAME macro to prepend a ., and it appears on amd64's System.map (no longer true on current FreeBSD).

Note, however, that in newer FreeBSD, brk() and sbrk() have been reimplemented to no longer depend of .curbrk, which was initialized from _end, which was supposed to come from the executable, but there was trouble when mixing LLVM's ld and GNU ld. So brk() and sbrk() now use the kernel to initialize its internal curbrk, and no longer depend on _end. See FreeBSD PR228754 for details.

Title: Explanation for this assembly code

Body:
void* curbrk;

__asm__ __volatile__(
    "mov .curbrk, %%rax;"
    "mov %%rax, %0"
        : "=r" (curbrk)
        :: "%rax"
);

Can anyone explain what this simple assembly code does? Thanks.


问:
Checking whether a list value is within a range
I have created a list of numbers in fav_numbers. The user will be prompted to enter 2 values: starting range and ending range. The program will check if the list of numbers will fall into the range that the user has inputted. If the numbers in the list fall within the range, the list will be printed out.
The thing is I'm not sure how to check if the individual numbers in the list are within the range.
I am a beginner to python so what would be the most straightforward way to do this, preferably using loops?</p>

```<code>start_range = int(input("Enter the starting number: "))
end_range = int(input("Enter the ending number: "))

#find favourite numbers
def find_favourite_numbers(start_range,end_range):
    fav_numbers = [70, 105, 140]
    for start_range and end_range in range(fav_numbers):
    if fav_numbers[0,1,2] >= start_range and fav_number <= end_range:
        print(fav_numbers)
    else:
        print("favourite numbers not in range")

    print(fav_numbers)

    return fav_numbers

#Do not remove the next line
find_favourite_numbers(start_range,end_range)
</code>```

答:
The way I see it you have a few options in descending order of efficiency:

Assuming the list is sorted as the example:

If the list is sorted, it is enough to just check the edges:

if start_range <= fav_numbers[0] and fav_numbers[-1] <= end_range:
    print("numbers are in range")
```

<h1>The general case (list is not sorted):</h1>

<p>Obviously sorting the list will bring you back to the previous section.</p>

<p>Alternatively, you can just do:</p>

<pre class="lang-py prettyprint-override"><code>if start_range <= min(fav_numbers) and max(fav_numbers) <= end_range:
    print("numbers are in range")
</code>```

Lastly, the optimized version of a regular loop will be to use the built-in any/all functions:

if all(start_range <= num <= end_range for num in fav_numbers):
    print("numbers are in range")
```

<p>The nice thing with using these functions is <em>short-circuiting</em>. This basically means that not all values will necessarily be checked. In the example above (using <code>all</code>), if a number is out of range, the loop will break, or - short-circuit. This means that the above single line of <code>all</code> is equivalent to the more messy:</p>

<pre class="lang-py prettyprint-override"><code>for num in fav_numbers:
    if not start_range <= num <= end_range: # equivalent to if num < start_range or num > end_range
        return False
return True
</code>```

Body:
I have created a list of numbers in fav_numbers. The user will be prompted to enter 2 values: starting range and ending range. The program will check if the list of numbers will fall into the range that the user has inputted. If the numbers in the list fall within the range, the list will be printed out.
The thing is I'm not sure how to check if the individual numbers in the list are within the range.
I am a beginner to python so what would be the most straightforward way to do this, preferably using loops?

start_range = int(input("Enter the starting number: "))
end_range = int(input("Enter the ending number: "))

#find favourite numbers
def find_favourite_numbers(start_range,end_range):
    fav_numbers = [70, 105, 140]
    for start_range and end_range in range(fav_numbers):
    if fav_numbers[0,1,2] >= start_range and fav_number <= end_range:
        print(fav_numbers)
    else:
        print("favourite numbers not in range")

    print(fav_numbers)

    return fav_numbers

#Do not remove the next line
find_favourite_numbers(start_range,end_range)

Body:
The way I see it you have a few options in descending order of efficiency:

Assuming the list is sorted as the example:

If the list is sorted, it is enough to just check the edges:

if start_range <= fav_numbers[0] and fav_numbers[-1] <= end_range:
    print("numbers are in range")

The general case (list is not sorted):

Obviously sorting the list will bring you back to the previous section.

Alternatively, you can just do:

if start_range <= min(fav_numbers) and max(fav_numbers) <= end_range:
    print("numbers are in range")

Lastly, the optimized version of a regular loop will be to use the built-in any/all functions:

if all(start_range <= num <= end_range for num in fav_numbers):
    print("numbers are in range")

The nice thing with using these functions is short-circuiting. This basically means that not all values will necessarily be checked. In the example above (using all), if a number is out of range, the loop will break, or - short-circuit. This means that the above single line of all is equivalent to the more messy:

for num in fav_numbers:
    if not start_range <= num <= end_range: # equivalent to if num < start_range or num > end_range
        return False
return True