问:
Deploying Google Cloud Endpoints configuration fails Google API Linter recommendations
Update: Cloud Endpoints Portal is being deprecated and will no longer be available after 21 March 2023.

After following Deploying the Endpoints configuration I have successfully deployed my compiled .proto file and gRPC API configuration file.

Great. I decided to be be a good citizen and use Google's API Linter on my .proto.

This resulted in a number of recommendations to include various annotations. The annotations required new proto imports;

Before

syntax = "proto3";
package api.v1;

// Request message for Get method.
message GetFooRequest {
  // The field will contain name of the resource requested.
  string name = 1;
}

...blah,blah
```
<p><strong>After</strong></p>
<pre class="lang-proto prettyprint-override"><code>syntax = "proto3";
package api.v1;

import "google/api/annotations.proto";
import "google/api/client.proto";
import "google/api/field_behavior.proto";
import "google/api/resource.proto";

// Request message for Get method.
message GetFooRequest {
  // The field will contain name of the resource requested.
  string name = 1 [
    (google.api.field_behavior) = REQUIRED,
    (google.api.resource_reference).type = "api.v1.HelloWorld/Foo"
  ];
}
...blah,blah
</code>```

The annotations require four new proto files to be imported:

import "google/api/annotations.proto";
import "google/api/client.proto";
import "google/api/field_behavior.proto";
import "google/api/resource.proto";
```
<p>All are part of Google's Common API protos, therefore I cloned the repo into <code>/Users/Jack/api-common-protos/</code> with:</p>
```git clone https://github.com/googleapis/api-common-protos.git
```
<p>...and include it when compiling my <code>.proto</code> file:</p>
```python3 -m grpc_tools.protoc --proto_path=api
                             --proto_path=/Users/Jack/api-common-protos/google
                             api/v1/foo.proto
```
<p>No errors. Great. Finally I deploy the API:</p>
```gcloud endpoints services deploy api_descriptor.pb api-config.yaml
```
<p>This completes. However, the Developer Portal now shows:</p>
```We encountered the following errors while processing this API specification:

API parse error: Error: ENOENT: no such file or directory, open '/tmp/google/api/client.proto'

Please correct these errors and try again.
```

Scrot:

If I remove the annotation (and required imports), the Endpoints Developer Portal for my API works fine.

答:
It's probably not much effort to temporarily work around the issue:

```<code>cp /Users/Jack/api-common-protos/google/api/client.proto /tmp/google/api/client.proto
</code>```

Then the file will be available, where it is being expected - despite not being put there automatically.

Body:
Update: Cloud Endpoints Portal is being deprecated and will no longer be available after 21 March 2023.

After following Deploying the Endpoints configuration I have successfully deployed my compiled .proto file and gRPC API configuration file.

Great. I decided to be be a good citizen and use Google's API Linter on my .proto.

This resulted in a number of recommendations to include various annotations. The annotations required new proto imports;

Before

syntax = "proto3";
package api.v1;

// Request message for Get method.
message GetFooRequest {
  // The field will contain name of the resource requested.
  string name = 1;
}

...blah,blah

After

syntax = "proto3";
package api.v1;

import "google/api/annotations.proto";
import "google/api/client.proto";
import "google/api/field_behavior.proto";
import "google/api/resource.proto";

// Request message for Get method.
message GetFooRequest {
  // The field will contain name of the resource requested.
  string name = 1 [
    (google.api.field_behavior) = REQUIRED,
    (google.api.resource_reference).type = "api.v1.HelloWorld/Foo"
  ];
}
...blah,blah

The annotations require four new proto files to be imported:

import "google/api/annotations.proto";
import "google/api/client.proto";
import "google/api/field_behavior.proto";
import "google/api/resource.proto";

All are part of Google's Common API protos, therefore I cloned the repo into /Users/Jack/api-common-protos/ with:

git clone https://github.com/googleapis/api-common-protos.git

...and include it when compiling my .proto file:

python3 -m grpc_tools.protoc --proto_path=api
                             --proto_path=/Users/Jack/api-common-protos/google
                             api/v1/foo.proto

No errors. Great. Finally I deploy the API:

gcloud endpoints services deploy api_descriptor.pb api-config.yaml

This completes. However, the Developer Portal now shows:

We encountered the following errors while processing this API specification:

API parse error: Error: ENOENT: no such file or directory, open '/tmp/google/api/client.proto'

Please correct these errors and try again.

Scrot:

If I remove the annotation (and required imports), the Endpoints Developer Portal for my API works fine.

Body:
It's probably not much effort to temporarily work around the issue:

cp /Users/Jack/api-common-protos/google/api/client.proto /tmp/google/api/client.proto

Then the file will be available, where it is being expected - despite not being put there automatically.


来源: stackexchange

问:
CSS child selector doesn't work on ie9
i have a page like this:

```<code><body>
<table width="100%">...</table>
<table width="100%">...</table>
<table width="100%">...</table>
<table width="100%">...</table>
</body>
</code>```

what i need to do is making all those tables 85% width and horizontally centered on the page. it would be easy if the page was a single page but this needs to work on 100+ pages and the only thing they have in common is the stylesheet file. so i need to do this with css only. i can't cover the tables inside a div or use jquery.

what i tried is:

```<code>body { text-align:center; }
body > table { text-align: left; margin: 0 auto; width: 85%; }
</code>```

this works perfectly on firefox and google chrome but it doesn't seem to work on ie9 (didn't tested but i'm sure it won't work with earlier ie versions)

i've tried lots of methods they wrote on similar questions but couldn't be able to solve this.

EDIT:

The doctype of the page was:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
</code>```

i changed it to:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code>```

and it works on ie9 too now!

The updated question is: is it possible without changing the doctype?

答:
I put together this jsfiddle and it looks like it works on IE9:

http://jsfiddle.net/XFgLf/

ContentLicense: CC BY-SA 3.0

Title: CSS child selector doesn't work on ie9

Body:
i have a page like this:

...

...

...

...

what i need to do is making all those tables 85% width and horizontally centered on the page. it would be easy if the page was a single page but this needs to work on 100+ pages and the only thing they have in common is the stylesheet file. so i need to do this with css only. i can't cover the tables inside a div or use jquery.

what i tried is:

body { text-align:center; }
body > table { text-align: left; margin: 0 auto; width: 85%; }

this works perfectly on firefox and google chrome but it doesn't seem to work on ie9 (didn't tested but i'm sure it won't work with earlier ie versions)

i've tried lots of methods they wrote on similar questions but couldn't be able to solve this.

EDIT:

The doctype of the page was:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

i changed it to:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

and it works on ie9 too now!

The updated question is: is it possible without changing the doctype?


问:
How to asynchronously write to a JSON file from an array?
I'm scraping some data and pushing it to any array from which it is written to a JSON file. Currently it writes to the JSON file after every push to th array...

```<code>    const myArray = [];
    const htmlString = await rp(url);
    $('a','#atozindex', htmlString).map(async (index, element) => {
        let link = $(element).attr('href');
        if (link) {
            //Do something
            myArray.push({ item1, item2, item3 });
            fs.writeFile("./arrayContents.json", JSON.stringify(myArray), function(err) {
                if(err) {
                    console.log(err);
                }
                console.log("Some Message");
            });
        }
    });
    return myArray;
</code>```

I want to have it push only once at the very end when all the data is already in the array. So something like this:

```<code>    const myArray = [];
    const htmlString = await rp(url);
    $('a','#atozindex', htmlString).map(async (index, element) => {
        let link = $(element).attr('href');
        if (link) {
            //Do something
            myArray.push({ item1, item2, item3 });
        }
    });
    fs.writeFile("./arrayContents.json", JSON.stringify(myArray), function(err) {
        if(err) {
            console.log(err);
        }
        console.log("Some Message");
    return myArray;
</code>```

But I'm having some trouble figuring it out.

答:
My async/await is rusty, to be sure to test... but I think you have 2 options - await all the asyncs:

```<code>const myArray = [];
const htmlString = await rp(url);
$('a','#atozindex', htmlString).map(async (index, element) => {
    let link = $(element).attr('href');
    if (link) {
        //Do something
        myArray.push({ item1, item2, item3 });
    }
}).forEach(pending => await pending);
fs.writeFile("./arrayContents.json", JSON.stringify(myArray), function(err) {
    if(err) {
        console.log(err);
    }
    console.log("Some Message");
return myArray;
</code>```

OR, remove the async:

```<code>const myArray = [];
const htmlString = await rp(url);
$('a','#atozindex', htmlString).map((index, element) => {
    let link = $(element).attr('href');
    if (link) {
        //Do something
        myArray.push({ item1, item2, item3 });
    }
});
fs.writeFile("./arrayContents.json", JSON.stringify(myArray), function(err) {
    if(err) {
        console.log(err);
    }
    console.log("Some Message");
return myArray;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm scraping some data and pushing it to any array from which it is written to a JSON file. Currently it writes to the JSON file after every push to th array...

    const myArray = [];
    const htmlString = await rp(url);
    $('a','#atozindex', htmlString).map(async (index, element) => {
        let link = $(element).attr('href');
        if (link) {
            //Do something
            myArray.push({ item1, item2, item3 });
            fs.writeFile("./arrayContents.json", JSON.stringify(myArray), function(err) {
                if(err) {
                    console.log(err);
                }
                console.log("Some Message");
            });
        }
    });
    return myArray;

I want to have it push only once at the very end when all the data is already in the array. So something like this:

    const myArray = [];
    const htmlString = await rp(url);
    $('a','#atozindex', htmlString).map(async (index, element) => {
        let link = $(element).attr('href');
        if (link) {
            //Do something
            myArray.push({ item1, item2, item3 });
        }
    });
    fs.writeFile("./arrayContents.json", JSON.stringify(myArray), function(err) {
        if(err) {
            console.log(err);
        }
        console.log("Some Message");
    return myArray;

But I'm having some trouble figuring it out.

Body:
My async/await is rusty, to be sure to test... but I think you have 2 options - await all the asyncs:

const myArray = [];
const htmlString = await rp(url);
$('a','#atozindex', htmlString).map(async (index, element) => {
    let link = $(element).attr('href');
    if (link) {
        //Do something
        myArray.push({ item1, item2, item3 });
    }
}).forEach(pending => await pending);
fs.writeFile("./arrayContents.json", JSON.stringify(myArray), function(err) {
    if(err) {
        console.log(err);
    }
    console.log("Some Message");
return myArray;

OR, remove the async:

const myArray = [];
const htmlString = await rp(url);
$('a','#atozindex', htmlString).map((index, element) => {
    let link = $(element).attr('href');
    if (link) {
        //Do something
        myArray.push({ item1, item2, item3 });
    }
});
fs.writeFile("./arrayContents.json", JSON.stringify(myArray), function(err) {
    if(err) {
        console.log(err);
    }
    console.log("Some Message");
return myArray;


问:
pytorch conv2d value cannot be converted to type uint8_t without overflow
I'm passing a torch.Tensor with a dtype of torch.uint8 to an nn.Conv2d module and it is giving the error

RuntimeError: value cannot be converted to type uint8_t without
  overflow: -0.0344873

My conv2d is defined as self.conv1 = nn.Conv2d(3, 6, 5). The error comes in my forward method when I pass the tensor to the module like self.conv1(x).  The tensor has shape (4, 3, 480, 640). I'm not sure how to fix this.  Here is the stack trace

```<code>Traceback (most recent call last):

  File "cnn.py", line 54, in <module>

    outputs = net(inputs)

  File "/Users/my_repos/venv_projc/lib/python3.7/site-packages/torch/nn/modules/module.py", line 532, in __call__

    result = self.forward(*input, **kwargs)

  File "cnn.py", line 24, in forward

    test = self.conv1(x)

  File "/Users/my_repos/venv_projc/lib/python3.7/site-packages/torch/nn/modules/module.py", line 532, in __call__

    result = self.forward(*input, **kwargs)

  File "/Users/my_repos/venv_projc/lib/python3.7/site-packages/torch/nn/modules/conv.py", line 345, in forward

    return self.conv2d_forward(input, self.weight)

  File "/Users/my_repos/venv_projc/lib/python3.7/site-packages/torch/nn/modules/conv.py", line 342, in conv2d_forward

    self.padding, self.dilation, self.groups)

RuntimeError: value cannot be converted to type uint8_t without overflow: -0.0344873
</code>```

答: Converting the tensor to a float seemed to fix it self.conv1(x.float())

Body:
I'm passing a torch.Tensor with a dtype of torch.uint8 to an nn.Conv2d module and it is giving the error

RuntimeError: value cannot be converted to type uint8_t without
  overflow: -0.0344873

My conv2d is defined as self.conv1 = nn.Conv2d(3, 6, 5). The error comes in my forward method when I pass the tensor to the module like self.conv1(x).  The tensor has shape (4, 3, 480, 640). I'm not sure how to fix this.  Here is the stack trace

Traceback (most recent call last):

  File "cnn.py", line 54, in <module>

    outputs = net(inputs)

  File "/Users/my_repos/venv_projc/lib/python3.7/site-packages/torch/nn/modules/module.py", line 532, in __call__

    result = self.forward(*input, **kwargs)

  File "cnn.py", line 24, in forward

    test = self.conv1(x)

  File "/Users/my_repos/venv_projc/lib/python3.7/site-packages/torch/nn/modules/module.py", line 532, in __call__

    result = self.forward(*input, **kwargs)

  File "/Users/my_repos/venv_projc/lib/python3.7/site-packages/torch/nn/modules/conv.py", line 345, in forward

    return self.conv2d_forward(input, self.weight)

  File "/Users/my_repos/venv_projc/lib/python3.7/site-packages/torch/nn/modules/conv.py", line 342, in conv2d_forward

    self.padding, self.dilation, self.groups)

RuntimeError: value cannot be converted to type uint8_t without overflow: -0.0344873


问:
How integrate Quasar framework and Vuetify?
How to install vuetify in a project generated with quasar cli?

In a normal project with vue cli only need the command

```<code>vue add vuetify
</code>```

but in quasar cli I run the command

```<code>npm install vuetify
</code>```

and generate new boot file, but i have an error in sass or sass-loader

答:
It, not a good idea to use two frontend UI frameworks like(bootstrap,vuetify, quasar ...) in one project, it's just like using honey and industrial sugar to make one tea.

You should always consider the bundle size of your work.

what if vuetify comes with a cli, would you have added vuetify to quasar or quasar to vuetify

Body:
How to install vuetify in a project generated with quasar cli?

In a normal project with vue cli only need the command

vue add vuetify

but in quasar cli I run the command

npm install vuetify

and generate new boot file, but i have an error in sass or sass-loader


问:
Trying to execute command on router. C++ & libssh
When I'm trying to run command on server (router) I get

[C] Jan  3 05:32:16 ndm: bin::ndmc: invalid option "-c".

Most of the code is taken from the documentation.
There is the code:

```<code>#include <iostream>
#include <string.h>
#include <libssh/libssh.h>

using std::string;
using std::cout;
using std::endl;
using std::cin;

string exec_ssh_command(ssh_session
session, char *command) {
    string receive = "";
    int rc, nbytes;
    char buffer[256];
    ssh_channel channel = ssh_channel_new(session);
    if( channel == NULL )
            return NULL;

    rc = ssh_channel_open_session(channel);
    if( rc != SSH_OK ) {
            ssh_channel_free(channel);
            return NULL;
    }

    rc = ssh_channel_request_exec(channel, command);
    if( rc != SSH_OK ) {
            ssh_channel_close(channel);
            ssh_channel_free(channel);
            cout << "Error";
            return NULL;
    }
    nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
    while (nbytes > 0)
    {
            if (write(1, buffer, nbytes) != (unsigned int) nbytes)
            {
                    ssh_channel_close(channel);
                    ssh_channel_free(channel);
                    return NULL;
            }
            nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
    }

    if( nbytes < 0 )
            return NULL;

    ssh_channel_send_eof(channel);
    ssh_channel_close(channel);
    ssh_channel_free(channel);

    return receive;
}

int main() {
    ssh_session my_ssh_session = ssh_new();
    if( my_ssh_session == NULL ) {
            cout << "Error creating ssh session" << endl;
            return 1;
    }
    ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "192.168.1.1");
    ssh_options_set(my_ssh_session, SSH_OPTIONS_USER, "admin");
    int rc = ssh_connect(my_ssh_session);
    if( rc != SSH_OK ) {
            cout << "Error with connecting" << endl;
            ssh_free(my_ssh_session);
            return -1;
    }

    rc = ssh_userauth_password(my_ssh_session, NULL, "pass");
    if( rc != SSH_AUTH_SUCCESS) {
            cout << "Error with authorization  " << ssh_get_error(my_ssh_session) << endl;
            ssh_disconnect(my_ssh_session);
            ssh_free(my_ssh_session);
            return -1;
    }
    string ip_hotspot = exec_ssh_command(my_ssh_session, "show ip hotspot");
    cout << ip_hotspot << endl;
    ssh_disconnect(my_ssh_session);
    ssh_free(my_ssh_session);
    return 0;
}
</code>```

My router is zyxel keenetic ultra.

uname -a: Linux localhost 4.9.112-perf-gfb7749d #1 SMP PREEMPT Thu Dec 6 16:06:30 WIB 2018 aarch64 Android

g++ -v:

clang version 7.0.1 (tags/RELEASE_701/final)
Target: aarch64--linux-android
Thread model: posix

I'm a beginner at libssh so please explain easier. :)

Thank you in advance!

答: It was fixed. On version 3.3.2 of Keenetic OS it works fine.

Body:
When I'm trying to run command on server (router) I get

[C] Jan  3 05:32:16 ndm: bin::ndmc: invalid option "-c".

Most of the code is taken from the documentation.
There is the code:

#include <iostream>
#include <string.h>
#include <libssh/libssh.h>

using std::string;
using std::cout;
using std::endl;
using std::cin;

string exec_ssh_command(ssh_session
session, char *command) {
    string receive = "";
    int rc, nbytes;
    char buffer[256];
    ssh_channel channel = ssh_channel_new(session);
    if( channel == NULL )
            return NULL;

    rc = ssh_channel_open_session(channel);
    if( rc != SSH_OK ) {
            ssh_channel_free(channel);
            return NULL;
    }

    rc = ssh_channel_request_exec(channel, command);
    if( rc != SSH_OK ) {
            ssh_channel_close(channel);
            ssh_channel_free(channel);
            cout << "Error";
            return NULL;
    }
    nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
    while (nbytes > 0)
    {
            if (write(1, buffer, nbytes) != (unsigned int) nbytes)
            {
                    ssh_channel_close(channel);
                    ssh_channel_free(channel);
                    return NULL;
            }
            nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
    }

    if( nbytes < 0 )
            return NULL;

    ssh_channel_send_eof(channel);
    ssh_channel_close(channel);
    ssh_channel_free(channel);

    return receive;
}

int main() {
    ssh_session my_ssh_session = ssh_new();
    if( my_ssh_session == NULL ) {
            cout << "Error creating ssh session" << endl;
            return 1;
    }
    ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "192.168.1.1");
    ssh_options_set(my_ssh_session, SSH_OPTIONS_USER, "admin");
    int rc = ssh_connect(my_ssh_session);
    if( rc != SSH_OK ) {
            cout << "Error with connecting" << endl;
            ssh_free(my_ssh_session);
            return -1;
    }

    rc = ssh_userauth_password(my_ssh_session, NULL, "pass");
    if( rc != SSH_AUTH_SUCCESS) {
            cout << "Error with authorization  " << ssh_get_error(my_ssh_session) << endl;
            ssh_disconnect(my_ssh_session);
            ssh_free(my_ssh_session);
            return -1;
    }
    string ip_hotspot = exec_ssh_command(my_ssh_session, "show ip hotspot");
    cout << ip_hotspot << endl;
    ssh_disconnect(my_ssh_session);
    ssh_free(my_ssh_session);
    return 0;
}

My router is zyxel keenetic ultra.

uname -a: Linux localhost 4.9.112-perf-gfb7749d #1 SMP PREEMPT Thu Dec 6 16:06:30 WIB 2018 aarch64 Android

g++ -v:

clang version 7.0.1 (tags/RELEASE_701/final)
Target: aarch64--linux-android
Thread model: posix

I'm a beginner at libssh so please explain easier. :)

Thank you in advance!


问:
Changing an array code to a vector
So I have been trying to look all over, but can't seem to find a whole lot on what exactly needs to be changed in order to convert an array to vector.  Or rather, I suppose I just don't know what exactly to search for.

The array is this:

```<code>public class Member{

 private int id;
 private String name;
 private String[] books = new String[5];
 //replace the String books array with a Vector variable named books
 //that functions exactly the same way

 public Member() {
     id = 0;
     name = "John Doe";
 }

 public Member(int pId, String pName) {
     id = pId;
     name = pName;
 }

 public int getId(){
     return id;
 }

 public void setId(int pId){
     id=pId;
 }

 public String getName(){
     return name;
 }

 public void setName(String pName){
     name=pName;
 }

 public String[] getBooks(){
     return books;
 }

 public void setBooks(String[] pBooks){
     books=pBooks;
 }

 public String toString(){
     StringBuffer buf = new StringBuffer();
     buf.append("ID: " + getId() + "  Member: " + getName() + "\n");
     for(int x=0; x<books.length; x++ ) {
         buf.append("Book: " + books[x] + "\n");
     }
     return buf.toString();
 }

/**
 * @param args
 */
public static void main(String[] args) {
    String[] list = {"Java Data Structures", "The Bible", "Grapes of Wrath",
                    "Goldfinger", "Sam I Am", "The Cat in the Hat", "Shawshenk Redemption",
                    "Green Eggs and Ham", "Linus and Lucy", "Abraham Lincoln"};

    Member m1 = new Member();
    m1.setId(431);
    m1.setName("William Wallace");
    for(int i=0; i<5; i++) {
        m1.books[i] = list[i];
    }

    Member m2 = new Member(7010, "Bonny Clyde");
    for(int i=5; i<list.length; i++) {
        int x = i-5;
        m2.books[x] = list[i];
    }

    System.out.println(m1.toString());
    System.out.println();
    System.out.println(m2.toString());
}

}
</code>```

Now, I have been trying to convert it, but to be honest, I don't know what I am doing.

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

public class Member{

 private int id;
 private String name;
 private Vector<String> books = new Vector<String>(5);
 //replace the String books array with a Vector variable named books
 //that functions exactly the same way

 public Member() {
     id = 0;
     name = "John Doe";
 }

 public Member(int pId, String pName) {
     id = pId;
     name = pName;
 }

 public int getId(){
     return id;
 }

 public void setId(int pId){
     id=pId;
 }

 public String getName(){
     return name;
 }

 public void setName(String pName){
     name=pName;
 }

 public String getBooks(){
     return books;
 }

 public void setBooks(String pBooks){
     books=pBooks;
 }

 public String toString(){
     StringBuffer buf = new StringBuffer();
     buf.append("ID: " + getId() + "  Member: " + getName() + "\n");
     for(int x=0; x<books.length; x++ ) {
         buf.append("Book: " + books<x> + "\n");
     }
     return buf.toString();
 }

/**
 * @param args
 */
public static void main(String args) {
    String list = {"Java Data Structures", "The Bible", "Grapes of Wrath",
                    "Goldfinger", "Sam I Am", "The Cat in the Hat", "Shawshenk Redemption",
                    "Green Eggs and Ham", "Linus and Lucy", "Abraham Lincoln"};

    Member m1 = new Member();
    m1.setId(431);
    m1.setName("William Wallace");
    for(int i=0; i<5; i++) {
        m1.books<i> = list<i>;
    }

    Member m2 = new Member(7010, "Bonny Clyde");
    for(int i=5; i<list.length; i++) {
        int x = i-5;
        m2.books<x> = list<i>;
    }

    System.out.println(m1.toString());
    System.out.println();
    System.out.println(m2.toString());
}

}
</code>```

Any help would be greatly appreciated.

答:
You can pack your array into a vector thus:

```<code>Vector<String> v = new Vector<String>(Arrays.asList(myList))
</code>```

and then your loop becomes

```<code>for (String s : v) {
  ...
}
</code>```

I would use ArrayList over Vector unless you've got a compelling reason to use Vector though.

Title: Changing an array code to a vector

Body:
So I have been trying to look all over, but can't seem to find a whole lot on what exactly needs to be changed in order to convert an array to vector.  Or rather, I suppose I just don't know what exactly to search for.

The array is this:

public class Member{

 private int id;
 private String name;
 private String[] books = new String[5];
 //replace the String books array with a Vector variable named books
 //that functions exactly the same way

 public Member() {
     id = 0;
     name = "John Doe";
 }

 public Member(int pId, String pName) {
     id = pId;
     name = pName;
 }

 public int getId(){
     return id;
 }

 public void setId(int pId){
     id=pId;
 }

 public String getName(){
     return name;
 }

 public void setName(String pName){
     name=pName;
 }

 public String[] getBooks(){
     return books;
 }

 public void setBooks(String[] pBooks){
     books=pBooks;
 }

 public String toString(){
     StringBuffer buf = new StringBuffer();
     buf.append("ID: " + getId() + "  Member: " + getName() + "\n");
     for(int x=0; x<books.length; x++ ) {
         buf.append("Book: " + books[x] + "\n");
     }
     return buf.toString();
 }

/**
 * @param args
 */
public static void main(String[] args) {
    String[] list = {"Java Data Structures", "The Bible", "Grapes of Wrath",
                    "Goldfinger", "Sam I Am", "The Cat in the Hat", "Shawshenk Redemption",
                    "Green Eggs and Ham", "Linus and Lucy", "Abraham Lincoln"};

    Member m1 = new Member();
    m1.setId(431);
    m1.setName("William Wallace");
    for(int i=0; i<5; i++) {
        m1.books[i] = list[i];
    }

    Member m2 = new Member(7010, "Bonny Clyde");
    for(int i=5; i<list.length; i++) {
        int x = i-5;
        m2.books[x] = list[i];
    }

    System.out.println(m1.toString());
    System.out.println();
    System.out.println(m2.toString());
}

}

Now, I have been trying to convert it, but to be honest, I don't know what I am doing.

import java.util.Vector;

public class Member{

 private int id;
 private String name;
 private Vector<String> books = new Vector<String>(5);
 //replace the String books array with a Vector variable named books
 //that functions exactly the same way

 public Member() {
     id = 0;
     name = "John Doe";
 }

 public Member(int pId, String pName) {
     id = pId;
     name = pName;
 }

 public int getId(){
     return id;
 }

 public void setId(int pId){
     id=pId;
 }

 public String getName(){
     return name;
 }

 public void setName(String pName){
     name=pName;
 }

 public String getBooks(){
     return books;
 }

 public void setBooks(String pBooks){
     books=pBooks;
 }

 public String toString(){
     StringBuffer buf = new StringBuffer();
     buf.append("ID: " + getId() + "  Member: " + getName() + "\n");
     for(int x=0; x<books.length; x++ ) {
         buf.append("Book: " + books<x> + "\n");
     }
     return buf.toString();
 }

/**
 * @param args
 */
public static void main(String args) {
    String list = {"Java Data Structures", "The Bible", "Grapes of Wrath",
                    "Goldfinger", "Sam I Am", "The Cat in the Hat", "Shawshenk Redemption",
                    "Green Eggs and Ham", "Linus and Lucy", "Abraham Lincoln"};

    Member m1 = new Member();
    m1.setId(431);
    m1.setName("William Wallace");
    for(int i=0; i<5; i++) {
        m1.books = list;
    }

    Member m2 = new Member(7010, "Bonny Clyde");
    for(int i=5; i<list.length; i++) {
        int x = i-5;
        m2.books<x> = list;
    }

    System.out.println(m1.toString());
    System.out.println();
    System.out.println(m2.toString());
}

}

Any help would be greatly appreciated.

Body:
You can pack your array into a vector thus:

Vector<String> v = new Vector<String>(Arrays.asList(myList))

and then your loop becomes

for (String s : v) {
  ...
}

I would use ArrayList over Vector unless you've got a compelling reason to use Vector though.


问:
Timezone Abbreviations in Java
I have a collection of Java Date objects, loaded from an old database which did not store timezone info.

I know that all the dates (which include hours, minutes and seconds) are for the U.S. Eastern time zone.

I want to derive the correct timezone abbreviation ("EST" or "EDT") for each date.

Here is my attempt (using Java 11). It is unwieldy, to say the least.

I looked into the following classes:

```<code>java.util.TimeZone
java.time.ZoneId
java.time.zone.ZoneRules
</code>```

Here is my method - it uses two statements purely to give me a fighting chance of still understanding what I wrote, a week from now.

EDIT - based on @VGR's comment below, I have updated the example. Now it expects a timezone display name - for example "America/New_York":

```<code>public String getTimezoneAbbrev(Date date, String tzName) {
    TimeZone tz = TimeZone.getTimeZone(tzName);
    boolean isDaylightSavings = tz.toZoneId().getRules().isDaylightSavings(date.toInstant());
    return tz.getDisplayName(isDaylightSavings, TimeZone.SHORT);
}
</code>```

It works (I have test cases), but is there a less verbose way?

(I did not find any code examples which use Date as their starting point).

答:
Something like the following?</p>

```<code>import java.util.Date;
import java.util.TimeZone;

public class Main {
    public static void main(String[] args) {
        System.out.println(TimeZone.getDefault().getDisplayName(TimeZone.getDefault().inDaylightTime(new Date()),TimeZone.SHORT));
    }
}
</code>```

Title: Timezone Abbreviations in Java

Body:
I have a collection of Java Date objects, loaded from an old database which did not store timezone info.

I know that all the dates (which include hours, minutes and seconds) are for the U.S. Eastern time zone.

I want to derive the correct timezone abbreviation ("EST" or "EDT") for each date.

Here is my attempt (using Java 11). It is unwieldy, to say the least.

I looked into the following classes:

java.util.TimeZone
java.time.ZoneId
java.time.zone.ZoneRules

Here is my method - it uses two statements purely to give me a fighting chance of still understanding what I wrote, a week from now.

EDIT - based on @VGR's comment below, I have updated the example. Now it expects a timezone display name - for example "America/New_York":

public String getTimezoneAbbrev(Date date, String tzName) {
    TimeZone tz = TimeZone.getTimeZone(tzName);
    boolean isDaylightSavings = tz.toZoneId().getRules().isDaylightSavings(date.toInstant());
    return tz.getDisplayName(isDaylightSavings, TimeZone.SHORT);
}

It works (I have test cases), but is there a less verbose way?

(I did not find any code examples which use Date as their starting point).

Body:
Something like the following?

import java.util.Date;
import java.util.TimeZone;

public class Main {
    public static void main(String[] args) {
        System.out.println(TimeZone.getDefault().getDisplayName(TimeZone.getDefault().inDaylightTime(new Date()),TimeZone.SHORT));
    }
}


问:
Joining two tables results in a connection failure to the server in psql and pgAdmin4
I am currently practicing SQL on an IMDB dataset, and here's the strange thing that I encounter.

PgAdmin4 and psql always raise an error telling me:

Connection to the server has been lost

... or ...:

Server closed the connection unexpectedly

... whenever I try to join two tables in the dataset using a query like:

```<code>select *
from movie, movie_directors
where movie.id = movie_directors.mid
</code>```

However, simple queries like:

```<code>select * from movie
</code>```

... or ...:

```<code>select count(*) from movie_directors
</code>```

.. work just fine.

Nevertheless, joining tables does not raise such error when I do query on some small test dataset I created.

Can somebody please help me fix this? Thanks a lot.

答:
Try it with the inner join version:</p>

```<code>select *
from movie inner join movie_directors
on movie.id = movie_directors.mid
</code>```

Body:
I am currently practicing SQL on an IMDB dataset, and here's the strange thing that I encounter.

PgAdmin4 and psql always raise an error telling me:

Connection to the server has been lost

... or ...:

Server closed the connection unexpectedly

... whenever I try to join two tables in the dataset using a query like:

select *
from movie, movie_directors
where movie.id = movie_directors.mid

However, simple queries like:

select * from movie

... or ...:

select count(*) from movie_directors

.. work just fine.

Nevertheless, joining tables does not raise such error when I do query on some small test dataset I created.

Can somebody please help me fix this? Thanks a lot.

Body:
Try it with the inner join version:

select *
from movie inner join movie_directors
on movie.id = movie_directors.mid


问:
How to call Mongoose Find function to fetch all of the documents as an array?
I am still new to Node.js and Mongoose and have no idea why this code is not returning an array. Any suggestions?

function all(array){
    array = card.cards.find({}, (err, items) => {
        array = items
        return array
    })
}

let arr = []
all(arr)
console.log(arr)
```

The end result is just an empty array.

答:
You don't need to pass in an array, you can return the items that are returned by the .find() method. </p>

```<code>function getAll(){
    card.cards.find({})
         .then(items => {
             return items
         }
         .catch(err => {
             console.log(err)
         }
}
</code>```

Body:
I am still new to Node.js and Mongoose and have no idea why this code is not returning an array. Any suggestions?

function all(array){
    array = card.cards.find({}, (err, items) => {
        array = items
        return array
    })
}

let arr = []
all(arr)
console.log(arr)

The end result is just an empty array.

Body:
You don't need to pass in an array, you can return the items that are returned by the .find() method.

function getAll(){
    card.cards.find({})
         .then(items => {
             return items
         }
         .catch(err => {
             console.log(err)
         }
}


问:
Post form not submitting inside while loop table php
I am trying to submit this form but it only submits the hidden input field. I can't understand why. It was working before. </p>

```<code>while ($row = mysqli_fetch_array($gettimesheets)) {
    $date = $row['Date'];
    $date = date('d-m-Y', strtotime($date));
    $teachername = $row['StaffName'];
    $teacherid = $row['StaffID'];
    $starttime = $row['StartTime'];
    $endtime = $row['EndTime'];
    $totalhours = $row['TotalHours'];
    $timesheetid = $row['id'];

    ?>
    <tr>
        <form action="edittimesheet.php" method="post">
            <td class="text-center"><?php echo $date; ?></td>
            <td><?php echo $teachername; ?></td>
            <td><?php echo $teacherid; ?></td>
            <td><input type="time" name="starttime" class="form-control" value="<?php echo $starttime; ?>"></td>
            <td><input type="time" name="endtime" class="form-control" value="<?php echo $endtime; ?>">
                <input type="text" name="timesheetid" value="<?php echo $timesheetid; ?>" hidden></td>
            <td class="text-right">
                <input type="submit" class="btn btn-success" value="Edit"/>
                <a href="deletetimesheet.php?id=<?php echo $timesheetid; ?>"
                   class="btn btn-simple btn-danger">Delete</a>
            </td>
        </form>
    </tr>

    <?php
}
</code>```

答:
Make your form outside your table and on your edit-submit button the id you edit.</p>

```<code><form action="edittimesheet.php"
<table>
<?php
while ($row = mysqli_fetch_array($gettimesheets)) {
     $date = $row['Date'];
     $date = date('d-m-Y', strtotime($date));
     $teachername = $row['StaffName'];
     $teacherid = $row['StaffID'];
     $starttime = $row['StartTime'];
     $endtime = $row['EndTime'];
     $totalhours = $row['TotalHours'];
     $timesheetid = $row['id'];

                                                ?>
                                                <tr>
method="post">
                                                  <td class="text-center"><?php echo $date ;?></td>
                                                  <td><?php echo $teachername ;?></td>
                                                  <td><?php echo $teacherid ;?></td>
                                                  <td><input type="time" name="starttime[$timesheetid]" class="form-control" value="<?php echo $starttime; ?>" ></td>
                                                  <td><input type="time" name="endtime[$timesheetid]" class="form-control" value="<?php echo $endtime; ?>" >
                                                  <input type="text" name="timesheetid[$timesheetid]" value="<?php echo $timesheetid; ?>" hidden></td>
                                                  <td class="text-right">
                                                    <input type="submit" name="edit" value ="<?php echo $timesheetid; ?>;" class="btn btn-success" value="Edit"/>
                                                    <a href="deletetimesheet.php?id=<?php echo $timesheetid; ?>" class="btn btn-simple btn-danger">Delete</a>
                                                  </td>

                                                </tr>

                                                <?php
                                              }
?>
</table>
</form>
</code>```

Body:
I am trying to submit this form but it only submits the hidden input field. I can't understand why. It was working before.

while ($row = mysqli_fetch_array($gettimesheets)) {
    $date = $row['Date'];
    $date = date('d-m-Y', strtotime($date));
    $teachername = $row['StaffName'];
    $teacherid = $row['StaffID'];
    $starttime = $row['StartTime'];
    $endtime = $row['EndTime'];
    $totalhours = $row['TotalHours'];
    $timesheetid = $row['id'];

    ?>

        <form action="edittimesheet.php" method="post">
            <?php echo $date; ?>
            <?php echo $teachername; ?>
            <?php echo $teacherid; ?>
            <input type="time" name="starttime" class="form-control" value="<?php echo $starttime; ?>">
            <input type="time" name="endtime" class="form-control" value="<?php echo $endtime; ?>">
                <input type="text" name="timesheetid" value="<?php echo $timesheetid; ?>" hidden>

                <input type="submit" class="btn btn-success" value="Edit"/>
                <a href="deletetimesheet.php?id=<?php echo $timesheetid; ?>"
                   class="btn btn-simple btn-danger">Delete

        </form>

    <?php
}

Body:
Make your form outside your table and on your edit-submit button the id you edit.

<form action="edittimesheet.php"
<table>
<?php
while ($row = mysqli_fetch_array($gettimesheets)) {
     $date = $row['Date'];
     $date = date('d-m-Y', strtotime($date));
     $teachername = $row['StaffName'];
     $teacherid = $row['StaffID'];
     $starttime = $row['StartTime'];
     $endtime = $row['EndTime'];
     $totalhours = $row['TotalHours'];
     $timesheetid = $row['id'];

                                                ?>
                                                <tr>
method="post">
                                                  <td class="text-center"><?php echo $date ;?></td>
                                                  <td><?php echo $teachername ;?></td>
                                                  <td><?php echo $teacherid ;?></td>
                                                  <td><input type="time" name="starttime[$timesheetid]" class="form-control" value="<?php echo $starttime; ?>" ></td>
                                                  <td><input type="time" name="endtime[$timesheetid]" class="form-control" value="<?php echo $endtime; ?>" >
                                                  <input type="text" name="timesheetid[$timesheetid]" value="<?php echo $timesheetid; ?>" hidden></td>
                                                  <td class="text-right">
                                                    <input type="submit" name="edit" value ="<?php echo $timesheetid; ?>;" class="btn btn-success" value="Edit"/>
                                                    <a href="deletetimesheet.php?id=<?php echo $timesheetid; ?>" class="btn btn-simple btn-danger">Delete</a>
                                                  </td>

                                                </tr>

                                                <?php
                                              }
?>
</table>
</form>


问:
Java: How to @SuppressWarnings unreachable code?
Sometimes when you are debugging, you have unreachable code fragment. Is there anyway to suppress the warning?</p>

答:
According to the Java Language Specification:

It is a compile-time error if a statement cannot be executed because it is unreachable.

You can sometimes turn unreachable code into dead code (e.g., the body of if (false) {...}). But it being an error is part of the language definition.


问:
How to implement router animation in Blazor?
I want to have some animation when navigating between pages in Blazor

How can I implement router animation in the Blazor app?

答:
Currently no such feature is supported in Blazor. The Router system in Blazor provides very limited functionality compared to, say, Angular. Be patient. Its coming. Meanwhile you may implement router animation by creating a custom router system of yourself. See articles by chris sainty how to do it. This... and that...

Hope this helps...


问:
How do I find out if user clicked on button on front end from backend?
So I think I have a simple situation here. I want to know which button my users are clicking even if they don't make it to their destination, so click rate over click-through rate. I want to know if people were turned off by a redirect or not, before they get redirected back. Hopefully that makes sense. So I want to find a way to get the front end js code to communicate with the backend code. So I can either read a notification saying "hey this dude clicked on this link" or of course just add it to a dataset and come up with analytics, but the main thing I want it to do is tell the backend code when someone clicked on a front end button.</p>

答:
You can use an EventListeners to listen event click on your different buttons.
When user click on some button, you can use fetch API or axios to do an Ajax call to notify your back end for this action.</p>


问:
Change browser-default form dropdown buttons?
I have a very strange CSS problem affecting different browsers and I don't understand how this happens. How can I style the form dropdown menu buttons and dropdown content? The background color can been changed, the border can be changed but the border-radius doesn't change when changing the CSS border radius.

The form button looks different on every browser. The dropdown menu shows best on Firefox as it has no border radius, no glow like Safari and even the dropdown content shows a green background color and white text.

1 = Safari, glow + border radius + basic white dropdown content.

2 = Chrome, border radius + basic white dropdown content + greater length.

3 = Firefox, perfectly styled, has styled dropdown content but terrible dropdown icon!

答:
This is not a dropdown element - but a select html element and as such has limited styling available and as you have found - much variation between browsers.

You can hide the browser native icon and insert one of your own by setting position: relative on the parent (select-wrapper) element and position: absolute on the child (icon) element and position it as you want.

This allows you to have control over the look of the icon. Be aware that the glow on focus is recommended for accessibility concerns - but you can remove that if you absolutely want to.

.select-wrapper {
  position: relative;
  width: 90px
}

select {
  padding: 4px 24px 4px 8px;
  font-size: 14px;
  background: #36af4b;
  color: #fff;
  border-radius: 4px;
   -webkit-appearance: none;
    -moz-appearance: none;
    text-indent: 1px;
    text-overflow: '';
    width: 100%;
    display: block
}

select:focus {
  outline: none;
}

.select-wrapper .fa{
  position: absolute;
  color: #fff;
  right: 10px;
  top: 5px;
  z-index: 1
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />

<div class="select-wrapper">
  <select>
   <option> option 1</option>
   <option> option 2</option>
   <option> option 3</option>
  </select>
  <span class="fa fa-angle-down"></span>
</div></code>```

Body:
This is not a dropdown element - but a select html element and as such has limited styling available and as you have found - much variation between browsers.

You can hide the browser native icon and insert one of your own by setting position: relative on the parent (select-wrapper) element and position: absolute on the child (icon) element and position it as you want.

This allows you to have control over the look of the icon. Be aware that the glow on focus is recommended for accessibility concerns - but you can remove that if you absolutely want to.

.select-wrapper {
  position: relative;
  width: 90px
}

select {
  padding: 4px 24px 4px 8px;
  font-size: 14px;
  background: #36af4b;
  color: #fff;
  border-radius: 4px;
   -webkit-appearance: none;
    -moz-appearance: none;
    text-indent: 1px;
    text-overflow: '';
    width: 100%;
    display: block
}

select:focus {
  outline: none;
}

.select-wrapper .fa{
  position: absolute;
  color: #fff;
  right: 10px;
  top: 5px;
  z-index: 1
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />

<div class="select-wrapper">
  <select>
   <option> option 1</option>
   <option> option 2</option>
   <option> option 3</option>
  </select>
  <span class="fa fa-angle-down"></span>
</div>


问:
Telegram desktop locking by shortcut?
How to lock desktop telegram using shortcuts on Ubuntu? (So that I need to enter local passcode to use it further)</p>

答:
I made some research and the answer is:

Ctrl + L

This site helped me, there are some extra shortcuts for telegram

Title: Telegram desktop locking by shortcut?


问:
How to click on specific part of element puppeteer
Say I have an element that's 500 pixels wide, called 'selector'. How would I go about, for example, clicking on pixel 400?

According to the puppeteer docs, .hover() will hover over the middle of the element. And when I tested it using code like

```<code>const selector = await page.$('selector');
await selector.hover();
await selector.click();
</code>```

sure enough, it clicked right on pixel 250. So clearly, the code exists to make this happen. I looked through the puppeteer docs, but couldn't find the source code I needed. Can anyone help?

答:
Puppeteer provides a method to click on a specific pixel on the page (Mouse.click(x, y)). You could calculate where that is relative to your element's position:

```<code>const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto("http://yoursite.com");

  const elem = await page.$("#my-element");
  await clickOnElement(elem, 400);

  await page.screenshot({ path: "example.png" });

  await browser.close();

  // Clicks on an element at position x,y
  async function clickOnElement(elem, x = null, y = null) {
    const rect = await page.evaluate(el => {
      const { top, left, width, height } = el.getBoundingClientRect();
      return { top, left, width, height };
    }, elem);

    // Use given position or default to center
    const _x = x !== null ? x : rect.width / 2;
    const _y = y !== null ? y : rect.height / 2;

    await page.mouse.click(rect.left + _x, rect.top + _y);
  }
})();
</code>```

Body:
Say I have an element that's 500 pixels wide, called 'selector'. How would I go about, for example, clicking on pixel 400?

According to the puppeteer docs, .hover() will hover over the middle of the element. And when I tested it using code like

const selector = await page.$('selector');
await selector.hover();
await selector.click();

sure enough, it clicked right on pixel 250. So clearly, the code exists to make this happen. I looked through the puppeteer docs, but couldn't find the source code I needed. Can anyone help?

Body:
Puppeteer provides a method to click on a specific pixel on the page (Mouse.click(x, y)). You could calculate where that is relative to your element's position:

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto("http://yoursite.com");

  const elem = await page.$("#my-element");
  await clickOnElement(elem, 400);

  await page.screenshot({ path: "example.png" });

  await browser.close();

  // Clicks on an element at position x,y
  async function clickOnElement(elem, x = null, y = null) {
    const rect = await page.evaluate(el => {
      const { top, left, width, height } = el.getBoundingClientRect();
      return { top, left, width, height };
    }, elem);

    // Use given position or default to center
    const _x = x !== null ? x : rect.width / 2;
    const _y = y !== null ? y : rect.height / 2;

    await page.mouse.click(rect.left + _x, rect.top + _y);
  }
})();


问:
Synchronizing events of my system into most widely used calendars
I have implemented a (sports field) booking system. I would like to add one feature: when a customer makes a booking I would like to offer him the possibility to get/sync his newly created entry in his own calendar.

One solution what I already found is to create an iCalendar feed for the customer with his bookings. So he can take this feed (basically an URL pointing to a user-specific .ics file) and integrate it into his calendar applications (as most will support the addition of external calendars).
One bottleneck with this solution is that a good amount of customers use Gmail and its calendar. And it may take some time until Gmail refreshes external calendars. So it may take up to few hours until the newly created entry appears in the customers calendar.
Of course there's no such problem when customer is using calendar apps which offer more frequent or on-demand synchronization.

So my question here: what other solutions can you recommend? An export in a file for the newly created event? Or any other technology to sync our bookings with the most widely used calendars? What would be the most usable solution for customers?

答:
If you want to be able to auto update / synchronise the booking by having the user subscribe,  then the ics feed is the standard cross application way to do it.

If it is just one booking and is never going to be updated, then you could encourage them to import the ics file to their calendar which usually then appears within seconds.

You can also email them the ics file.  It is then not subscribeable as it is NOT a url.  How it is handled depends on their email and system setup, but most would offer import into their calendar. (Mine opens in notepad++) ;)


问:
how to enable remote debugging from window machine to Ubuntu machine via netbeans
I want to run remote debugging from Netbeans IDE, OS for remote PC is Ubuntu.
Ubuntu has got some firewall setup, how do I enable it to allow request(remote debugging) from Windows pc?
The application running in Ubuntu is not a web application </p>

答:
I changed the run script and added debug command to execute my jar in debug mode

java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=,suspend=n appname

Configure Netbeans, using attach debugger mentioning remote host IP and port number (same port number used in debug script).
Then stopped firewall in Ubuntu (remote host), as it is ours by running the following command

systemctl stop firewalld

Started the application in debug mode
Clicked attach debugger and OK from Netbeans after setting breakpoint


问:
Walls not showing
I exported some mesh in fbx format and imported in Unity. As you can see in the screenshoots, the walls are not shown to the camera. Why is this happening? How can I fix this?

答:
Could be wrong normals.

Fly around in the scene view and check if the room is visible from the outside. If so, invert the normals with a 3D modeling programm.

Or change the shader to show both sides (disable Backface culling)

Title: Walls not showing


问:
Using ctrl+d to end caesar cipher
I know there are a few similar questions already posted, but all the solutions I tried did not fix my code. So, my caesar cipher is working as intended. However, I want to be able to exit using ctrl+d, rather than ctrl+c. My code right now is:

```<code>int main (int argc, char *argv[]){
        char code[500], ch;
        int c, key;
        key = atoi(argv[1]);
        printf("%s",code);
        for(;;){
                fgets(code, 500, stdin);
                for(c = 0;code[c] != '\0'; ++c){
                        ch = code[c];
                        if(ch >= 'a' && ch <= 'z'){
                                ch = ch + key;
                                if(ch > 'z'){
                                        ch = ch - 26 ;
                                }
                                else if(ch < 'a'){
                                        ch = ch + 26;
                                }
                                code[c] = ch;
                        }
                        else if(ch >= 'A' && ch <= 'Z'){
                                ch = ch + key;
                                if(ch > 'Z'){
                                        ch = ch - 'Z' + 'A' - 1;
                                }
                                else if(ch < 'A'){
                                        ch = ch + 26;
                                }
                                code[c] = ch;
                        }
                }
                printf("%s\n", code);
        }
        return 0;
}
</code>```

When I compile it, run it, and type

```<code>./a.out 2
abc
</code>```

it returns "cde" and leaves the command line hanging so I can type another string.
However, when I press ctrl+d, it just reiterates the program (if I press ctrl+d after seeing cde, it will return efg), when I want it to exit the program when I press it.

One solution I found was to add a

```<code>if(code == EOF (or '\0' or NULL)) {
   break;
}
</code>```

Aside from warning me that there was point and integer comparison warning, none of them worked.
Does anyone know how to fix this?
Any help is greatly appreciated!

答:
replace:

```<code> for(;;){
                fgets(code, 500, stdin);
</code>```

with:

```<code>while (fgets(code, sizeof code, stdin)) {
</code>```

and EOF will cause fgets to return NULL, thus stopping your program.

Title: Using ctrl+d to end caesar cipher

Body:
I know there are a few similar questions already posted, but all the solutions I tried did not fix my code. So, my caesar cipher is working as intended. However, I want to be able to exit using ctrl+d, rather than ctrl+c. My code right now is:

int main (int argc, char *argv[]){
        char code[500], ch;
        int c, key;
        key = atoi(argv[1]);
        printf("%s",code);
        for(;;){
                fgets(code, 500, stdin);
                for(c = 0;code[c] != '\0'; ++c){
                        ch = code[c];
                        if(ch >= 'a' && ch <= 'z'){
                                ch = ch + key;
                                if(ch > 'z'){
                                        ch = ch - 26 ;
                                }
                                else if(ch < 'a'){
                                        ch = ch + 26;
                                }
                                code[c] = ch;
                        }
                        else if(ch >= 'A' && ch <= 'Z'){
                                ch = ch + key;
                                if(ch > 'Z'){
                                        ch = ch - 'Z' + 'A' - 1;
                                }
                                else if(ch < 'A'){
                                        ch = ch + 26;
                                }
                                code[c] = ch;
                        }
                }
                printf("%s\n", code);
        }
        return 0;
}

When I compile it, run it, and type

./a.out 2
abc

it returns "cde" and leaves the command line hanging so I can type another string.
However, when I press ctrl+d, it just reiterates the program (if I press ctrl+d after seeing cde, it will return efg), when I want it to exit the program when I press it.

One solution I found was to add a

if(code == EOF (or '\0' or NULL)) {
   break;
}

Aside from warning me that there was point and integer comparison warning, none of them worked.
Does anyone know how to fix this?
Any help is greatly appreciated!

Body:
replace:

 for(;;){
                fgets(code, 500, stdin);

with:

while (fgets(code, sizeof code, stdin)) {

and EOF will cause fgets to return NULL, thus stopping your program.


问:
Divide a Set into Subsets of objects having equal field?
I am currently trying to implement a data structure in java, and would like to divide a set of input objects, into different subsets of objects having an equal field.

An example use case:

We want to divide a list of persons to sub list of persons being born a certain date.

Input: person1 born 1990, person2 born 2000, person3 born 1990.

Output:

1 -> person1, person3

2 -> person2

```<code>public Map<Integer, List<Foo>> getIntToFooMap(List<Foo> foos) {
    Map<Integer, List<Foo>> map = new TreeMap<>(); // need keys to be automatically ordered.
    List<Foo> foosWithSameSetId = new ArrayList<>();
    if (!foos.isEmpty) {
       for (Foo foo: foos) {
           for (Foo foo2: foos) {
               if (foo.getSetId().equals(foo2.getSetId())) {
                   foosWithSameSetId.add(foo2);
               }
           }
        map.put(foo.getSetId(), foosWithSameSetId);
        foosWithSameSetId.clear();
       }
    }
  return map;
 }
</code>```

The code above is not optimal, the time complexity is quadratic, and also not thread safe.
Can someone tell me of a better way to divide a List or a Set into subsets of objects having an equal field, in this case the setId.

答: Try a hashmap, it should handle hashing for you to bring your runtime down to near linear. </p>

Body:
I am currently trying to implement a data structure in java, and would like to divide a set of input objects, into different subsets of objects having an equal field.

An example use case:

We want to divide a list of persons to sub list of persons being born a certain date.

Input: person1 born 1990, person2 born 2000, person3 born 1990.

Output:

1 -> person1, person3

2 -> person2

public Map<Integer, List<Foo>> getIntToFooMap(List<Foo> foos) {
    Map<Integer, List<Foo>> map = new TreeMap<>(); // need keys to be automatically ordered.
    List<Foo> foosWithSameSetId = new ArrayList<>();
    if (!foos.isEmpty) {
       for (Foo foo: foos) {
           for (Foo foo2: foos) {
               if (foo.getSetId().equals(foo2.getSetId())) {
                   foosWithSameSetId.add(foo2);
               }
           }
        map.put(foo.getSetId(), foosWithSameSetId);
        foosWithSameSetId.clear();
       }
    }
  return map;
 }

The code above is not optimal, the time complexity is quadratic, and also not thread safe.
Can someone tell me of a better way to divide a List or a Set into subsets of objects having an equal field, in this case the setId.


问:
How do I create a new list of dictionaries based on a key-value result?
I have a list of dictionaries. For example, something like [{'sex':'male'}, {'sex':'male'}, {'sex':'male'}, {'sex':'female'}, {'sex':'female'}. Imagine this, but way bigger.

How would I be able to go though and make a new list with just the male dictionaries? It would look like [{'sex':'male'}, {'sex':'male'}, {'sex':'male'}

答:
There are many ways you can go about doing this. One of them is using list comprehensions.

```<code>old_list = [{'sex':'male'}, {'sex':'male'}, {'sex':'male'}, {'sex':'female'}, {'sex':'female'}]

new_list = [item for item in old_list if item.get('sex') == 'male']
</code>```

However, if your original list had 10 million dictionaries inside, Python would go over the 10 million items before it continues with other stuff.

Another way would be to use a filter, this one is better if you have a very large number of dictionaries in your list because it would not process all of them at once but would rather kind of "stream" them when you use the new_list in another loop, the way this would work is as follows. The way filter works is by taking a function that returns either True or False. This function is then provided every list item. If it returns True, the item stays, if it returns False the item is filtered out.

```<code>new_list = filter(lambda item: item.get('sex') == 'male', old_list)
</code>```

Be careful that if you have items in your list that are not dictionaries, you would need to make sure that they are dictionaries before calling .get() on them. You can do this by changing your conditions to be isinstance(item, dict) and item.get('sex') == 'male'

Body:
There are many ways you can go about doing this. One of them is using list comprehensions.

old_list = [{'sex':'male'}, {'sex':'male'}, {'sex':'male'}, {'sex':'female'}, {'sex':'female'}]

new_list = [item for item in old_list if item.get('sex') == 'male']

However, if your original list had 10 million dictionaries inside, Python would go over the 10 million items before it continues with other stuff.

Another way would be to use a filter, this one is better if you have a very large number of dictionaries in your list because it would not process all of them at once but would rather kind of "stream" them when you use the new_list in another loop, the way this would work is as follows. The way filter works is by taking a function that returns either True or False. This function is then provided every list item. If it returns True, the item stays, if it returns False the item is filtered out.

new_list = filter(lambda item: item.get('sex') == 'male', old_list)

Be careful that if you have items in your list that are not dictionaries, you would need to make sure that they are dictionaries before calling .get() on them. You can do this by changing your conditions to be isinstance(item, dict) and item.get('sex') == 'male'


问:
Requests Timeout Error (requests.exceptions.ConnectionError: ('Connection aborted.', OSError("(10060, 'WSAETIMEDOUT')")))
I have seen a lot of questions on this topic but none of them contain a solution that works for me yet. Here is my full code:

```<code>import pandas as pd
import requests
import time

pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

# Game Id
game_id = '0021900001'

# Headers for API Request
header_data = {
    'Host': 'stats.nba.com',
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
    'Referer': 'stats.nba.com',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
}

###
### Calculate Players on court at the start of each period
###

# Build advanced boxscore url
def advanced_boxscore_url(game_id, start, end):
    return 'https://stats.nba.com/stats/boxscoretraditionalv2/?gameId={0}&startPeriod=0&endPeriod=14&startRange={1}&endRange={2}&rangeType=2'.format(game_id, start, end)

# Helper functions
def calculate_time_at_period(period):
    if period > 5:
        return (720 * 4 + (period - 5) * (5 * 60)) * 10
    else:
        return (720 * (period - 1)) * 10

def split_subs(df, tag):
    subs = df[[tag, 'PERIOD', 'EVENTNUM']]
    subs['SUB'] = tag
    subs.columns = ['PLAYER_ID', 'PERIOD', 'EVENTNUM', 'SUB']
    return subs

def frame_to_row(df):
    team1 = df['TEAM_ID'].unique()[0]
    team2 = df['TEAM_ID'].unique()[1]
    players1 = df[df['TEAM_ID'] == team1]['PLAYER_ID'].tolist()
    players1.sort()
    players2 = df[df['TEAM_ID'] == team2]['PLAYER_ID'].tolist()
    players2.sort()

    lst = [team1]
    lst.append(players1)
    lst.append(team2)
    lst.append(players2)

    return lst

# extracts data from api response
def extract_data(url):
    print(url)
    r = requests.get(url, headers=header_data)
    resp = r.json()
    results = resp['resultSets'][0]
    headers = results['headers']
    rows = results['rowSet']
    frame = pd.DataFrame(rows)
    frame.columns = headers
    return frame

play_by_play = pd.read_csv('pbp_v3_0210.csv')

substitutionsOnly = play_by_play[play_by_play['EVENTMSGTYPE'] == 8][['PERIOD', 'EVENTNUM', 'PLAYER1_ID', 'PLAYER2_ID']]
substitutionsOnly.columns = ['PERIOD', 'EVENTNUM', 'OUT', 'IN']

subs_in = split_subs(substitutionsOnly, 'IN')
subs_out = split_subs(substitutionsOnly, 'OUT')

full_subs = pd.concat([subs_out, subs_in], axis=0).reset_index()[['PLAYER_ID', 'PERIOD', 'EVENTNUM', 'SUB']]
first_event_of_period = full_subs.loc[full_subs.groupby(by=['PERIOD', 'PLAYER_ID'])['EVENTNUM'].idxmin()]
players_subbed_in_at_each_period = first_event_of_period[first_event_of_period['SUB'] == 'IN'][
    ['PLAYER_ID', 'PERIOD', 'SUB']]

periods = players_subbed_in_at_each_period['PERIOD'].drop_duplicates().values.tolist()

rows = []
for period in periods:
    low = calculate_time_at_period(period) + 5
    high = calculate_time_at_period(period + 1) - 5
    boxscore = advanced_boxscore_url(game_id, low, high)
    # time.sleep(2)
    boxscore_players = extract_data(boxscore)[['PLAYER_NAME', 'PLAYER_ID', 'TEAM_ID']]
    boxscore_players['PERIOD'] = period

    players_subbed_in_at_period = players_subbed_in_at_each_period[players_subbed_in_at_each_period['PERIOD'] == period]

    joined_players = pd.merge(boxscore_players, players_subbed_in_at_period, on=['PLAYER_ID', 'PERIOD'], how='left')
    joined_players = joined_players[pd.isnull(joined_players['SUB'])][['PLAYER_NAME', 'PLAYER_ID', 'TEAM_ID', 'PERIOD']]
    row = frame_to_row(joined_players)
    row.append(period)
    rows.append(row)

players_on_court_at_start_of_period = pd.DataFrame(rows)
cols = ['TEAM_ID_1', 'TEAM_1_PLAYERS', 'TEAM_ID_2', 'TEAM_2_PLAYERS', 'PERIOD']
players_on_court_at_start_of_period.columns = cols

holder = "00219"
for x in range(2, 10):
    time.sleep(2)
    if x == 707:
        continue
    excess = ""
    if(x < 10):
        excess = "0000" + str(x)
    elif(x < 100):
        excess = "000" + str(x)
    elif(x < 1000):
        excess = "00" + str(x)
    else:
        excess = "0" + str(x)
    holder = "00219" + excess
    game_id = holder

    holder_play_by_play = pd.read_csv('pbp_for_parsing')

    substitutionsOnly = holder_play_by_play[holder_play_by_play['EVENTMSGTYPE'] == 8][
        ['PERIOD', 'EVENTNUM', 'PLAYER1_ID', 'PLAYER2_ID']]
    substitutionsOnly.columns = ['PERIOD', 'EVENTNUM', 'OUT', 'IN']

    subs_in = split_subs(substitutionsOnly, 'IN')
    subs_out = split_subs(substitutionsOnly, 'OUT')

    full_subs = pd.concat([subs_out, subs_in], axis=0).reset_index()[['PLAYER_ID', 'PERIOD', 'EVENTNUM', 'SUB']]
    first_event_of_period = full_subs.loc[full_subs.groupby(by=['PERIOD', 'PLAYER_ID'])['EVENTNUM'].idxmin()]
    players_subbed_in_at_each_period = first_event_of_period[first_event_of_period['SUB'] == 'IN'][
        ['PLAYER_ID', 'PERIOD', 'SUB']]

    periods = players_subbed_in_at_each_period['PERIOD'].drop_duplicates().values.tolist()

    rows = []
    for period in periods:
        low = calculate_time_at_period(period) + 5
        high = calculate_time_at_period(period + 1) - 5
        boxscore = advanced_boxscore_url(game_id, low, high)
        boxscore_players = extract_data(boxscore)[['PLAYER_NAME', 'PLAYER_ID', 'TEAM_ID']]
        boxscore_players['PERIOD'] = period

        players_subbed_in_at_period = players_subbed_in_at_each_period[
            players_subbed_in_at_each_period['PERIOD'] == period]

        joined_players = pd.merge(boxscore_players, players_subbed_in_at_period, on=['PLAYER_ID', 'PERIOD'], how='left')
        joined_players = joined_players[pd.isnull(joined_players['SUB'])][
            ['PLAYER_NAME', 'PLAYER_ID', 'TEAM_ID', 'PERIOD']]
        row = frame_to_row(joined_players)
        row.append(period)
        rows.append(row)

    holder_players_on_court_at_start_of_period = pd.DataFrame(rows)
    cols = ['TEAM_ID_1', 'TEAM_1_PLAYERS', 'TEAM_ID_2', 'TEAM_2_PLAYERS', 'PERIOD']
    holder_players_on_court_at_start_of_period.columns = cols
    players_on_court_at_start_of_period = players_on_court_at_start_of_period.concat([players_on_court_at_start_of_period, holder_players_on_court_at_start_of_period], axis=0).reset_index()[['TEAM_ID_1', 'TEAM_1_PLAYERS', 'TEAM_ID_2', 'TEAM_2_PLAYERS', 'PERIOD']]

players_on_court_at_start_of_period.to_csv("onoff0210.csv", index=False)
</code>```

The full error message I am receiving is:

```<code>Traceback (most recent call last):
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 672, in urlopen
    chunked=chunked,
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 421, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 416, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\http\client.py", line 1344, in getresponse
    response.begin()
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\http\client.py", line 306, in begin
    version, status, reason = self._read_status()
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\http\client.py", line 267, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\socket.py", line 589, in readinto
    return self._sock.recv_into(b)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\contrib\pyopenssl.py", line 318, in recv_into
    raise SocketError(str(e))
OSError: (10060, 'WSAETIMEDOUT')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\requests\adapters.py", line 449, in send
    timeout=timeout
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 720, in urlopen
    method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\util\retry.py", line 400, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\packages\six.py", line 734, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 672, in urlopen
    chunked=chunked,
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 421, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 416, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\http\client.py", line 1344, in getresponse
    response.begin()
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\http\client.py", line 306, in begin
    version, status, reason = self._read_status()
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\http\client.py", line 267, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\socket.py", line 589, in readinto
    return self._sock.recv_into(b)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\contrib\pyopenssl.py", line 318, in recv_into
    raise SocketError(str(e))
urllib3.exceptions.ProtocolError: ('Connection aborted.', OSError("(10060, 'WSAETIMEDOUT')"))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/xxxxx/PycharmProjects/NBAdata/V.3/On Off V3.py", line 100, in <module>
    boxscore_players = extract_data(boxscore)[['PLAYER_NAME', 'PLAYER_ID', 'TEAM_ID']]
  File "C:/Users/xxxxx/PycharmProjects/NBAdata/V.3/On Off V3.py", line 69, in extract_data
    r = requests.get(url, headers=header_data)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\requests\api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\requests\sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\requests\sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\requests\adapters.py", line 498, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', OSError("(10060, 'WSAETIMEDOUT')"))
</code>```

I'm not the most experienced with this kind of code, so I came to stack overflow to try to find a solution, some involving create a User-Agent (which I have already done), switching advanced LAN settings in control panel (couldn't even find advanced LAN settings, might have been removed from Windows), trying to use an online IDE (but none of the ones I have found allow me to both import a csv and have my code output to a csv when done), trying to add a timeout to my requests.get (which really only caused more errors), and maybe even some others that I am forgetting at the moment. I have also made a bunch of other files with somewhat similar formats and similar targets urls that have worked fine. And yes, my internet connection is completely fine, everything else runs smoothly, including other Python files.

This has really caused a roadblock in my current project and I can't really continue anything until I resolve this, so if anybody can come in with a magical solution that would be fantastic. The expected result of this code is that it would iterate through the for loop all the way through the maximum parameter and output a csv that would then be used as a dataframe for all of the data I had just scraped.

答: As it turns out, the Key Error was being raised because the value began with '00' before the rest of the string, but the dataframe read that value as an integer and chopped off those two zeroes, creating a URL that went to nowhere. After changing the datatype, the program works fine now. </p>

Body:
I have seen a lot of questions on this topic but none of them contain a solution that works for me yet. Here is my full code:

import pandas as pd
import requests
import time

pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

# Game Id
game_id = '0021900001'

# Headers for API Request
header_data = {
    'Host': 'stats.nba.com',
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
    'Referer': 'stats.nba.com',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
}

###
### Calculate Players on court at the start of each period
###

# Build advanced boxscore url
def advanced_boxscore_url(game_id, start, end):
    return 'https://stats.nba.com/stats/boxscoretraditionalv2/?gameId={0}&startPeriod=0&endPeriod=14&startRange={1}&endRange={2}&rangeType=2'.format(game_id, start, end)

# Helper functions
def calculate_time_at_period(period):
    if period > 5:
        return (720 * 4 + (period - 5) * (5 * 60)) * 10
    else:
        return (720 * (period - 1)) * 10

def split_subs(df, tag):
    subs = df[[tag, 'PERIOD', 'EVENTNUM']]
    subs['SUB'] = tag
    subs.columns = ['PLAYER_ID', 'PERIOD', 'EVENTNUM', 'SUB']
    return subs

def frame_to_row(df):
    team1 = df['TEAM_ID'].unique()[0]
    team2 = df['TEAM_ID'].unique()[1]
    players1 = df[df['TEAM_ID'] == team1]['PLAYER_ID'].tolist()
    players1.sort()
    players2 = df[df['TEAM_ID'] == team2]['PLAYER_ID'].tolist()
    players2.sort()

    lst = [team1]
    lst.append(players1)
    lst.append(team2)
    lst.append(players2)

    return lst

# extracts data from api response
def extract_data(url):
    print(url)
    r = requests.get(url, headers=header_data)
    resp = r.json()
    results = resp['resultSets'][0]
    headers = results['headers']
    rows = results['rowSet']
    frame = pd.DataFrame(rows)
    frame.columns = headers
    return frame

play_by_play = pd.read_csv('pbp_v3_0210.csv')

substitutionsOnly = play_by_play[play_by_play['EVENTMSGTYPE'] == 8][['PERIOD', 'EVENTNUM', 'PLAYER1_ID', 'PLAYER2_ID']]
substitutionsOnly.columns = ['PERIOD', 'EVENTNUM', 'OUT', 'IN']

subs_in = split_subs(substitutionsOnly, 'IN')
subs_out = split_subs(substitutionsOnly, 'OUT')

full_subs = pd.concat([subs_out, subs_in], axis=0).reset_index()[['PLAYER_ID', 'PERIOD', 'EVENTNUM', 'SUB']]
first_event_of_period = full_subs.loc[full_subs.groupby(by=['PERIOD', 'PLAYER_ID'])['EVENTNUM'].idxmin()]
players_subbed_in_at_each_period = first_event_of_period[first_event_of_period['SUB'] == 'IN'][
    ['PLAYER_ID', 'PERIOD', 'SUB']]

periods = players_subbed_in_at_each_period['PERIOD'].drop_duplicates().values.tolist()

rows = []
for period in periods:
    low = calculate_time_at_period(period) + 5
    high = calculate_time_at_period(period + 1) - 5
    boxscore = advanced_boxscore_url(game_id, low, high)
    # time.sleep(2)
    boxscore_players = extract_data(boxscore)[['PLAYER_NAME', 'PLAYER_ID', 'TEAM_ID']]
    boxscore_players['PERIOD'] = period

    players_subbed_in_at_period = players_subbed_in_at_each_period[players_subbed_in_at_each_period['PERIOD'] == period]

    joined_players = pd.merge(boxscore_players, players_subbed_in_at_period, on=['PLAYER_ID', 'PERIOD'], how='left')
    joined_players = joined_players[pd.isnull(joined_players['SUB'])][['PLAYER_NAME', 'PLAYER_ID', 'TEAM_ID', 'PERIOD']]
    row = frame_to_row(joined_players)
    row.append(period)
    rows.append(row)

players_on_court_at_start_of_period = pd.DataFrame(rows)
cols = ['TEAM_ID_1', 'TEAM_1_PLAYERS', 'TEAM_ID_2', 'TEAM_2_PLAYERS', 'PERIOD']
players_on_court_at_start_of_period.columns = cols

holder = "00219"
for x in range(2, 10):
    time.sleep(2)
    if x == 707:
        continue
    excess = ""
    if(x < 10):
        excess = "0000" + str(x)
    elif(x < 100):
        excess = "000" + str(x)
    elif(x < 1000):
        excess = "00" + str(x)
    else:
        excess = "0" + str(x)
    holder = "00219" + excess
    game_id = holder

    holder_play_by_play = pd.read_csv('pbp_for_parsing')

    substitutionsOnly = holder_play_by_play[holder_play_by_play['EVENTMSGTYPE'] == 8][
        ['PERIOD', 'EVENTNUM', 'PLAYER1_ID', 'PLAYER2_ID']]
    substitutionsOnly.columns = ['PERIOD', 'EVENTNUM', 'OUT', 'IN']

    subs_in = split_subs(substitutionsOnly, 'IN')
    subs_out = split_subs(substitutionsOnly, 'OUT')

    full_subs = pd.concat([subs_out, subs_in], axis=0).reset_index()[['PLAYER_ID', 'PERIOD', 'EVENTNUM', 'SUB']]
    first_event_of_period = full_subs.loc[full_subs.groupby(by=['PERIOD', 'PLAYER_ID'])['EVENTNUM'].idxmin()]
    players_subbed_in_at_each_period = first_event_of_period[first_event_of_period['SUB'] == 'IN'][
        ['PLAYER_ID', 'PERIOD', 'SUB']]

    periods = players_subbed_in_at_each_period['PERIOD'].drop_duplicates().values.tolist()

    rows = []
    for period in periods:
        low = calculate_time_at_period(period) + 5
        high = calculate_time_at_period(period + 1) - 5
        boxscore = advanced_boxscore_url(game_id, low, high)
        boxscore_players = extract_data(boxscore)[['PLAYER_NAME', 'PLAYER_ID', 'TEAM_ID']]
        boxscore_players['PERIOD'] = period

        players_subbed_in_at_period = players_subbed_in_at_each_period[
            players_subbed_in_at_each_period['PERIOD'] == period]

        joined_players = pd.merge(boxscore_players, players_subbed_in_at_period, on=['PLAYER_ID', 'PERIOD'], how='left')
        joined_players = joined_players[pd.isnull(joined_players['SUB'])][
            ['PLAYER_NAME', 'PLAYER_ID', 'TEAM_ID', 'PERIOD']]
        row = frame_to_row(joined_players)
        row.append(period)
        rows.append(row)

    holder_players_on_court_at_start_of_period = pd.DataFrame(rows)
    cols = ['TEAM_ID_1', 'TEAM_1_PLAYERS', 'TEAM_ID_2', 'TEAM_2_PLAYERS', 'PERIOD']
    holder_players_on_court_at_start_of_period.columns = cols
    players_on_court_at_start_of_period = players_on_court_at_start_of_period.concat([players_on_court_at_start_of_period, holder_players_on_court_at_start_of_period], axis=0).reset_index()[['TEAM_ID_1', 'TEAM_1_PLAYERS', 'TEAM_ID_2', 'TEAM_2_PLAYERS', 'PERIOD']]

players_on_court_at_start_of_period.to_csv("onoff0210.csv", index=False)

The full error message I am receiving is:

Traceback (most recent call last):
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 672, in urlopen
    chunked=chunked,
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 421, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 416, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\http\client.py", line 1344, in getresponse
    response.begin()
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\http\client.py", line 306, in begin
    version, status, reason = self._read_status()
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\http\client.py", line 267, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\socket.py", line 589, in readinto
    return self._sock.recv_into(b)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\contrib\pyopenssl.py", line 318, in recv_into
    raise SocketError(str(e))
OSError: (10060, 'WSAETIMEDOUT')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\requests\adapters.py", line 449, in send
    timeout=timeout
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 720, in urlopen
    method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\util\retry.py", line 400, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\packages\six.py", line 734, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 672, in urlopen
    chunked=chunked,
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 421, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\connectionpool.py", line 416, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\http\client.py", line 1344, in getresponse
    response.begin()
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\http\client.py", line 306, in begin
    version, status, reason = self._read_status()
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\http\client.py", line 267, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\socket.py", line 589, in readinto
    return self._sock.recv_into(b)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\urllib3\contrib\pyopenssl.py", line 318, in recv_into
    raise SocketError(str(e))
urllib3.exceptions.ProtocolError: ('Connection aborted.', OSError("(10060, 'WSAETIMEDOUT')"))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/xxxxx/PycharmProjects/NBAdata/V.3/On Off V3.py", line 100, in <module>
    boxscore_players = extract_data(boxscore)[['PLAYER_NAME', 'PLAYER_ID', 'TEAM_ID']]
  File "C:/Users/xxxxx/PycharmProjects/NBAdata/V.3/On Off V3.py", line 69, in extract_data
    r = requests.get(url, headers=header_data)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\requests\api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\requests\sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\requests\sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\xxxxx\Anaconda3\envs\NBAdata\lib\site-packages\requests\adapters.py", line 498, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', OSError("(10060, 'WSAETIMEDOUT')"))

I'm not the most experienced with this kind of code, so I came to stack overflow to try to find a solution, some involving create a User-Agent (which I have already done), switching advanced LAN settings in control panel (couldn't even find advanced LAN settings, might have been removed from Windows), trying to use an online IDE (but none of the ones I have found allow me to both import a csv and have my code output to a csv when done), trying to add a timeout to my requests.get (which really only caused more errors), and maybe even some others that I am forgetting at the moment. I have also made a bunch of other files with somewhat similar formats and similar targets urls that have worked fine. And yes, my internet connection is completely fine, everything else runs smoothly, including other Python files.

This has really caused a roadblock in my current project and I can't really continue anything until I resolve this, so if anybody can come in with a magical solution that would be fantastic. The expected result of this code is that it would iterate through the for loop all the way through the maximum parameter and output a csv that would then be used as a dataframe for all of the data I had just scraped.


问:
How to send a photo on Telegram that has InlineKeyboardMarkup using Python post request and a Telegram bot
I have the following file:

```<code># get_request.py

import requests

API_TOKEN = "fake:APITOken"

# api-endpoint
URL = "https://api.telegram.org/bot" + API_TOKEN + "/sendphoto"

multipart_form_data = {
    'photo': ('pic.png', open('pic.png', 'rb')),
    'action': (None, 'send'),
    'chat_id': (None, <MY-ID>),
    'caption': (None, 'This is a *description* of the _image_'),
    'parse_mode': (None, 'Markdown'),
    'reply_to_message_id': (None, 103),
    # 'reply_markup': (None, [[{"text": "Hello"}, {"text": "Bye"}, {"text": "I love you"}]])
}

response = requests.post(URL, files=multipart_form_data)

data = response.json()

import json
print(json.dumps(data, sort_keys=True, indent=4))
</code>```

The problem is that I want to uncomment the reply_markup line, because I want to add some buttons to the image, but uncommenting this line gives me:

```<code>Traceback (most recent call last):
  File "get_request.py", line 32, in <module>
    response = requests.post(URL, files=multipart_form_data)
  File "/usr/local/lib/python3.7/site-packages/requests/api.py", line 116, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/requests/api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/requests/sessions.py", line 519, in request
    prep = self.prepare_request(req)
  File "/usr/local/lib/python3.7/site-packages/requests/sessions.py", line 462, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/usr/local/lib/python3.7/site-packages/requests/models.py", line 316, in prepare
    self.prepare_body(data, files, json)
  File "/usr/local/lib/python3.7/site-packages/requests/models.py", line 504, in prepare_body
    (body, content_type) = self._encode_files(files, data)
  File "/usr/local/lib/python3.7/site-packages/requests/models.py", line 169, in _encode_files
    body, content_type = encode_multipart_formdata(new_fields)
  File "/usr/local/lib/python3.7/site-packages/urllib3/filepost.py", line 90, in encode_multipart_formdata
    body.write(data)
TypeError: a bytes-like object is required, not 'list'
</code>```

How can I solve this issue?

答:
Your missing the inline_keyboard key. Also use json.dumps to create an proper obj for the form_data;

Don't forget to add some CallBack data to the button to tell them apart if somebody clicks them;

```<code>{"text": "Hello", "callback_data": "x"}
</code>```

Updated code;

```<code># get_request.py

import requests

API_TOKEN = "fake:APITOken"

# api-endpoint
URL = "https://api.telegram.org/bot" + API_TOKEN + "/sendphoto"

keyboard=json.dumps({ "inline_keyboard": [ [ {"text": "Hello", "callback_data": "x"}, {"text": "Bye", "callback_data": "x"}, {"text": "I love you", "callback_data": "x"} ] ] })

multipart_form_data = {
    'photo': ('pic.png', open('pic.png', 'rb')),
    'action': (None, 'send'),
    'chat_id': (None, <ID>),
    'caption': (None, 'This is a *description* of the _image_'),
    'parse_mode': (None, 'Markdown'),
    'reply_to_message_id': (None, 103),
    'reply_markup': (None, keyboard )
}

response = requests.post(URL, files=multipart_form_data)

data = response.json()

import json
print(json.dumps(data, sort_keys=True, indent=4))
</code>```

Body:
I have the following file:

# get_request.py

import requests

API_TOKEN = "fake:APITOken"

# api-endpoint
URL = "https://api.telegram.org/bot" + API_TOKEN + "/sendphoto"

multipart_form_data = {
    'photo': ('pic.png', open('pic.png', 'rb')),
    'action': (None, 'send'),
    'chat_id': (None, <MY-ID>),
    'caption': (None, 'This is a *description* of the _image_'),
    'parse_mode': (None, 'Markdown'),
    'reply_to_message_id': (None, 103),
    # 'reply_markup': (None, [[{"text": "Hello"}, {"text": "Bye"}, {"text": "I love you"}]])
}

response = requests.post(URL, files=multipart_form_data)

data = response.json()

import json
print(json.dumps(data, sort_keys=True, indent=4))

The problem is that I want to uncomment the reply_markup line, because I want to add some buttons to the image, but uncommenting this line gives me:

Traceback (most recent call last):
  File "get_request.py", line 32, in <module>
    response = requests.post(URL, files=multipart_form_data)
  File "/usr/local/lib/python3.7/site-packages/requests/api.py", line 116, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/requests/api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/requests/sessions.py", line 519, in request
    prep = self.prepare_request(req)
  File "/usr/local/lib/python3.7/site-packages/requests/sessions.py", line 462, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/usr/local/lib/python3.7/site-packages/requests/models.py", line 316, in prepare
    self.prepare_body(data, files, json)
  File "/usr/local/lib/python3.7/site-packages/requests/models.py", line 504, in prepare_body
    (body, content_type) = self._encode_files(files, data)
  File "/usr/local/lib/python3.7/site-packages/requests/models.py", line 169, in _encode_files
    body, content_type = encode_multipart_formdata(new_fields)
  File "/usr/local/lib/python3.7/site-packages/urllib3/filepost.py", line 90, in encode_multipart_formdata
    body.write(data)
TypeError: a bytes-like object is required, not 'list'

How can I solve this issue?

Body:
Your missing the inline_keyboard key. Also use json.dumps to create an proper obj for the form_data;

Don't forget to add some CallBack data to the button to tell them apart if somebody clicks them;

{"text": "Hello", "callback_data": "x"}

Updated code;

# get_request.py

import requests

API_TOKEN = "fake:APITOken"

# api-endpoint
URL = "https://api.telegram.org/bot" + API_TOKEN + "/sendphoto"

keyboard=json.dumps({ "inline_keyboard": [ [ {"text": "Hello", "callback_data": "x"}, {"text": "Bye", "callback_data": "x"}, {"text": "I love you", "callback_data": "x"} ] ] })

multipart_form_data = {
    'photo': ('pic.png', open('pic.png', 'rb')),
    'action': (None, 'send'),
    'chat_id': (None, <ID>),
    'caption': (None, 'This is a *description* of the _image_'),
    'parse_mode': (None, 'Markdown'),
    'reply_to_message_id': (None, 103),
    'reply_markup': (None, keyboard )
}

response = requests.post(URL, files=multipart_form_data)

data = response.json()

import json
print(json.dumps(data, sort_keys=True, indent=4))