问:
How to get confusion matrix of a CNN model
I have used CNN model for binary image classification. I am able to get accuracy and loss but don't know how to get confusion matrix of such model. Also how graph can be plotted of accuracy and loss?</p>

```<code>import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
import pickle
import numpy as np

X = np.array(pickle.load(open("X.pickle","rb")))
Y = np.array(pickle.load(open("Y.pickle","rb")))

#scaling our image data
X = X/255.0

model = Sequential()
#model.add(Conv2D(64 ,(3,3), input_shape = X.shape[1:]))
model.add(Conv2D(64 ,(3,3), input_shape = X.shape[1:]))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Conv2D(128 ,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Conv2D(256 ,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Conv2D(512 ,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Flatten())

model.add(Dense(2048))
model.add(Activation("relu"))

model.add(Dropout(0.5))

model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss="binary_crossentropy",
             optimizer = "adam",
             metrics = ['accuracy'])

model.fit(X, Y, batch_size=32, epochs = 15, validation_split=0.1)
</code>```

答:
The recommended way to plot loss and accuracy when training a model with Tensorflow and Keras is using Tensorboard (https://www.tensorflow.org/tensorboard/get_started)

Tensorflow also provides a function to compute the confusion matrix : https://www.tensorflow.org/api_docs/python/tf/math/confusion_matrix

Body:
I have used CNN model for binary image classification. I am able to get accuracy and loss but don't know how to get confusion matrix of such model. Also how graph can be plotted of accuracy and loss?

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
import pickle
import numpy as np

X = np.array(pickle.load(open("X.pickle","rb")))
Y = np.array(pickle.load(open("Y.pickle","rb")))

#scaling our image data
X = X/255.0

model = Sequential()
#model.add(Conv2D(64 ,(3,3), input_shape = X.shape[1:]))
model.add(Conv2D(64 ,(3,3), input_shape = X.shape[1:]))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Conv2D(128 ,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Conv2D(256 ,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Conv2D(512 ,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Flatten())

model.add(Dense(2048))
model.add(Activation("relu"))

model.add(Dropout(0.5))

model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss="binary_crossentropy",
             optimizer = "adam",
             metrics = ['accuracy'])

model.fit(X, Y, batch_size=32, epochs = 15, validation_split=0.1)


来源: stackexchange

问:
Can I get some assistance with my homework having to do with counter-controlled repetition and arguments?
Okay, so I need to have the output look like a diamond of asterisks, with each row increasing by 2 asterisks until the middle has 9 asterisks...and then the rows decrease. function main has to be:

```<code>int main (void){
   int i;
   i = 0;
   while (i < 5){
      printline (4-i, i*2+1);
      i = i + 1;
   }
   i = 3;
   while (i >= 0) {
      printline (4-i, i*2+1);
      i = i - 1;
   }
   return 0;
}
</code>```

Now I am supposed to define function printline to print a single line of the figure each time it is called. It takes 2 arguments, the number of spaces and the number of asterisks that should be printed on the line. Use counter controlled repetition to print the appropriate number of spaces and again to print the appropriate number of asterisks.

```<code>char print_line (int spaces, int stars){
   for (int i = 4; i>=spaces; i--){
      printf(" ");
   }
   for (int i = 1; i<=stars; i+=2){
      printf("*");
   }
   printf("\n");
}
</code>```

Woohoo! I'm almost done! The outputs kinda right, except that instead of a line with 4 spaces with a star, a line with 3 spaces with 3 stars, and so on up to no spaces and 9 stars, (and then reverses)...I get a line with a star, a line with a space and 2 stars, a line with two spaces three stars, etc, up to 4 spaces five stars (and then reverses)...

The reason printline is different is because I have problems writing with this sometimes and I kept on getting italics whenever I tried to write it...

答:
Some hints:

Your function need only print characters, it does not return anything (there's a specific return type for this)

The number of spaces and the number of stars to print are probably integers

You can print a single space using printf(" ");

You can print a single star using printf("*");

You can print a "newline" (which goes to the next line) using printf("\n");

If you say int i=0; for(i=0; i<n; i++) { printf("X"); } you will print the letter X a total of n times (you may not have learned for loops at this point; if not, use the next hint)

If you say int i=0; while(i<n) { printf("X"); i++; } you will also print the letter X a total of n times

You will be much happier if you use parameter names other than a and b.  Try to think of a name that corresponds with what the parameter represents.

Response to your edit:

You will want to use two separate loops; one that prints the spaces, and then one that prints the stars

for loops are always constructed with one initializer, one check condition, and one step/increment

You should not need to assign values to stars or spaces; they are numbers given to you by whoever calls your printline function (i.e. they already have a value)

Response to your second edit:

In your for loops, you probably want to use an index variable other than the parameter being passed in (e.g. for(i=0; i<spaces; i++), where i is just a counter you declare at the top of your function, like in the code from the assignment)  In your current construction, it will try to print 4 spaces, no matter what the caller specified when they called your function.

You only need to output the newline once, after you're done with all the spaces and stars (i.e. outputing the newline doesn't belong inside a for loop)

You probably only need to increment your counter by 1 each time you output a star.

If the assignment says to make a function called printline, you can't call it print_line; that isn't the same thing (neither is PrintLine)

Response to your third edit:

Don't forget "You probably only need to increment your counter by 1 each time you output a star."

Don't forget "Your function need only print characters, it does not return anything (there's a specific return type for this)" (i.e. it should not be returning a char)

I think you want the code that prints spaces to look more like the code that prints stars

OwnerDisplayName: Kaity

ContentLicense: CC BY-SA 3.0

Body:
Okay, so I need to have the output look like a diamond of asterisks, with each row increasing by 2 asterisks until the middle has 9 asterisks...and then the rows decrease. function main has to be:

int main (void){
   int i;
   i = 0;
   while (i < 5){
      printline (4-i, i*2+1);
      i = i + 1;
   }
   i = 3;
   while (i >= 0) {
      printline (4-i, i*2+1);
      i = i - 1;
   }
   return 0;
}

Now I am supposed to define function printline to print a single line of the figure each time it is called. It takes 2 arguments, the number of spaces and the number of asterisks that should be printed on the line. Use counter controlled repetition to print the appropriate number of spaces and again to print the appropriate number of asterisks.

char print_line (int spaces, int stars){
   for (int i = 4; i>=spaces; i--){
      printf(" ");
   }
   for (int i = 1; i<=stars; i+=2){
      printf("*");
   }
   printf("\n");
}

Woohoo! I'm almost done! The outputs kinda right, except that instead of a line with 4 spaces with a star, a line with 3 spaces with 3 stars, and so on up to no spaces and 9 stars, (and then reverses)...I get a line with a star, a line with a space and 2 stars, a line with two spaces three stars, etc, up to 4 spaces five stars (and then reverses)...

The reason printline is different is because I have problems writing with this sometimes and I kept on getting italics whenever I tried to write it...

LastEditorDisplayName: Ferruccio

OwnerDisplayName: Daniel L

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Daniel L


问:
How to let Flash app communicate with server?
What's an easy and secure way to let my Flash app communicate with my back-end server?

The Flash app, which is a video player, should retrieve the person's username and send back an ID. How would I do this?

Note: Back-end is written in Javascript.

答:
I've used XML-RPC in a Flash client before. I've gotten it to work pretty well too.

I've personally used this Action Script 3 implementation:

http://danielmclaren.com/2007/08/03/xmlrpc-for-actionscript-30-free-library

Of course, the server I was talking with was Java/Tomcat. However, I'm pretty sure there are XML-RPC implementations for JavaScript; a quick search found this:

http://phpxmlrpc.sourceforge.net/jsxmlrpc/

Don't know how much setup/overhead it would be for you server-wise, but I've had success with that protocol.


问:
Read files with only specific names from Amazon S3
I have connected to Amazon S3 and am trying to retrieve data from the JSON content from multiple buckets using the below code.

But I have to read only specific JSON files, but not all. How do I do it?

Code:

```<code>for i in bucket:
    try:
          result = client.list_objects(Bucket=i,Prefix = 'PROCESSED_BY/FILE_JSON', Delimiter='/')
          content_object = s3.Object(i, "PROCESSED_BY/FILE_JSON/?Account.json")
          file_content = content_object.get()['Body'].read().decode('utf-8')
          json_content = json.loads(file_content)
    except KeyError:
          pass
</code>```

Bucket structure example.

```<code>test-eob/PROCESSED_BY/FILE_JSON/222-Account.json
test-eob/PROCESSED_BY/FILE_JSON/1212121-Account.json
test-eob/PROCESSED_BY/FILE_JSON/122-multi.json
test-eob/PROCESSED_BY/FILE_JSON/qwqwq-Account.json
test-eob/PROCESSED_BY/FILE_JSON/wqwqw-multi.json
</code>```

From the above list, I want to only read *-Account.json files.

How can I achieve this?

答:
There are several ways to do this in Python. For example, checking if 'stringA' is in 'stringB':

```<code>list1=['test-eob/PROCESSED_BY/FILE_JSON/222-Account.json',
'test-eob/PROCESSED_BY/FILE_JSON/1212121-Account.json',
'test-eob/PROCESSED_BY/FILE_JSON/122-multi.json',
'test-eob/PROCESSED_BY/FILE_JSON/qwqwq-Account.json',
'test-eob/PROCESSED_BY/FILE_JSON/wqwqw-multi.json',]

for i in list1:
    if 'Account' in i:
        print (i)
    else:
        pass
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have connected to Amazon S3 and am trying to retrieve data from the JSON content from multiple buckets using the below code.

But I have to read only specific JSON files, but not all. How do I do it?

Code:

for i in bucket:
    try:
          result = client.list_objects(Bucket=i,Prefix = 'PROCESSED_BY/FILE_JSON', Delimiter='/')
          content_object = s3.Object(i, "PROCESSED_BY/FILE_JSON/?Account.json")
          file_content = content_object.get()['Body'].read().decode('utf-8')
          json_content = json.loads(file_content)
    except KeyError:
          pass

Bucket structure example.

test-eob/PROCESSED_BY/FILE_JSON/222-Account.json
test-eob/PROCESSED_BY/FILE_JSON/1212121-Account.json
test-eob/PROCESSED_BY/FILE_JSON/122-multi.json
test-eob/PROCESSED_BY/FILE_JSON/qwqwq-Account.json
test-eob/PROCESSED_BY/FILE_JSON/wqwqw-multi.json

From the above list, I want to only read *-Account.json files.

How can I achieve this?

Body:
There are several ways to do this in Python. For example, checking if 'stringA' is in 'stringB':

list1=['test-eob/PROCESSED_BY/FILE_JSON/222-Account.json',
'test-eob/PROCESSED_BY/FILE_JSON/1212121-Account.json',
'test-eob/PROCESSED_BY/FILE_JSON/122-multi.json',
'test-eob/PROCESSED_BY/FILE_JSON/qwqwq-Account.json',
'test-eob/PROCESSED_BY/FILE_JSON/wqwqw-multi.json',]

for i in list1:
    if 'Account' in i:
        print (i)
    else:
        pass


问:
Android. JSON parser return null in my new module
I created a new module in my project where I need parse JSON file, but parser(I used GSON) returns null. Before the module was created in the project, the parser worked. Json string from file is correct.

file.json

```<code>{"link":"https://google.com/","title":"Google"}
</code>```

how I parse

```<code>BrowserLink browserLink = gson.fromJson(json, BrowserLink.class);
</code>```

BrowserLink.java

```<code>public class BrowserLink {
    private String title;

    private String link;

    @NonNull
    @Override
    public String toString() {
        return "title: " + title + "; link: " + link;
    }
}
</code>```

Result from browserLink.toString()

```<code>title = title: null; link: null
</code>```

What should I do with the module for work parser?

答:
Fixed after Android Studio and Gradle update
https://developer.android.com/studio/write/java8-support#library-desugaring</p>

Body:
I created a new module in my project where I need parse JSON file, but parser(I used GSON) returns null. Before the module was created in the project, the parser worked. Json string from file is correct.

file.json

{"link":"https://google.com/","title":"Google"}

how I parse

BrowserLink browserLink = gson.fromJson(json, BrowserLink.class);

BrowserLink.java

public class BrowserLink {
    private String title;

    private String link;

    @NonNull
    @Override
    public String toString() {
        return "title: " + title + "; link: " + link;
    }
}

Result from browserLink.toString()

title = title: null; link: null

What should I do with the module for work parser?


问:
$.getJSON PHP alternative
$.getJSON might be misleading, but what I want to do is get JSON from a url via a PHP file.

```<code>var url = "https://script.google.com/macros/s/XXXXXXXXXX/exec?action=read";
$.getJSON(url, function (json) {
//DO SOMETHING WITH THE DATA
}
</code>```

This works fine in javascript. When I google get JSON from url maybe it's because I'm learning PHP but I can't seem to find an answer that works. Or when I google $.getJSON I get people trying to get Json from a PHP file.

All my data is stored via a googlesheet that I access by calling google script and it sends it back and I can take the information I want e.g

```<code>json.records[0].NAME;
</code>```

I want to pass some data to a PHP file that I can't fathom how to do that.

Any help would be greatly appreciated.

答:
It's simple as js:

$content = file_get_contents('https://script.google.com/macros/s/XXXXXXXXXX/exec?action=read');
$data = json_decode($content); // return object
$data = json_decode($content, true); // return array
```

Title: $.getJSON PHP alternative

Body:
$.getJSON might be misleading, but what I want to do is get JSON from a url via a PHP file.

var url = "https://script.google.com/macros/s/XXXXXXXXXX/exec?action=read";
$.getJSON(url, function (json) {
//DO SOMETHING WITH THE DATA
}

This works fine in javascript. When I google get JSON from url maybe it's because I'm learning PHP but I can't seem to find an answer that works. Or when I google $.getJSON I get people trying to get Json from a PHP file.

All my data is stored via a googlesheet that I access by calling google script and it sends it back and I can take the information I want e.g

json.records[0].NAME;

I want to pass some data to a PHP file that I can't fathom how to do that.

Any help would be greatly appreciated.


问:
Correct use of fasthttp.Client combined with goroutines
I am new to Go and am looking for the correct way of using net/http or fasthttp with goroutines. Unfortunately there are not many fasthttp client examples out there.

I found the following code: (Example1)

```<code>package main

import (
    "bufio"
    "fmt"
    "github.com/valyala/fasthttp"
    "log"
    "net"
    "os"
    "sync"
    "time"
)

func grabPage(fastClient *fasthttp.Client, i int, wg *sync.WaitGroup) {
    defer wg.Done()
    _, body, err := fastClient.GetTimeout(nil, "https://en.wikipedia.org/wiki/Immanuel_Kant", time.Duration(time.Second*20))
    if err != nil {
        log.Fatal(err)
    }
    f, err := os.Create(fmt.Sprintf("./data/%d.txt", i))
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    w := bufio.NewWriter(f)
    w.Write(body)
}

func main() {
    var wg sync.WaitGroup
    total := 500

    c := &fasthttp.Client{
        Dial: func(addr string) (net.Conn, error) {
            return fasthttp.DialTimeout(addr, time.Second*10)
        },
        MaxConnsPerHost: total,
    }

    wg.Add(total)
    for index := 0; index < total; index++ {
        go grabPage(c, index, &wg)
    }
    wg.Wait()
}
</code>```

In this code the developer creates a fasthttp.Client instance in the main() function and passes it to the goroutine using go grabPage(c, ...). For my understanding, this way you create one instance and all the requests use this one instance to do the job.

On another page, a developer uses something like that: (Example2)

```<code>func grabPage(i int, wg *sync.WaitGroup) {
    defer wg.Done()

    fastClient := &fasthttp.Client{
        Dial: func(addr string) (net.Conn, error) {
            return fasthttp.DialTimeout(addr, time.Second*10)
        },
        MaxConnsPerHost: 500,
    }

    _, body, err := fastClient.GetTimeout(nil, "https://en.wikipedia.org/wiki/Immanuel_Kant", time.Duration(time.Second*20))
    if err != nil {
        log.Fatal(err)
    }
    f, err := os.Create(fmt.Sprintf("./data/%d.txt", i))
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    w := bufio.NewWriter(f)
    w.Write(body)
}
</code>```

The big question is, are both solutions correct?
Or does the Example2 solution really create a new instance and use a lot of memory for every goroutine?

I made the examples out of snippets for my question, in the Example2 for sure defer are missing. This is not part of the question.

A small side question:
(fastClient *fasthttp.Client, i int, wg *sync.WaitGroup) -> fastClient and wg are pointers, so why call grabPage(c, index, &wg) and not grabPage(&c, index, &wg)?

答:
The big answer: both are correct (as in they work just fine), just different.

Per the docs, a fasthttp.Client is safe for concurrent use so sharing one instance is fine. It may run into concurrent connection limits but that might not be an issue.

The second example does have some overhead and will not be able to reuse connections or parameters, but again this could be a use case where it does not matter (if I only perform two operations, saving on the overhead might not be worth optimizing for).

For the second part of the question:

c is already a *fasthttp.Client, so there's not need to take its address (&fasthttp.Client returns a pointer to a new fasthttp.Client)

wg is a plain sync.WaitGroup so the address must be taken

Body:
I am new to Go and am looking for the correct way of using net/http or fasthttp with goroutines. Unfortunately there are not many fasthttp client examples out there.

I found the following code: (Example1)

package main

import (
    "bufio"
    "fmt"
    "github.com/valyala/fasthttp"
    "log"
    "net"
    "os"
    "sync"
    "time"
)

func grabPage(fastClient *fasthttp.Client, i int, wg *sync.WaitGroup) {
    defer wg.Done()
    _, body, err := fastClient.GetTimeout(nil, "https://en.wikipedia.org/wiki/Immanuel_Kant", time.Duration(time.Second*20))
    if err != nil {
        log.Fatal(err)
    }
    f, err := os.Create(fmt.Sprintf("./data/%d.txt", i))
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    w := bufio.NewWriter(f)
    w.Write(body)
}

func main() {
    var wg sync.WaitGroup
    total := 500

    c := &fasthttp.Client{
        Dial: func(addr string) (net.Conn, error) {
            return fasthttp.DialTimeout(addr, time.Second*10)
        },
        MaxConnsPerHost: total,
    }

    wg.Add(total)
    for index := 0; index < total; index++ {
        go grabPage(c, index, &wg)
    }
    wg.Wait()
}

In this code the developer creates a fasthttp.Client instance in the main() function and passes it to the goroutine using go grabPage(c, ...). For my understanding, this way you create one instance and all the requests use this one instance to do the job.

On another page, a developer uses something like that: (Example2)

func grabPage(i int, wg *sync.WaitGroup) {
    defer wg.Done()

    fastClient := &fasthttp.Client{
        Dial: func(addr string) (net.Conn, error) {
            return fasthttp.DialTimeout(addr, time.Second*10)
        },
        MaxConnsPerHost: 500,
    }

    _, body, err := fastClient.GetTimeout(nil, "https://en.wikipedia.org/wiki/Immanuel_Kant", time.Duration(time.Second*20))
    if err != nil {
        log.Fatal(err)
    }
    f, err := os.Create(fmt.Sprintf("./data/%d.txt", i))
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    w := bufio.NewWriter(f)
    w.Write(body)
}

The big question is, are both solutions correct?
Or does the Example2 solution really create a new instance and use a lot of memory for every goroutine?

I made the examples out of snippets for my question, in the Example2 for sure defer are missing. This is not part of the question.

A small side question:
(fastClient *fasthttp.Client, i int, wg *sync.WaitGroup) -> fastClient and wg are pointers, so why call grabPage(c, index, &wg) and not grabPage(&c, index, &wg)?


问:
Taking details from a map and saving it into another?
I have a map like this

```<code>map<string, pair< pair<int, int>, string> >
</code>```

what is the easiest way to get only the two strings and save into another map like this

```<code>map<string, string>
</code>```

?
I mean is there another way other than something like this??

```<code>    map<string, pair< pair<int, int>, string> >  info;
    map<string, pair< pair<int, int>, string> >::iterator i;
    map<string, string> something;

    for(i=info.begin(); i!=info.end(); ++i)
        something[*i).first] = ((*i).second).second;
</code>```

答:
```<code>map<string, pair< pair<int, int>, string> > map1 /* = ... */;
map<string, string> map2;

BOOST_FOREACH (const pair<string, pair< pair<int, int>, string> > >& it, map1) {
   map2[it.first] = it.second.second;
}
</code>```

By the way, EWTYPE.

Body:
I have a map like this

map<string, pair< pair<int, int>, string> >

what is the easiest way to get only the two strings and save into another map like this

map<string, string>

?
I mean is there another way other than something like this??

    map<string, pair< pair<int, int>, string> >  info;
    map<string, pair< pair<int, int>, string> >::iterator i;
    map<string, string> something;

    for(i=info.begin(); i!=info.end(); ++i)
        something[*i).first] = ((*i).second).second;

Body:
map<string, pair< pair<int, int>, string> > map1 /* = ... */;
map<string, string> map2;

BOOST_FOREACH (const pair<string, pair< pair<int, int>, string> > >& it, map1) {
   map2[it.first] = it.second.second;
}

By the way, EWTYPE.


问:
metric-server : TLS handshake error from 20.99.219.64:57467: EOF
I have deployed metric server using :

```<code>kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.3.6/components.yaml
</code>```

Metric server pod is running but in logs I am getting error :

```<code>I0601 20:00:01.321004       1 log.go:172] http: TLS handshake error from 20.99.219.64:34903: EOF
I0601 20:00:01.321160       1 log.go:172] http: TLS handshake error from 20.99.219.64:22575: EOF
I0601 20:00:01.332318       1 log.go:172] http: TLS handshake error from 20.99.219.64:14603: EOF
I0601 20:00:01.333174       1 log.go:172] http: TLS handshake error from 20.99.219.64:22517: EOF
I0601 20:00:01.351649       1 log.go:172] http: TLS handshake error from 20.99.219.64:3598: EOF
</code>```

IP : 20.99.219.64
This is not present in Cluster. I have checked using :
kubectl get all --all-namespaces -o wide | grep "20.99.219.64"
Nothing is coming as O/P.

I have using Calico and initialize the cluster with --pod-network-cidr=20.96.0.0/12

Also kubectl top nodes is not working, Getting error :

```<code>node@kubemaster:~/Desktop/dashboard$ kubectl top nodes
Error from server (ServiceUnavailable): the server is currently unable to handle the request (get nodes.metrics.k8s.io)
</code>```

答:
During deployment of metrics-server remember to add following line in args section:

```<code>  - args:
    - --kubelet-insecure-tls
    - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
</code>```

Also add the following line at the spec:spec level outside of the previous containers level:

```<code>  hostNetwork: true
  restartPolicy: Always
</code>```

Remember to apply changes.

Metrics-server attempts to authorize itself using token authentication. Please ensure that you're running your kubelets with webhook token authentication turned on.

Speaking about TLS directly. TLS message is big packet and MTU in calico is wrong so change it according calico-project-mtu.

Execute command:

$ kubectl edit configmap calico-config -n kube-system  and change the MTU value from 1500 to 1430.

Take a look: metrics-server-mtu.

Body:
I have deployed metric server using :

kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.3.6/components.yaml

Metric server pod is running but in logs I am getting error :

I0601 20:00:01.321004       1 log.go:172] http: TLS handshake error from 20.99.219.64:34903: EOF
I0601 20:00:01.321160       1 log.go:172] http: TLS handshake error from 20.99.219.64:22575: EOF
I0601 20:00:01.332318       1 log.go:172] http: TLS handshake error from 20.99.219.64:14603: EOF
I0601 20:00:01.333174       1 log.go:172] http: TLS handshake error from 20.99.219.64:22517: EOF
I0601 20:00:01.351649       1 log.go:172] http: TLS handshake error from 20.99.219.64:3598: EOF

IP : 20.99.219.64
This is not present in Cluster. I have checked using :
kubectl get all --all-namespaces -o wide | grep "20.99.219.64"
Nothing is coming as O/P.

I have using Calico and initialize the cluster with --pod-network-cidr=20.96.0.0/12

Also kubectl top nodes is not working, Getting error :

node@kubemaster:~/Desktop/dashboard$ kubectl top nodes
Error from server (ServiceUnavailable): the server is currently unable to handle the request (get nodes.metrics.k8s.io)

Body:
During deployment of metrics-server remember to add following line in args section:

  - args:
    - --kubelet-insecure-tls
    - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname

Also add the following line at the spec:spec level outside of the previous containers level:

  hostNetwork: true
  restartPolicy: Always

Remember to apply changes.

Metrics-server attempts to authorize itself using token authentication. Please ensure that you're running your kubelets with webhook token authentication turned on.

Speaking about TLS directly. TLS message is big packet and MTU in calico is wrong so change it according calico-project-mtu.

Execute command:

$ kubectl edit configmap calico-config -n kube-system  and change the MTU value from 1500 to 1430.

Take a look: metrics-server-mtu.


问:
How to extend Jenkins job page with new links and icons
I'm developing my first Jenkins plugin and followed the tutorial at wiki.jenkins-ci.org. After adding a BuildStep and generating the results I now want to publish them to the user. I would like to do this via a new link entry on the job page and a corrsponding result view page.

Unfortunatelly I do not find the right extension points for the navigation bar at the left side, the main navigation links in the center as well as the new target page. Can somebody point me in the right direction or give me a link to a tutorial or blog post that explains this scenario?

Thanks

答:
An addition to @dchang comment:

I managed to make this functionality work also on pipelines by extending TransientActionFactory<WorkflowJob>:

```<code>@Extension
public static class PipelineLatestConsoleProjectActionFactory extends TransientActionFactory<WorkflowJob> {

    @Override
    public Class<WorkflowJob> type() {
        return WorkflowJob.class;
    }

    @Nonnull
    @Override
    public Collection<? extends Action> createFor(@Nonnull WorkflowJob job) {
        return Collections.singletonList(new LatestConsoleProjectAction(job));
    }
}
</code>```

Body:
An addition to @dchang comment:

I managed to make this functionality work also on pipelines by extending TransientActionFactory<WorkflowJob>:

@Extension
public static class PipelineLatestConsoleProjectActionFactory extends TransientActionFactory<WorkflowJob> {

    @Override
    public Class<WorkflowJob> type() {
        return WorkflowJob.class;
    }

    @Nonnull
    @Override
    public Collection<? extends Action> createFor(@Nonnull WorkflowJob job) {
        return Collections.singletonList(new LatestConsoleProjectAction(job));
    }
}


问:
React field onChange not firing when value gets inserted programatically (hooks, not classes)

I'm writing an app (from full stack open) which will search through countries, and display country information if only one country is selected.
The application works well when a human uses it, however, if more than 1 country is displayed, I want the user to be able to click a 'show' button next to the country name, and display the country information for the given country.

 I figured I could just create a function that changes the search field's value, and set the value to the given country's name.

My problem is, that the onChange on the input doesn't fire when it gets filled out programmatically.

I've tried create a new hook just for the input field, but I couldn't get that to work either.
How can I go about making my onChange trigger when the field is filled programmatically?

I want to do this in the function toggleShowCountry

Code:

```<code>
import React, {useState, useEffect} from 'react';

import axios from 'axios';

function App() {

  const [countries, setCountries] = useState([]);
  const [search, setSearch] = useState(countries);
  const [inputField, setInputField] = useState("");

  const fetchCountries = () => {
    axios
    .get('https://restcountries.eu/rest/v2/all')
    .then(response => {
      setCountries(response.data);
    });
  };
  useEffect(fetchCountries, []);

  const handleSearch = (e) => {
    e.preventDefault();
    const searchField = document.querySelector('#searchCountry').value;

      setSearch(Object.values(countries).filter(country =>
        country.name.toLowerCase().includes(searchField.toLowerCase())))

  }

  const toggleShowCountry = (props) => {

    const searchField = document.querySelector('#searchCountry');
    searchField.value = props;

  }

  return (
    <div>
      <h2>Search countries</h2>
      <Search handleSearch={handleSearch} />
      <Display countries={search} toggleShowCountry={toggleShowCountry} />
    </div>
  )
}

const Display = (props) => {

  const countries = props.countries;
  let filteredCountries = countries.map(country => country);

  if (countries.length > 10){
    return(
      <>
        <p>Too many matches, specify another filter.</p>
      </>
    )
  } else if (countries.length === 1){
    return (
      <>
      {filteredCountries.map(country =>
        <div key={country}>
          <ShowCountry country={country} key={country} />

        </div>
      )}

      </>
    )
  } else {
    return (
      <>

        {filteredCountries.map(country =>
          <ul key={country.name}>
            <FilteredCountries country={country} key={country.name} toggleShowCountry={props.toggleShowCountry}/>
          </ul>
        )}
      </>
    )
  }
}

const FilteredCountries = (props) => {
  const country = props.country;
  return (
    <>
      <li>{country.name} <button onClick={() => props.toggleShowCountry(country.name)}>Show</button></li>
    </>
  )
}

const ShowCountry = ({country}) => {

  return (
    <>
      <h2>{country.name}</h2>
      <p>Capital: {country.capital}</p>
      <p>Population: {country.population}</p>

      <h3><strong>Languages</strong></h3>
      <ul>
        {country.languages.map(language =>
          <li key={language.name}>{language.name}</li>
        )}
      </ul>
      <img src={country.flag} alt="flag" width="100px"/>
    </>
  )
}

const Search = (props) => {
  return (
    <div>
      <form>
        <div>
          <label htmlFor="countries">Enter country </label>
          <input name="countries" id="searchCountry" onChange={props.handleSearch} />
        </div>
      </form>
    </div>
  )
}

export default App;
</code>```

答:
You can call setSearch also and then it work:

```<code>const toggleShowCountry = (props) => {
  const searchField = document.querySelector('#searchCountry');
  searchField.value = props;
  setSearch(Object.values(countries).filter(country =>
    country.name.toLowerCase() === props.toLowerCase()))
}
</code>```

See in playground: https://jscomplete.com/playground/s505973

Body:
I'm writing an app (from full stack open) which will search through countries, and display country information if only one country is selected.
The application works well when a human uses it, however, if more than 1 country is displayed, I want the user to be able to click a 'show' button next to the country name, and display the country information for the given country.

 I figured I could just create a function that changes the search field's value, and set the value to the given country's name.

My problem is, that the onChange on the input doesn't fire when it gets filled out programmatically.

I've tried create a new hook just for the input field, but I couldn't get that to work either.
How can I go about making my onChange trigger when the field is filled programmatically?

I want to do this in the function toggleShowCountry

Code:

import React, {useState, useEffect} from 'react';

import axios from 'axios';

function App() {

  const [countries, setCountries] = useState([]);
  const [search, setSearch] = useState(countries);
  const [inputField, setInputField] = useState("");

  const fetchCountries = () => {
    axios
    .get('https://restcountries.eu/rest/v2/all')
    .then(response => {
      setCountries(response.data);
    });
  };
  useEffect(fetchCountries, []);

  const handleSearch = (e) => {
    e.preventDefault();
    const searchField = document.querySelector('#searchCountry').value;

      setSearch(Object.values(countries).filter(country =>
        country.name.toLowerCase().includes(searchField.toLowerCase())))

  }

  const toggleShowCountry = (props) => {

    const searchField = document.querySelector('#searchCountry');
    searchField.value = props;

  }

  return (

Search countries

      <Search handleSearch={handleSearch} />
      <Display countries={search} toggleShowCountry={toggleShowCountry} />

  )
}

const Display = (props) => {

  const countries = props.countries;
  let filteredCountries = countries.map(country => country);

  if (countries.length > 10){
    return(
      <>

Too many matches, specify another filter.

      </>
    )
  } else if (countries.length === 1){
    return (
      <>
      {filteredCountries.map(country =>

          <ShowCountry country={country} key={country} />

      )}

      </>
    )
  } else {
    return (
      <>

        {filteredCountries.map(country =>

            <FilteredCountries country={country} key={country.name} toggleShowCountry={props.toggleShowCountry}/>

        )}
      </>
    )
  }
}

const FilteredCountries = (props) => {
  const country = props.country;
  return (
    <>

{country.name} <button onClick={() => props.toggleShowCountry(country.name)}>Show</button>

    </>
  )
}

const ShowCountry = ({country}) => {

  return (
    <>

{country.name}

Capital: {country.capital}

Population: {country.population}

Languages

        {country.languages.map(language =>

{language.name}

        )}

    </>
  )
}

const Search = (props) => {
  return (

      <form>

          Enter country
          <input name="countries" id="searchCountry" onChange={props.handleSearch} />

      </form>

  )
}

export default App;

Body:
You can call setSearch also and then it work:

const toggleShowCountry = (props) => {
  const searchField = document.querySelector('#searchCountry');
  searchField.value = props;
  setSearch(Object.values(countries).filter(country =>
    country.name.toLowerCase() === props.toLowerCase()))
}

See in playground: https://jscomplete.com/playground/s505973


问:
Can't access Azure Appservice protected by AAD from Postman
I have an app service say https://blahablah.azurewebsites.net to which I have hosted an ASP. Net web api project(An api that returns list of to do items by GET request), so that I can access the API without any authentication using https://blahablah.azurewebsites.net/api/TodoItems as i had TodoItems as my controller.

Now when I create an Azure AD and set Advanced Authentication of the app service; I can't access the api on the previous endpoint; When I use postman with the client id, secret, auth and token endpoints, it says my redirect URL is not valid;

So what should be my redirect URL? How can i successfully send a GET request from POSTMAN?

Update 1: My endpoints were wrong, and I corrected it to login.microsoftonline.com instead of login.microsoft.com, so I'm getting the access token, but when I'm sending a get request to above api with that token in header, it still says 401 unauthorised.
And i'm using redirect url as https://www.getpostman.com/oauth2/callback

Update 2: Here is my configuration

1)I have 2 AAD apps: blahablahAAD aap and PostmanAAD app

2)For app service, blahablah i use the first AAD app thru Express authentication of Azure Active Directory;

3)I have made https://blahablah.azurewebsites.net/api as the first AAD app's Application ID URI, and hence am able to expose https://blahablah.azurewebsites.net/api/TodoItems with TodoItems as scope.

4)I have added the API to "API permissions" of the first AAD app; (uptil now it works well in browser asking me for login and then taking me to the endpoint;)

5) For the PostmanAAD, I use it's client id,secret in Postman and get the token; I send it as request header to API;but it failss

6) I have added PostmanAAD's client id in "Expose API->add client application" of blahablahAAD.

7) I have done step 4 for PostmanAAD also

8) I have granted admin consent to all in default directory.

Note: I haven't added any authorization related code to my ASP .NET web api project that i hosted as app service, but i believe i can access it without writing code(as in AAD will do the task for me).

答:
Set resource url as the guid of the azure ad app instead of application id url.

Click azure ad app and choose Application Id in Overview.


问:
What is the best strategy to select which parameters to use for Geode server and locator startup script
Our company uses Geode services for some of our applications, we are making use of Geode Member group configurations as well for maintaining different regions.

We have been undergoing an effort of migrating our applications from Geode version 1.6 to the latest version 1.12.

We have seen dramatic performance decrease after the upgrade, if we use the older parameters for the server and locator startup scripts, and things work fine when we remove those parameters.

We are now planning to take the route of understanding the parameters (earlier used) and available, to determine the most optimal configurations for the server and locator to get the best out of the new Geode version.

I was wondering if someone has any best practices or recommendations to follow for this task.

Below are the configurations for the Geode locator and server startup scripts for old and new versions.

Locator startup command

---Old configurations ( works great with Geode 1.6 version but not with any version after Geode 1.8)

```<code>gfsh start locator --locators=$locators_str --name=${EC2_HOSTNAME}.aws.compnaynamedigital.net --initial-heap=2G --max-heap=2G --dir=/opt/compnayname/geode/locator --J=-Dlog4j.configurationFile=/opt/compnayname/geode/log4j2-locator.xml --J=-DCLUSTER=${ECS_CLUSTER} --J='-javaagent:/opt/compnayname/geode/jmxtrans-agent-1.2.6.jar=/opt/compnayname/geode/jmxtrans-agent-locator.xml' --J=-Dgemfire.distributed-system-id=${DISTRIBUTED_SYSTEM_ID} --J=-Dgemfire.member-timeout=30000 --J=-Dgemfire.max-num-reconnect-tries=0 --J=-Dgemfire.jmx-manager=true --J=-Dgemfire.jmx-manager-start=true --J=-Dgemfire.jmx-manager-port=1099 --J=-Dgemfire.http-service-port=0 --J=-Dgemfire.log-level=info --J=-Dgemfire.log-file-size-limit=10 --J=-Dgemfire.log-disk-space-limit=10 --J=-Dgemfire.disable-auto-reconnect=true
</code>```

---New configuration (works great with all versions)

```<code>gfsh start locator --locators=$locators_str --name=${EC2_HOSTNAME}.aws.compnaynamedigital.net --J=-Xmx2048m --dir=/opt/compnayname/geode/locator --J=-Dlog4j.configurationFile=/opt/compnayname/geode/log4j2-locator.xml --J='-javaagent:/opt/compnayname/geode/jmxtrans-agent-1.2.6.jar=/opt/compnayname/geode/jmxtrans-agent-locator.xml'
</code>```

Server Startup command

---Old configurations ( works great with Geode 1.6 version but not with any version after Geode 1.8)

```<code>gfsh start server --locators=$locators_str --name=${EC2_HOSTNAME}.aws.compnaynamedigital.net --initial-heap=${GEODE_INIT_HEAP} --max-heap=${GEODE_MAX_HEAP} --group=${SERVER_GROUP} --dir=/opt/compnayname/geode/server --classpath=/opt/compnayname/geode/services-geode.jar --J=-Dlog4j.configurationFile=/opt/compnayname/geode/log4j2-server.xml --J=-DCLUSTER=${ECS_CLUSTER} --J='-javaagent:/opt/compnayname/geode/jmxtrans-agent-1.2.6.jar=/opt/compnayname/geode/jmxtrans-agent-server.xml' --J=-Dgemfire.distributed-system-id=${DISTRIBUTED_SYSTEM_ID} --J=-Dgemfire.member-timeout=30000 --J=-Dgemfire.max-num-reconnect-tries=0 --J=-Dgemfire.socket-buffer-size=16777215 --J=-Dgemfire.off-heap-memory-size=${GEODE_OFF_HEAP} --J=-XX:+UseParNewGC --J=-XX:+UseConcMarkSweepGC --J=-XX:CMSInitiatingOccupancyFraction=60 --eviction-heap-percentage=70 --critical-heap-percentage=90 --J=-Dgemfire.http-service-port=0 --J=-Dgemfire.log-level=info --J=-Dgemfire.log-file-size-limit=10 --J=-Dgemfire.log-disk-space-limit=10 --J=-Dgemfire.disable-auto-reconnect=true ${ADDTL_GEODE_SERVER_OPTS}
</code>```

---New configuration (works great with all versions)

```<code>gfsh start server --locators=$locators_str --name=${EC2_HOSTNAME}.aws.compnaynamedigital.net --J=-Xmx${GEODE_MAX_HEAP}  --group=${SERVER_GROUP} --dir=/opt/compnayname/geode/server --classpath=/opt/compnayname/geode/services-geode.jar --J=-Dlog4j.configurationFile=/opt/compnayname/geode/log4j2-server.xml --J='-javaagent:/opt/compnayname/geode/jmxtrans-agent-1.2.6.jar=/opt/compnayname/geode/jmxtrans-agent-server.xml'
</code>```

Test Environment Details

We are using the exact same environment (read AWS) for testing the old and new configurations and performing the same test to measure the response time. We are using 3 Geode locators and 3 Geode servers for the different member groups.

The only difference is the Geode version

We are actually doing a count operation (we have written a count function to execute on Geode regions to count the records existing in the downloaded data which is actually data sketches (https://datasketches.apache.org/)). This count operation on the same data in the same testing environment is giving a drastically slow response with the old configuration using any Geode version beyond 1.8

Another surprising thing is that if I use the old configurations in my local laptop (my laptop serves as locator and server both) with any Geode version greater than 1.8 (including the latest version of Geode), then I am not seeing this issue. Somehow these extra configurations are causing slowness in the AWS environment in the distributed infrastructure.

Please let me know if more information is required and I will be glad to provide more details.

Any information on this will be appreciated.

答:
The main difference I see is the inclusion of --J='-javaagent:/opt/xyz/geode/jmxtrans-agent-1.2.6.jar=/opt/xyz/geode/jmxtrans-agent-server.xml' in the startup parameters. This seems to be a third party Java Agent to expose several JVM metrics through JMX.

Do you know if the agent itself is modifying the byte code?, I've seen negative effects of that approach for Geode applications in the past (not performance related, though). Have you tried upgrading the agent to the latest available version (1.2.10)?. As a side note, Geode already exposes a lot of metrics and information through JMX out of the box, is there any reason why you're relying on yet another external tool for this?.

We have seen dramatic performance decrease after the upgrade

How are you measuring performance?, where do you see the degradation?, are you executing exactly the same workload on exactly the same machines, where the only difference is the Geode version?. There are several actors in play here.

That said, diagnosing and troubleshooting performance degradations can be a long and though process, so my suggestion would be to open a Geode JIRA Ticket with all the relevant information and artefacts.

Cheers.

Body:
Our company uses Geode services for some of our applications, we are making use of Geode Member group configurations as well for maintaining different regions.

We have been undergoing an effort of migrating our applications from Geode version 1.6 to the latest version 1.12.

We have seen dramatic performance decrease after the upgrade, if we use the older parameters for the server and locator startup scripts, and things work fine when we remove those parameters.

We are now planning to take the route of understanding the parameters (earlier used) and available, to determine the most optimal configurations for the server and locator to get the best out of the new Geode version.

I was wondering if someone has any best practices or recommendations to follow for this task.

Below are the configurations for the Geode locator and server startup scripts for old and new versions.

Locator startup command

---Old configurations ( works great with Geode 1.6 version but not with any version after Geode 1.8)

gfsh start locator --locators=$locators_str --name=${EC2_HOSTNAME}.aws.compnaynamedigital.net --initial-heap=2G --max-heap=2G --dir=/opt/compnayname/geode/locator --J=-Dlog4j.configurationFile=/opt/compnayname/geode/log4j2-locator.xml --J=-DCLUSTER=${ECS_CLUSTER} --J='-javaagent:/opt/compnayname/geode/jmxtrans-agent-1.2.6.jar=/opt/compnayname/geode/jmxtrans-agent-locator.xml' --J=-Dgemfire.distributed-system-id=${DISTRIBUTED_SYSTEM_ID} --J=-Dgemfire.member-timeout=30000 --J=-Dgemfire.max-num-reconnect-tries=0 --J=-Dgemfire.jmx-manager=true --J=-Dgemfire.jmx-manager-start=true --J=-Dgemfire.jmx-manager-port=1099 --J=-Dgemfire.http-service-port=0 --J=-Dgemfire.log-level=info --J=-Dgemfire.log-file-size-limit=10 --J=-Dgemfire.log-disk-space-limit=10 --J=-Dgemfire.disable-auto-reconnect=true

---New configuration (works great with all versions)

gfsh start locator --locators=$locators_str --name=${EC2_HOSTNAME}.aws.compnaynamedigital.net --J=-Xmx2048m --dir=/opt/compnayname/geode/locator --J=-Dlog4j.configurationFile=/opt/compnayname/geode/log4j2-locator.xml --J='-javaagent:/opt/compnayname/geode/jmxtrans-agent-1.2.6.jar=/opt/compnayname/geode/jmxtrans-agent-locator.xml'

Server Startup command

---Old configurations ( works great with Geode 1.6 version but not with any version after Geode 1.8)

gfsh start server --locators=$locators_str --name=${EC2_HOSTNAME}.aws.compnaynamedigital.net --initial-heap=${GEODE_INIT_HEAP} --max-heap=${GEODE_MAX_HEAP} --group=${SERVER_GROUP} --dir=/opt/compnayname/geode/server --classpath=/opt/compnayname/geode/services-geode.jar --J=-Dlog4j.configurationFile=/opt/compnayname/geode/log4j2-server.xml --J=-DCLUSTER=${ECS_CLUSTER} --J='-javaagent:/opt/compnayname/geode/jmxtrans-agent-1.2.6.jar=/opt/compnayname/geode/jmxtrans-agent-server.xml' --J=-Dgemfire.distributed-system-id=${DISTRIBUTED_SYSTEM_ID} --J=-Dgemfire.member-timeout=30000 --J=-Dgemfire.max-num-reconnect-tries=0 --J=-Dgemfire.socket-buffer-size=16777215 --J=-Dgemfire.off-heap-memory-size=${GEODE_OFF_HEAP} --J=-XX:+UseParNewGC --J=-XX:+UseConcMarkSweepGC --J=-XX:CMSInitiatingOccupancyFraction=60 --eviction-heap-percentage=70 --critical-heap-percentage=90 --J=-Dgemfire.http-service-port=0 --J=-Dgemfire.log-level=info --J=-Dgemfire.log-file-size-limit=10 --J=-Dgemfire.log-disk-space-limit=10 --J=-Dgemfire.disable-auto-reconnect=true ${ADDTL_GEODE_SERVER_OPTS}

---New configuration (works great with all versions)

gfsh start server --locators=$locators_str --name=${EC2_HOSTNAME}.aws.compnaynamedigital.net --J=-Xmx${GEODE_MAX_HEAP}  --group=${SERVER_GROUP} --dir=/opt/compnayname/geode/server --classpath=/opt/compnayname/geode/services-geode.jar --J=-Dlog4j.configurationFile=/opt/compnayname/geode/log4j2-server.xml --J='-javaagent:/opt/compnayname/geode/jmxtrans-agent-1.2.6.jar=/opt/compnayname/geode/jmxtrans-agent-server.xml'

Test Environment Details

We are using the exact same environment (read AWS) for testing the old and new configurations and performing the same test to measure the response time. We are using 3 Geode locators and 3 Geode servers for the different member groups.

The only difference is the Geode version

We are actually doing a count operation (we have written a count function to execute on Geode regions to count the records existing in the downloaded data which is actually data sketches (https://datasketches.apache.org/)). This count operation on the same data in the same testing environment is giving a drastically slow response with the old configuration using any Geode version beyond 1.8

Another surprising thing is that if I use the old configurations in my local laptop (my laptop serves as locator and server both) with any Geode version greater than 1.8 (including the latest version of Geode), then I am not seeing this issue. Somehow these extra configurations are causing slowness in the AWS environment in the distributed infrastructure.

Please let me know if more information is required and I will be glad to provide more details.

Any information on this will be appreciated.


问:
Pointers in insert function for Binary Search Tree (BST)
This program is a insert function for a binary search tree, I totally understand the concept behind it and everything.. the only thing I don't understand is this line :

```<code>BTree root = NULL;
</code>```

so as i understand root is a pointer that does not point to any thing thats why its NULL , but why its data type is BTree, is it not supposed to be _btree ?
I know there is a pointer *Btree but its not a datatype so how is it possible.

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

typedef struct _btree
{
    int v;
    struct _btree *left, *right;

} BTreeRec , *BTree;

BTree insert(BTree t, int v)
{
    if (t == NULL) {

        t = (BTree)malloc(sizeof(BTreeRec)); t->v = v;
        t->left = t->right = NULL;

    } else if (v < t->v)
        t->left = insert(t->left, v);
    else
        t->right = insert(t->right, v); return t;
}

int main() {

 BTree root = NULL;

}

</code>```

答:
Derived types can be declared via typedef. Here it happens at:

```<code>typedef struct _btree {...} BTreeRec , *BTree;
</code>```

It declares BTreeRec as a synonym for struct _btree, and Btree as a synonym for struct _btree *.

So BTree root = NULL; is equivalent to:

```<code>struct _btree *root = NULL;
</code>```

Body:
This program is a insert function for a binary search tree, I totally understand the concept behind it and everything.. the only thing I don't understand is this line :

BTree root = NULL;

so as i understand root is a pointer that does not point to any thing thats why its NULL , but why its data type is BTree, is it not supposed to be _btree ?
I know there is a pointer *Btree but its not a datatype so how is it possible.

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

typedef struct _btree
{
    int v;
    struct _btree *left, *right;

} BTreeRec , *BTree;

BTree insert(BTree t, int v)
{
    if (t == NULL) {

        t = (BTree)malloc(sizeof(BTreeRec)); t->v = v;
        t->left = t->right = NULL;

    } else if (v < t->v)
        t->left = insert(t->left, v);
    else
        t->right = insert(t->right, v); return t;
}

int main() {

 BTree root = NULL;

}

Body:
Derived types can be declared via typedef. Here it happens at:

typedef struct _btree {...} BTreeRec , *BTree;

It declares BTreeRec as a synonym for struct _btree, and Btree as a synonym for struct _btree *.

So BTree root = NULL; is equivalent to:

struct _btree *root = NULL;


问:
How can I write gerrit.config format?

File gerrit.config

The audit configuration can be defined in the main gerrit.config
in a specific section dedicated to the audit-sl4j plugin.

gerrit.audit-sl4j.format
:   Output format of the audit record. Can be set to either JSON
    or CSV. By default, CSV.

gerrit.audit-sl4j.logName
:   Write audit to a separate log name under Gerrit logs directory.
    By default, audit records are put into the error_log.

How can I write the section gerrit.audit-sl4j.logName?
I have tried this :
But it doesn't work.

答:
You forgot to paste the example that doesn't work for you. While you update it I can share a working example in case it can be of any help.

This is the audit-sl4j configuration part of a working gerrit.config:

```<code>[plugin "audit-sl4j"]
  format = JSON
  logName = audit_log
</code>```

In this example, we are writing the audit logs to a file called audit_log in JSON format.

I hope this help.

Title: How can I write gerrit.config format?

Body:
You forgot to paste the example that doesn't work for you. While you update it I can share a working example in case it can be of any help.

This is the audit-sl4j configuration part of a working gerrit.config:

[plugin "audit-sl4j"]
  format = JSON
  logName = audit_log

In this example, we are writing the audit logs to a file called audit_log in JSON format.

I hope this help.


问:
Alternative to TfidfVectorizer
Is there any alternative to TfidfVectorizer function of sklearn.feature_extraction.text module? I've heard of fastText and GloVe, but couldn't find a good expalnation of how to use it to vectorize text.

Edit: Basically I've a feature called narration, which consists of English sentences. In order to feed this into any ML algorithm I've to convert it into a numeric matrix representation. TfIdf was one way. Is there any other way that I can try out? (May or may not be under sklearn)

答: What you are looking for is called text embedding, see for example this. Essentially for your naration feature, you are looking to turn a sequence into vectors, hence seq_to_vec. TfIdf is just one of the simplest ways of doing this, which yields a sparse (many more components are =0, than not). I suggest you look here for a good starting point.</p>

Title: Alternative to TfidfVectorizer


答:
The lines:

```<code>typedef struct _btree
{ int v;
struct _btree *left, *right;
} BTreeRec , *BTree;
</code>```

are equivalent to:

```<code>struct _btree {
     int v;
     struct _btree *left;
     struct _btree *right;
};
typedef struct _btree   BTreeRec;
typedef struct _btree * BTree;
</code>```

A typedef is like an alias for the name. And the * "sticks" with it. Every time your write BTree it's the same as struct _btree * with the star included. So your code is equivalent to:

```<code>struct _btree *insert(struct _btree *t, int v) {
   if (t == NULL) {
        t = malloc(sizeof(struct _btree));
        t->v = v;
        t->left = NULL;
        t->right = NULL;
   } else if (v < t->v) {
        t->left = insert(t->left, v);
   } else {
        t->right = insert(t->right, v);
   }
   return t;
}

int main() {
   struct _btree *root = NULL;
}
</code>```

Which is 500% more readable and the intention is much more clearer. Code is like a poem - it has to be nice to read it. As a general rule the use of typedef pointers is discouraged (unless you are implementing a specific case like an opaque library where you specifically want to use them). Subjectively: I am on the side that also doesn't like the use of typedef to hide a struct.

Title: Pointers in insert function for Binary Search Tree (BST)

Body:
The lines:

typedef struct _btree
{ int v;
struct _btree *left, *right;
} BTreeRec , *BTree;

are equivalent to:

struct _btree {
     int v;
     struct _btree *left;
     struct _btree *right;
};
typedef struct _btree   BTreeRec;
typedef struct _btree * BTree;

A typedef is like an alias for the name. And the * "sticks" with it. Every time your write BTree it's the same as struct _btree * with the star included. So your code is equivalent to:

struct _btree *insert(struct _btree *t, int v) {
   if (t == NULL) {
        t = malloc(sizeof(struct _btree));
        t->v = v;
        t->left = NULL;
        t->right = NULL;
   } else if (v < t->v) {
        t->left = insert(t->left, v);
   } else {
        t->right = insert(t->right, v);
   }
   return t;
}

int main() {
   struct _btree *root = NULL;
}

Which is 500% more readable and the intention is much more clearer. Code is like a poem - it has to be nice to read it. As a general rule the use of typedef pointers is discouraged (unless you are implementing a specific case like an opaque library where you specifically want to use them). Subjectively: I am on the side that also doesn't like the use of typedef to hide a struct.


问:
return statement is not working properly in for loop
```<code>def chek(name):
    for i in range(3):
        print(name)
        print(i)
        if i == 1:
            chek(name="name2")
        elif name == 'name2':
            print("changed name: ",name)
            return name

s = chek("name1")

print("final name:",s)
</code>```

In this code my expected output is :

```<code>name1
0
name1
1
name2
0
changed name: name2
final name: name2
</code>```

Actual output is :

```<code>name1
0
name1
1
name2
0
changed name:  name2
name1
2
final name:  None
</code>```

Can anyone help me to understand,
is anything wrong in my code or  it's is behavior

答:
Try with updating this part:

```<code>
if i == 1:
    return chek(name="name2")

</code>```

this would return the second check() calling value;

Body:
def chek(name):
    for i in range(3):
        print(name)
        print(i)
        if i == 1:
            chek(name="name2")
        elif name == 'name2':
            print("changed name: ",name)
            return name

s = chek("name1")

print("final name:",s)

In this code my expected output is :

name1
0
name1
1
name2
0
changed name: name2
final name: name2

Actual output is :

name1
0
name1
1
name2
0
changed name:  name2
name1
2
final name:  None

Can anyone help me to understand,
is anything wrong in my code or  it's is behavior

Body:
Try with updating this part:

if i == 1:
    return chek(name="name2")

this would return the second check() calling value;


问:
Where can I see deno downloaded packages?
I am new to deno and currently exploring for a minimum viable project in deno. I want to like npm which downloads the npm packages inside the folder node_modules, similarly I want to see the deno packages in a directory. In my current project I do not see any downloaded packages. Please suggest me where to look for deno packages. If I write dep.ts file to mention all the deno packages, can I use the same deno packages for some other projects. My question is bit similar to what Maven or Gradle in java handles. It means I want to know whether deno maintains a single folder in OS so that all the packages are downloaded and used in many projects. I want to check the directory containing the deno packages in windows 10.

答:
You can use deno info to get the cache directory of remote modules.

Sample output (Windows 10):
```<code>> deno info
DENO_DIR location: "C:\\Users\\ford\\AppData\\Local\\deno"
Remote modules cache: "C:\\Users\\ford\\AppData\\Local\\deno\\deps"
TypeScript compiler cache: "C:\\Users\\ford\\AppData\\Local\\deno\\gen"
</code>```
To get info about a single (remote) module:

deno info --unstable https://deno.land/std/fs/mod.ts # --unstable needed as of 1.0.3
```
Sample output:
```local: C:\Users\ford\AppData\Local\deno\deps\https\deno.land\434fe4a7...8f300799a073e0
type: TypeScript
compiled: C:\Users\ford\AppData\Local\deno\gen\https\deno.land\std\fs\mod.ts.js
map: C:\Users\ford\AppData\Local\deno\gen\https\deno.land\std\fs\mod.ts.js.map
deps:
https://deno.land/std/fs/mod.ts
  ├─┬ https://deno.land/std/fs/empty_dir.ts
  ...
```

local: Local path of source file (TS or JS)

compiled: Local path of compiled source code (.js, for TS only)

map: Local path of source map (TS only)

deps: Dependency tree of source file

Body:
You can use deno info to get the cache directory of remote modules.

Sample output (Windows 10):

> deno info
DENO_DIR location: "C:\\Users\\ford\\AppData\\Local\\deno"
Remote modules cache: "C:\\Users\\ford\\AppData\\Local\\deno\\deps"
TypeScript compiler cache: "C:\\Users\\ford\\AppData\\Local\\deno\\gen"

To get info about a single (remote) module:

deno info --unstable https://deno.land/std/fs/mod.ts # --unstable needed as of 1.0.3

Sample output:

local: C:\Users\ford\AppData\Local\deno\deps\https\deno.land\434fe4a7...8f300799a073e0
type: TypeScript
compiled: C:\Users\ford\AppData\Local\deno\gen\https\deno.land\std\fs\mod.ts.js
map: C:\Users\ford\AppData\Local\deno\gen\https\deno.land\std\fs\mod.ts.js.map
deps:
https://deno.land/std/fs/mod.ts
  ├─┬ https://deno.land/std/fs/empty_dir.ts
  ...

local: Local path of source file (TS or JS)

compiled: Local path of compiled source code (.js, for TS only)

map: Local path of source map (TS only)

deps: Dependency tree of source file


问:
Web scraping in Python - extract a value from website
I'm trying to extract two values from this website:

bizportal.co.il

One value is the dollar rate from the right, and from the left the drop/rise in percentage.

The problem is that, after I'm getting the dollar rate value, the number is rounded from some reason. (You can see in the terminal). I want to get the exactly number as shown in the website.

Is there some friendly documentation for web scraping in Python?

P.S: how can I get rid of the pop up Python terminal window when running a code in VS ? I just want the output will be in VS - in the interactive window.

```<code>my_url = "https://www.bizportal.co.il/forex/quote/generalview/22212222"

uClient = urlopen(my_url)

page_html = uClient.read()

uClient.close()

page_soup = BeautifulSoup(page_html, "html.parser")

div_class = page_soup.findAll("div",{"class":"data-row"})

print (div_class)
#print(div_class[0].text)
#print(div_class[1].text)
</code>```

答:
The problem is this element is being dynamically updated with Javascript. You will not be able to scrape the 'up to date' value with urllib or requests. When the page is loaded, it has a recent value populated (likely from a database) and then it is replaced with the real time number via Javascript.

In this case it would be better to use something like Selenium, to load the webpage - this allows the javascript to execute on the page, and then scrape the numbers.

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

options = Options()
options.add_argument("--headless") # allows you to scrape page without opening the browser window
driver = webdriver.Chrome('./chromedriver', options=options)

driver.get("https://www.bizportal.co.il/forex/quote/generalview/22212222")
time.sleep(1) # put in to allow JS time to load, sometimes works without.
values = driver.find_elements_by_class_name('num')
price = values[0].get_attribute("innerHTML")
change = values[1].find_element_by_css_selector("span").get_attribute("innerHTML")

print(price, "\n", change)
</code>```

Output:

```<code>╰─$ python selenium_scrape.py
3.483
 -0.74%
</code>```

You should familiarize yourself with Selenium, understand how to set it up, and run it - this includes installing the browser (in this case I am using Chrome, but you can use others), understanding where to get the browser driver (Chromedriver in this case) and understand how to parse the page. You can learn all about it here https://www.selenium.dev/documentation/en/

Body:
I'm trying to extract two values from this website:

bizportal.co.il

One value is the dollar rate from the right, and from the left the drop/rise in percentage.

The problem is that, after I'm getting the dollar rate value, the number is rounded from some reason. (You can see in the terminal). I want to get the exactly number as shown in the website.

Is there some friendly documentation for web scraping in Python?

P.S: how can I get rid of the pop up Python terminal window when running a code in VS ? I just want the output will be in VS - in the interactive window.

my_url = "https://www.bizportal.co.il/forex/quote/generalview/22212222"

uClient = urlopen(my_url)

page_html = uClient.read()

uClient.close()

page_soup = BeautifulSoup(page_html, "html.parser")

div_class = page_soup.findAll("div",{"class":"data-row"})

print (div_class)
#print(div_class[0].text)
#print(div_class[1].text)

Body:
The problem is this element is being dynamically updated with Javascript. You will not be able to scrape the 'up to date' value with urllib or requests. When the page is loaded, it has a recent value populated (likely from a database) and then it is replaced with the real time number via Javascript.

In this case it would be better to use something like Selenium, to load the webpage - this allows the javascript to execute on the page, and then scrape the numbers.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

options = Options()
options.add_argument("--headless") # allows you to scrape page without opening the browser window
driver = webdriver.Chrome('./chromedriver', options=options)

driver.get("https://www.bizportal.co.il/forex/quote/generalview/22212222")
time.sleep(1) # put in to allow JS time to load, sometimes works without.
values = driver.find_elements_by_class_name('num')
price = values[0].get_attribute("innerHTML")
change = values[1].find_element_by_css_selector("span").get_attribute("innerHTML")

print(price, "\n", change)

Output:

╰─$ python selenium_scrape.py
3.483
 -0.74%

You should familiarize yourself with Selenium, understand how to set it up, and run it - this includes installing the browser (in this case I am using Chrome, but you can use others), understanding where to get the browser driver (Chromedriver in this case) and understand how to parse the page. You can learn all about it here https://www.selenium.dev/documentation/en/


问:
How can I get a calendar weeks start and end date in Python?
I would like to have a function get_cw_borders(year: int, cw: int) -> Tuple[datetime.datetime, datetime.datetime] which should behave like this:

```<code>>>> get_cw_borders(2020, 17)
(datetime.datetime(2020, 4, 20), datetime.datetime(2020, 4, 26))

>>> get_cw_borders(2020, 18)
(datetime.datetime(2020, 4, 27), datetime.datetime(2020, 5, 3))

>>> get_cw_borders(2020, 1)
(datetime.datetime(2019, 12, 30), datetime.datetime(2020, 1, 5))

>>> get_cw_borders(2017, 1)
(datetime.datetime(2017, 1, 2), datetime.datetime(2017, 1, 8))
</code>```

I'm aware that some countries start the week on Sunday instead of Monday. I think (please correct me if I'm wrong) that this is just a constant offset for this function, so that would not be a big deal.

Is there a built-in function to get this?

Non-Duplicates

Thank you for linking similar questions.

Python: give start and end of week data from a given date: I don't have a given date

答:
datetime.strptime supports week number and week day in the format.
Note that the week day is required, but you can do something like:

```<code>def get_cw_borders(week_number):
    start = datetime.strptime(f"2020-{week_number}-0", "%Y-%U-%w")
    end = datetime.strptime(f"2020-{week_number}-6", "%Y-%U-%w")
    return (start, end)
</code>```

Note that %U and %w consider sunday as the first day of the week. If you want the week to start on monday, you can use %W, but need some extra work to make the week day work.

I think you can do the following when starting the week on monday:

```<code>def get_cw_borders_start_on_monday(week_number):
    # Week day 1 indicates monday
    start = datetime.strptime(f"2020-{week_number}-1", "%Y-%W-%w")
    # Week day 0 indicates sunday, at end of week when using %W
    end = datetime.strptime(f"2020-{week_number}-0", "%Y-%W-%w")
    return (start, end)
</code>```

Body:
I would like to have a function get_cw_borders(year: int, cw: int) -> Tuple[datetime.datetime, datetime.datetime] which should behave like this:

>>> get_cw_borders(2020, 17)
(datetime.datetime(2020, 4, 20), datetime.datetime(2020, 4, 26))

>>> get_cw_borders(2020, 18)
(datetime.datetime(2020, 4, 27), datetime.datetime(2020, 5, 3))

>>> get_cw_borders(2020, 1)
(datetime.datetime(2019, 12, 30), datetime.datetime(2020, 1, 5))

>>> get_cw_borders(2017, 1)
(datetime.datetime(2017, 1, 2), datetime.datetime(2017, 1, 8))

I'm aware that some countries start the week on Sunday instead of Monday. I think (please correct me if I'm wrong) that this is just a constant offset for this function, so that would not be a big deal.

Is there a built-in function to get this?

Non-Duplicates

Thank you for linking similar questions.

Python: give start and end of week data from a given date: I don't have a given date

Body:
datetime.strptime supports week number and week day in the format.
Note that the week day is required, but you can do something like:

def get_cw_borders(week_number):
    start = datetime.strptime(f"2020-{week_number}-0", "%Y-%U-%w")
    end = datetime.strptime(f"2020-{week_number}-6", "%Y-%U-%w")
    return (start, end)

Note that %U and %w consider sunday as the first day of the week. If you want the week to start on monday, you can use %W, but need some extra work to make the week day work.

I think you can do the following when starting the week on monday:

def get_cw_borders_start_on_monday(week_number):
    # Week day 1 indicates monday
    start = datetime.strptime(f"2020-{week_number}-1", "%Y-%W-%w")
    # Week day 0 indicates sunday, at end of week when using %W
    end = datetime.strptime(f"2020-{week_number}-0", "%Y-%W-%w")
    return (start, end)


问:
How to add .a libraries on flutter plugin via podspec
I am trying to include .a files on the iOS side of the plugin. Below is my file structure.

Now when I try to add .a files via vendored_libraries on podspec, pod install is successfully completed. And when I compile the code, I get Library Not Found  -lAccuraFace

I tried to add the .a file on the Link Binary With Libraries section on the build phase on the Pod target. It's still the same, how can I define the podspec in such a way that the .a file is included and linked automatically.

Here is my podspec file for the plugin

```<code>Pod::Spec.new do |s|
  s.name             = 'accuraemirates'
  s.version          = '0.0.1'
  s.summary          = 'A new Flutter plugin.'
  s.description      = <<-DESC
A new Flutter plugin.
                       DESC
  s.homepage         = 'http://example.com'
  s.license          = { :file => '../LICENSE' }
  s.author           = { 'Your Company' => 'email@example.com' }
  s.source           = { :path => '.' }
  s.source_files = 'Classes/**/*'
  s.dependency 'Flutter'
  s.public_header_files = 'Classes/*{.h}'
  s.private_header_files = 'Classes/CodeScan/**/*{.h,.cpp,.a}'
  s.platform = :ios, '8.0'
  s.preserve_paths = 'opencv2.framework'
  s.xcconfig = {
    'OTHER_LDFLAGS' => '-framework opencv2 -lAccuraFace',
  }
  s.ios.vendored_frameworks = 'opencv2.framework', "CoreVideo.framework", "Foundation.framework", "CoreGrpahics.framework",
  "Accelerate.framework", "CoreMedia.framework", "CoreImage.framework", "QuartzCore.framework", "AudioToolbox.framework", "CoreData.framework", "SystemConfiguration.framework"
  s.ios.vendored_libraries = 'Classes/Framework/*{.a}', "libz.1.dylib", "c++", "stdc++"

  # Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
  s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
  s.swift_version = '5.0'
end
</code>```

Here is the root podfile

```<code>ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def parse_KV_file(file, separator='=')
  file_abs_path = File.expand_path(file)
  if !File.exists? file_abs_path
    return [];
  end
  generated_key_values = {}
  skip_line_start_symbols = ["#", "/"]
  File.foreach(file_abs_path) do |line|
    next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
    plugin = line.split(pattern=separator)
    if plugin.length == 2
      podname = plugin[0].strip()
      path = plugin[1].strip()
      podpath = File.expand_path("#{path}", file_abs_path)
      generated_key_values[podname] = podpath
    else
      puts "Invalid plugin specification: #{line}"
    end
  end
  generated_key_values
end

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  # Flutter Pod

  copied_flutter_dir = File.join(__dir__, 'Flutter')
  copied_framework_path = File.join(copied_flutter_dir, 'Flutter.framework')
  copied_podspec_path = File.join(copied_flutter_dir, 'Flutter.podspec')
  unless File.exist?(copied_framework_path) && File.exist?(copied_podspec_path)
    # Copy Flutter.framework and Flutter.podspec to Flutter/ to have something to link against if the xcode backend script has not run yet.
    # That script will copy the correct debug/profile/release version of the framework based on the currently selected Xcode configuration.
    # CocoaPods will not embed the framework on pod install (before any build phases can generate) if the dylib does not exist.

    generated_xcode_build_settings_path = File.join(copied_flutter_dir, 'Generated.xcconfig')
    unless File.exist?(generated_xcode_build_settings_path)
      raise "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter pub get is executed first"
    end
    generated_xcode_build_settings = parse_KV_file(generated_xcode_build_settings_path)
    cached_framework_dir = generated_xcode_build_settings['FLUTTER_FRAMEWORK_DIR'];

    unless File.exist?(copied_framework_path)
      FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir)
    end
    unless File.exist?(copied_podspec_path)
      FileUtils.cp(File.join(cached_framework_dir, 'Flutter.podspec'), copied_flutter_dir)
    end
  end

  # Keep pod path relative so it can be checked into Podfile.lock.
  pod 'Flutter', :path => 'Flutter'

  # Plugin Pods

  # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock
  # referring to absolute paths on developers' machines.
  system('rm -rf .symlinks')
  system('mkdir -p .symlinks/plugins')
  plugin_pods = parse_KV_file('../.flutter-plugins')
  plugin_pods.each do |name, path|
    symlink = File.join('.symlinks', 'plugins', name)
    File.symlink(path, symlink)
    pod name, :path => File.join(symlink, 'ios')
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end
</code>```

Is it not possible to add/link .a libraries from podspec file on a flutter plugin.

答:
You definitely CAN add .a libraries, try to check the following configuration path

```<code>TARGETS->Build Settings->Search Paths-> Library Search Paths

</code>```

Right there, add path where .a library was located.

Here is a valid path configuration demo:

==========================================================================

UPDATE

For flutter plugin

As for ship as flutter plugin ,file with .a suffix is actually static library, here is a snippet for how to do it in a .podspec file:

```<code> s.subspec 'Core' do |sc|
    sc.ios.library = 'z'
    sc.frameworks = 'SystemConfiguration', 'QuartzCore', 'CoreText', 'WebKit'
    sc.source_files = 'AppboyKit/headers/AppboyKitLibrary/*.h', 'AppboyKit/ABKIdentifierForAdvertisingProvider.m', 'AppboyKit/ABKModalWebViewController.m', 'AppboyKit/ABKNoConnectionLocalization.m', 'AppboyKit/ABKLocationManagerProvider.m'
    sc.resource = 'AppboyKit/Appboy.bundle'
    sc.vendored_libraries = 'AppboyKit/libAppboyKitLibrary.a'
    sc.weak_framework = 'CoreTelephony', 'Social', 'Accounts', 'AdSupport', 'UserNotifications'
  end
</code>```

Pay attention to line start with sc.vendored_libraries there.Here is the complete source.

Body:
I am trying to include .a files on the iOS side of the plugin. Below is my file structure.

Now when I try to add .a files via vendored_libraries on podspec, pod install is successfully completed. And when I compile the code, I get Library Not Found  -lAccuraFace

I tried to add the .a file on the Link Binary With Libraries section on the build phase on the Pod target. It's still the same, how can I define the podspec in such a way that the .a file is included and linked automatically.

Here is my podspec file for the plugin

Pod::Spec.new do |s|
  s.name             = 'accuraemirates'
  s.version          = '0.0.1'
  s.summary          = 'A new Flutter plugin.'
  s.description      = <<-DESC
A new Flutter plugin.
                       DESC
  s.homepage         = 'http://example.com'
  s.license          = { :file => '../LICENSE' }
  s.author           = { 'Your Company' => 'email@example.com' }
  s.source           = { :path => '.' }
  s.source_files = 'Classes/**/*'
  s.dependency 'Flutter'
  s.public_header_files = 'Classes/*{.h}'
  s.private_header_files = 'Classes/CodeScan/**/*{.h,.cpp,.a}'
  s.platform = :ios, '8.0'
  s.preserve_paths = 'opencv2.framework'
  s.xcconfig = {
    'OTHER_LDFLAGS' => '-framework opencv2 -lAccuraFace',
  }
  s.ios.vendored_frameworks = 'opencv2.framework', "CoreVideo.framework", "Foundation.framework", "CoreGrpahics.framework",
  "Accelerate.framework", "CoreMedia.framework", "CoreImage.framework", "QuartzCore.framework", "AudioToolbox.framework", "CoreData.framework", "SystemConfiguration.framework"
  s.ios.vendored_libraries = 'Classes/Framework/*{.a}', "libz.1.dylib", "c++", "stdc++"

  # Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported.
  s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
  s.swift_version = '5.0'
end

Here is the root podfile

ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def parse_KV_file(file, separator='=')
  file_abs_path = File.expand_path(file)
  if !File.exists? file_abs_path
    return [];
  end
  generated_key_values = {}
  skip_line_start_symbols = ["#", "/"]
  File.foreach(file_abs_path) do |line|
    next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
    plugin = line.split(pattern=separator)
    if plugin.length == 2
      podname = plugin[0].strip()
      path = plugin[1].strip()
      podpath = File.expand_path("#{path}", file_abs_path)
      generated_key_values[podname] = podpath
    else
      puts "Invalid plugin specification: #{line}"
    end
  end
  generated_key_values
end

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  # Flutter Pod

  copied_flutter_dir = File.join(__dir__, 'Flutter')
  copied_framework_path = File.join(copied_flutter_dir, 'Flutter.framework')
  copied_podspec_path = File.join(copied_flutter_dir, 'Flutter.podspec')
  unless File.exist?(copied_framework_path) && File.exist?(copied_podspec_path)
    # Copy Flutter.framework and Flutter.podspec to Flutter/ to have something to link against if the xcode backend script has not run yet.
    # That script will copy the correct debug/profile/release version of the framework based on the currently selected Xcode configuration.
    # CocoaPods will not embed the framework on pod install (before any build phases can generate) if the dylib does not exist.

    generated_xcode_build_settings_path = File.join(copied_flutter_dir, 'Generated.xcconfig')
    unless File.exist?(generated_xcode_build_settings_path)
      raise "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter pub get is executed first"
    end
    generated_xcode_build_settings = parse_KV_file(generated_xcode_build_settings_path)
    cached_framework_dir = generated_xcode_build_settings['FLUTTER_FRAMEWORK_DIR'];

    unless File.exist?(copied_framework_path)
      FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir)
    end
    unless File.exist?(copied_podspec_path)
      FileUtils.cp(File.join(cached_framework_dir, 'Flutter.podspec'), copied_flutter_dir)
    end
  end

  # Keep pod path relative so it can be checked into Podfile.lock.
  pod 'Flutter', :path => 'Flutter'

  # Plugin Pods

  # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock
  # referring to absolute paths on developers' machines.
  system('rm -rf .symlinks')
  system('mkdir -p .symlinks/plugins')
  plugin_pods = parse_KV_file('../.flutter-plugins')
  plugin_pods.each do |name, path|
    symlink = File.join('.symlinks', 'plugins', name)
    File.symlink(path, symlink)
    pod name, :path => File.join(symlink, 'ios')
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end

Is it not possible to add/link .a libraries from podspec file on a flutter plugin.

Body:
You definitely CAN add .a libraries, try to check the following configuration path

TARGETS->Build Settings->Search Paths-> Library Search Paths

Right there, add path where .a library was located.

Here is a valid path configuration demo:

==========================================================================

UPDATE

For flutter plugin

As for ship as flutter plugin ,file with .a suffix is actually static library, here is a snippet for how to do it in a .podspec file:

 s.subspec 'Core' do |sc|
    sc.ios.library = 'z'
    sc.frameworks = 'SystemConfiguration', 'QuartzCore', 'CoreText', 'WebKit'
    sc.source_files = 'AppboyKit/headers/AppboyKitLibrary/*.h', 'AppboyKit/ABKIdentifierForAdvertisingProvider.m', 'AppboyKit/ABKModalWebViewController.m', 'AppboyKit/ABKNoConnectionLocalization.m', 'AppboyKit/ABKLocationManagerProvider.m'
    sc.resource = 'AppboyKit/Appboy.bundle'
    sc.vendored_libraries = 'AppboyKit/libAppboyKitLibrary.a'
    sc.weak_framework = 'CoreTelephony', 'Social', 'Accounts', 'AdSupport', 'UserNotifications'
  end

Pay attention to line start with sc.vendored_libraries there.Here is the complete source.


问:
Read files with only specific names from Amazon S3
I have connected to Amazon S3 and am trying to retrieve data from the JSON content from multiple buckets using the below code.

But I have to read only specific JSON files, but not all. How do I do it?

Code:

```<code>for i in bucket:
    try:
          result = client.list_objects(Bucket=i,Prefix = 'PROCESSED_BY/FILE_JSON', Delimiter='/')
          content_object = s3.Object(i, "PROCESSED_BY/FILE_JSON/?Account.json")
          file_content = content_object.get()['Body'].read().decode('utf-8')
          json_content = json.loads(file_content)
    except KeyError:
          pass
</code>```

Bucket structure example.

```<code>test-eob/PROCESSED_BY/FILE_JSON/222-Account.json
test-eob/PROCESSED_BY/FILE_JSON/1212121-Account.json
test-eob/PROCESSED_BY/FILE_JSON/122-multi.json
test-eob/PROCESSED_BY/FILE_JSON/qwqwq-Account.json
test-eob/PROCESSED_BY/FILE_JSON/wqwqw-multi.json
</code>```

From the above list, I want to only read *-Account.json files.

How can I achieve this?

答:
You can make use of a regex that matches your pattern from the list of objects.</p>

```<code>import re

MATCH = "FILE_JSON/.*?Account.json"

full_list = [
  "test-eob/PROCESSED_BY/FILE_JSON/222-Account.json",
  "test-eob/PROCESSED_BY/FILE_JSON/1212121-Account.json",
  "test-eob/PROCESSED_BY/FILE_JSON/122-multi.json",
  "test-eob/PROCESSED_BY/FILE_JSON/qwqwq-Account.json",
  "test-eob/PROCESSED_BY/FILE_JSON/wqwqw-multi.json"
]

for item in full_list:
  if re.search(MATCH, item):
    print(item)
</code>```

Body:
I have connected to Amazon S3 and am trying to retrieve data from the JSON content from multiple buckets using the below code.

But I have to read only specific JSON files, but not all. How do I do it?

Code:

for i in bucket:
    try:
          result = client.list_objects(Bucket=i,Prefix = 'PROCESSED_BY/FILE_JSON', Delimiter='/')
          content_object = s3.Object(i, "PROCESSED_BY/FILE_JSON/?Account.json")
          file_content = content_object.get()['Body'].read().decode('utf-8')
          json_content = json.loads(file_content)
    except KeyError:
          pass

Bucket structure example.

test-eob/PROCESSED_BY/FILE_JSON/222-Account.json
test-eob/PROCESSED_BY/FILE_JSON/1212121-Account.json
test-eob/PROCESSED_BY/FILE_JSON/122-multi.json
test-eob/PROCESSED_BY/FILE_JSON/qwqwq-Account.json
test-eob/PROCESSED_BY/FILE_JSON/wqwqw-multi.json

From the above list, I want to only read *-Account.json files.

How can I achieve this?

Body:
You can make use of a regex that matches your pattern from the list of objects.

import re

MATCH = "FILE_JSON/.*?Account.json"

full_list = [
  "test-eob/PROCESSED_BY/FILE_JSON/222-Account.json",
  "test-eob/PROCESSED_BY/FILE_JSON/1212121-Account.json",
  "test-eob/PROCESSED_BY/FILE_JSON/122-multi.json",
  "test-eob/PROCESSED_BY/FILE_JSON/qwqwq-Account.json",
  "test-eob/PROCESSED_BY/FILE_JSON/wqwqw-multi.json"
]

for item in full_list:
  if re.search(MATCH, item):
    print(item)


问:
How do I declare a function with optional parameters in C#
I want to write a class for creating Excel files from Datagridviews. I want to add a bottom line with Subtotals for selected columns and the number of those columns change from 1 to 3.
I want my function work like this

```<code>exportToExcel(string title, DataGridView dgv, int colId1, int colId2, int colId3); //for with 3 sub total

//Example:
exportToExcel("Some Title",mygridview, 3);  //for 1 sub total
exportToExcel("Another Titme", othergridview, 5,6,7); //for 3 sub totals
</code>```

Do I have to create functions for different variations or is there a way to make 2nd and 3rd column numbers optional ?

答:
You can declare method like this. you have to provide the default value to the optional parameters. </p>

```<code>void Method(int a, int b = 0, int c = 0)
{

}
</code>```

Body:
I want to write a class for creating Excel files from Datagridviews. I want to add a bottom line with Subtotals for selected columns and the number of those columns change from 1 to 3.
I want my function work like this

exportToExcel(string title, DataGridView dgv, int colId1, int colId2, int colId3); //for with 3 sub total

//Example:
exportToExcel("Some Title",mygridview, 3);  //for 1 sub total
exportToExcel("Another Titme", othergridview, 5,6,7); //for 3 sub totals

Do I have to create functions for different variations or is there a way to make 2nd and 3rd column numbers optional ?

Body:
You can declare method like this. you have to provide the default value to the optional parameters.

void Method(int a, int b = 0, int c = 0)
{

}


问:
How can I migrate Dart code to non-nullable (NNBD)?
I have a Flutter application that was written before null safety was introduced to Dart.

I heard of a Null Safety Migration Tooling. How could I use it to convert my code from pre-NNBD to non-nullable by default?

答:
You need at least Dart 2.9. At the time of writing, you can use 2.9.0-10.0.dev, i.e. put the following SDK constraint in your pubspec.yaml:

environment:
  sdk: ">=2.9.0-10.0.dev <3.0.0"
```

Hints (/*?*/ & /*!*/)

The /*?*/ hint means that something should explicitly be nullable.

/*!*/ means that something should be non-nullable.

You can already add these hints manually before using NNBD. Otherwise, you can add them with the tool during migration (see below).

Edits

There are ?, !, and _ edits.

? makes a type nullable after migration. _ makes it non-nullable (meaning no character is changed because non-nullable is the default).

! makes an expression non-nullable.

These edits are previewed in the migration tool.

Using the tool

Dart 2.9 comes with an nnbd_migration package.

This tool can be used to interactively convert code to NNBD.

I will cover the migration steps described in the README and try to simplify them:

Go to your project in your command line and run pub get or flutter pub get when using Flutter. (Note that at the time of writing, the Flutter SDK is not yet supported)

Run dart migrate. (Note that at the time of writing, I need to use --skip-pub-outdated)

Wait for analysis and migration to complete and then view migration suggestions by opening the URL you see in the command line in your browser (of format http://localhost:<port>/<project path>?authToken=<token>). You should see something like this:

Select a file to begin with. It should look something like this:

View the proposed edits on the right (matching the highlighted characters):

If you find edits that you think are not correct, find the root cause in Edit Details:

You can scroll down to trace the root expression that led to the edit proposal. When you find some wrong decision somewhere along the way, you either Add /*?*/ hint or Add /*!*/ hint as explained above (you can also add them manually in your IDE).

If an edit looks right, you do not need to do anything.

You will probably need to Rerun From Sources a lot. This will apply the new hints you added and any other edits you made to the code and generate new edits. Do this until all edits look right.

Now, you might see your hints highlighted in red, which means that the tool will remove the hints and convert them to either ?, !, or blank.

You should probably save your project at this point (e.g. git commit).

Note: at this point, your code has a bunch of added /*?*/ and /*!*/ hints and has not yet been migrated.

Apply Migration: this will apply the proposed edits and remove all hints.

Probably leave the migration tool open for now.

Now, you do not have any hints in your code anymore.

Test your project (pub get or flutter pub get and then run).

If something went wrong, it is helpful to have left the migration tool open.
Potentially, you want to revert your version to before the migration and repeat the steps.

Success! Your project is now null safe

Body:
You need at least Dart 2.9. At the time of writing, you can use 2.9.0-10.0.dev, i.e. put the following SDK constraint in your pubspec.yaml:

environment:
  sdk: ">=2.9.0-10.0.dev <3.0.0"

Hints (/*?*/ & /*!*/)

The /*?*/ hint means that something should explicitly be nullable.

/*!*/ means that something should be non-nullable.

You can already add these hints manually before using NNBD. Otherwise, you can add them with the tool during migration (see below).

Edits

There are ?, !, and _ edits.

? makes a type nullable after migration. _ makes it non-nullable (meaning no character is changed because non-nullable is the default).

! makes an expression non-nullable.

These edits are previewed in the migration tool.

Using the tool

Dart 2.9 comes with an nnbd_migration package.

This tool can be used to interactively convert code to NNBD.

I will cover the migration steps described in the README and try to simplify them:

Go to your project in your command line and run pub get or flutter pub get when using Flutter. (Note that at the time of writing, the Flutter SDK is not yet supported)

Run dart migrate. (Note that at the time of writing, I need to use --skip-pub-outdated)

Wait for analysis and migration to complete and then view migration suggestions by opening the URL you see in the command line in your browser (of format http://localhost:<port>/<project path>?authToken=<token>). You should see something like this:

Select a file to begin with. It should look something like this:

View the proposed edits on the right (matching the highlighted characters):

If you find edits that you think are not correct, find the root cause in Edit Details:

You can scroll down to trace the root expression that led to the edit proposal. When you find some wrong decision somewhere along the way, you either Add /*?*/ hint or Add /*!*/ hint as explained above (you can also add them manually in your IDE).

If an edit looks right, you do not need to do anything.

You will probably need to Rerun From Sources a lot. This will apply the new hints you added and any other edits you made to the code and generate new edits. Do this until all edits look right.

Now, you might see your hints highlighted in red, which means that the tool will remove the hints and convert them to either ?, !, or blank.

You should probably save your project at this point (e.g. git commit).

Note: at this point, your code has a bunch of added /*?*/ and /*!*/ hints and has not yet been migrated.

Apply Migration: this will apply the proposed edits and remove all hints.

Probably leave the migration tool open for now.

Now, you do not have any hints in your code anymore.

Test your project (pub get or flutter pub get and then run).

If something went wrong, it is helpful to have left the migration tool open.
Potentially, you want to revert your version to before the migration and repeat the steps.

Success! Your project is now null safe


答:
You can specify defaults for parameters in the method signature.  Like this:

```<code>exportToExcel(string title, DataGridView dgv, int colId1, int colId2 = 6, int colId3 = 7);
</code>```

Then, if you don't specify values when calling, then the "defaults" will be taken instead.

This means you can use this method for 3, 4, or 5 parameters specified.

```<code>exportToExcel("Some Title",mygridview, 3);  //Using 2 defaults
exportToExcel("Some Title",mygridview, 3, 6);  //using 1 default
exportToExcel("Another Titme", othergridview, 5,6,7); //full usage, no defaults
</code>```

Title: How do I declare a function with optional parameters in C#

Body:
You can specify defaults for parameters in the method signature.  Like this:

exportToExcel(string title, DataGridView dgv, int colId1, int colId2 = 6, int colId3 = 7);

Then, if you don't specify values when calling, then the "defaults" will be taken instead.

This means you can use this method for 3, 4, or 5 parameters specified.

exportToExcel("Some Title",mygridview, 3);  //Using 2 defaults
exportToExcel("Some Title",mygridview, 3, 6);  //using 1 default
exportToExcel("Another Titme", othergridview, 5,6,7); //full usage, no defaults


问:
How to make correctly autocomplete in React
I want to make autocomplete input of cities in React. I have json file of cities ~15mb. How should I correctly implement it? Should I keep this json on client side?

答:
you could make a request to the server on every keystroke but start the search after say 3 characters

e.g. searching for London

You would only make the first request after the user has typed in Lon

15mb seems a lot though, maybe you want to think of filtering this down beforehand so you request less countries back. e.g. make the user select a country beforehand so you only request cities in that country. so if they pick USA, then type in Chi it would only return cities in the USA starting with Chi

I don't think it's a good idea to pull the 15mb client side as that is a huge amount of data


答:
You can use default values for the optional paramenters, something like:

```<code>exportToExcel(string title, DataGridView dgv, int colId1, int colId2 = 0, int colId3 = 0);
</code>```

With a method like that you'd be able to make a call with 1 to 3 columns.

Also another approach would be this - the good thing about using this one is that if one day your number of columns increases or decreases you won't have to change the signature:

```<code>exportToExcel(string title, DataGridView dgv, params int[] colIds);
</code>```

Body:
You can use default values for the optional paramenters, something like:

exportToExcel(string title, DataGridView dgv, int colId1, int colId2 = 0, int colId3 = 0);

With a method like that you'd be able to make a call with 1 to 3 columns.

Also another approach would be this - the good thing about using this one is that if one day your number of columns increases or decreases you won't have to change the signature:

exportToExcel(string title, DataGridView dgv, params int[] colIds);


问:
connect to host localhost port 22: Connection refused
While installing hadoop in my local machine , i got following error </p>

```<code>ssh -vvv localhost
OpenSSH_5.5p1, OpenSSL 1.0.0e-fips 6 Sep 2011
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to localhost [127.0.0.1] port 22.
debug1: connect to address 127.0.0.1 port 22: Connection refused
ssh: connect to host localhost port 22: Connection refused
</code>```

<p>can some one help me to resolve this error , than changing port number </p>

答:
try sudo vi /etc/ssh/sshd_config

in first few lies you'll find

Package generated configuration file

See the sshd_config(5) manpage for details

What ports, IPs and protocols we listen for

Port xxxxx

change Port xxxxx to "Port 22" and exit vi by saving changes.

restart ssh sudo service ssh restart

Body:
While installing hadoop in my local machine , i got following error

ssh -vvv localhost
OpenSSH_5.5p1, OpenSSL 1.0.0e-fips 6 Sep 2011
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to localhost [127.0.0.1] port 22.
debug1: connect to address 127.0.0.1 port 22: Connection refused
ssh: connect to host localhost port 22: Connection refused

can some one help me to resolve this error , than changing port number