问:
remove a string from the column name
I have a table with column name is:

```<code>> head(a1)[1:5,1:3]
                a1_a1_AAACCTGAGCGTTTAC-1 a1_a1_AAACCTGAGTCGCCGT-1 a1_a1_AAACCTGGTAGGACAC-1
ENSG00000243485                        0                        0                        0
ENSG00000237613                        0                        0                        0
ENSG00000186092                        0                        0                        0
ENSG00000238009                        0                        0                        0
ENSG00000239945                        0                        0                        0
</code>```

I want to delete the "a1_" in my column name.

Thanks in advance for great help!

Best,

Yue

```<code>> head(a1)[1:5,1:3]
                a1_AAACCTGAGCGTTTAC-1 a1_AAACCTGAGTCGCCGT-1 a1_AAACCTGGTAGGACAC-1
ENSG00000243485                     0                     0                     0
ENSG00000237613                     0                     0                     0
ENSG00000186092                     0                     0                     0
ENSG00000238009                     0                     0                     0
ENSG00000239945                     0                     0                     0
</code>```

答:
if you want to remove just one a1

```<code>library(stringr)
colnames(a1) <- str_remove(colnames(a1), "^a1_")
</code>```

base R

```<code>colnames(a1) <- gsub("^a1_", "",colnames(a1))
</code>```

Title: remove a string from the column name

Body:
I have a table with column name is:

> head(a1)[1:5,1:3]
                a1_a1_AAACCTGAGCGTTTAC-1 a1_a1_AAACCTGAGTCGCCGT-1 a1_a1_AAACCTGGTAGGACAC-1
ENSG00000243485                        0                        0                        0
ENSG00000237613                        0                        0                        0
ENSG00000186092                        0                        0                        0
ENSG00000238009                        0                        0                        0
ENSG00000239945                        0                        0                        0

I want to delete the "a1_" in my column name.

Thanks in advance for great help!

Best,

Yue

> head(a1)[1:5,1:3]
                a1_AAACCTGAGCGTTTAC-1 a1_AAACCTGAGTCGCCGT-1 a1_AAACCTGGTAGGACAC-1
ENSG00000243485                     0                     0                     0
ENSG00000237613                     0                     0                     0
ENSG00000186092                     0                     0                     0
ENSG00000238009                     0                     0                     0
ENSG00000239945                     0                     0                     0

Body:
if you want to remove just one a1

library(stringr)
colnames(a1) <- str_remove(colnames(a1), "^a1_")

base R

colnames(a1) <- gsub("^a1_", "",colnames(a1))


来源: stackexchange

问:
Python: Parse multiple tables from webpage and group data in CSV
I'm a total newbie at Python and have what I think is a pretty complex problem. I'd like to parse two tables from a website for about 80 URLs, example of one of the pages: https://www.sports-reference.com/cfb/players/sam-darnold-1.html

I'd need the first table "Passing" and the second table "Rushing and Receiving" from each of the 80 URLs (I know how to get the first and second table). But the problem is I need it for all 80 URLs in one csv.

This is my code so far and how the data looks:

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

COLUMNS = ['School', 'Conf', 'Class', 'Pos', 'G', 'Cmp', 'Att', 'Pct', 'Yds','Y/A', 'AY/A', 'TD', 'Int', 'Rate']

urls = ['https://www.sports-reference.com/cfb/players/russell-wilson-1.html',
        'https://www.sports-reference.com/cfb/players/cam-newton-1.html',
        'https://www.sports-reference.com/cfb/players/peyton-manning-1.html']
#scrape elements

dataframes = []
try:
    for url in urls:
        response = requests.get(url)
        soup = BeautifulSoup(response.content, "html.parser")
        #print(soup)
        table = soup.find_all('table')[0] # Find the first "table" tag in the page
        rows = table.find_all("tr")
        cy_data = []
        for row in rows:
            cells = row.find_all("td")
            cells = cells[0:14]
            cy_data.append([cell.text for cell in cells]) # For each "td" tag, get the text inside it

        dataframes.append(pd.DataFrame(cy_data, columns=COLUMNS).drop(0, axis=0))
except:
    pass

data = pd.concat(dataframes)
data.to_csv('testcsv3.csv', sep=',') ```

+---+--+----------------------+---------+-------+-----+----+-----+------+------+-------+------+------+-----+-----+-------+
|   |  |        School        |  Conf   | Class | Pos | G  | Cmp | Att  | Pct  |  Yds  | Y/A  | AY/A | TD  | Int | Rate  |
+---+--+----------------------+---------+-------+-----+----+-----+------+------+-------+------+------+-----+-----+-------+
| 1 |  |                      |         |       |     |    |     |      |      |       |      |      |     |     |       |
| 2 |  | North Carolina State | ACC     | FR    | QB  | 11 | 150 |  275 | 54.5 |  1955 |  7.1 |  8.2 |  17 |   1 | 133.9 |
| 3 |  | North Carolina State | ACC     | SO    | QB  | 12 | 224 |  378 | 59.3 |  3027 |    8 |  8.3 |  31 |  11 | 147.8 |
| 4 |  | North Carolina State | ACC     | JR    | QB  | 13 | 308 |  527 | 58.4 |  3563 |  6.8 |  6.6 |  28 |  14 | 127.5 |
| 5 |  | Wisconsin            | Big Ten | SR    | QB  | 14 | 225 |  309 | 72.8 |  3175 | 10.3 | 11.8 |  33 |   4 | 191.8 |
| 6 |  | Overall              |         |       |     |    | 907 | 1489 | 60.9 | 11720 |  7.9 |  8.4 | 109 |  30 | 147.2 |
| 7 |  | North Carolina State |         |       |     |    | 682 | 1180 | 57.8 |  8545 |  7.2 |  7.5 |  76 |  26 | 135.5 |
| 8 |  | Wisconsin            |         |       |     |    | 225 |  309 | 72.8 |  3175 | 10.3 | 11.8 |  33 |   4 | 191.8 |
| 1 |  |                      |         |       |     |    |     |      |      |       |      |      |     |     |       |
| 2 |  | Florida              | SEC     | FR    | QB  |  5 |   5 |   10 |   50 |    40 |    4 |    4 |   0 |   0 |  83.6 |
| 3 |  | Florida              | SEC     | SO    | QB  |  1 |   1 |    2 |   50 |    14 |    7 |    7 |   0 |   0 | 108.8 |
| 4 |  | Auburn               | SEC     | JR    | QB  | 14 | 185 |  280 | 66.1 |  2854 | 10.2 | 11.2 |  30 |   7 |   182 |
| 5 |  | Overall              |         |       |     |    | 191 |  292 | 65.4 |  2908 |   10 | 10.9 |  30 |   7 | 178.2 |
| 6 |  | Florida              |         |       |     |    |   6 |   12 |   50 |    54 |  4.5 |  4.5 |   0 |   0 |  87.8 |
| 7 |  | Auburn               |         |       |     |    | 185 |  280 | 66.1 |  2854 | 10.2 | 11.2 |  30 |   7 |   182 |
+---+--+----------------------+---------+-------+-----+----+-----+------+------+-------+------+------+-----+-----+-------+

And this is how I'd like the data to look, note the player name is missing from each grouping which ideally can be added from the sample website/url and I've added the second table which I need help appending:

+---+----------------+----------------------+---------+-------+-----+----+-----+------+------+-------+------+------+-----+-----+-------+----------------------+---------+-------+-----+----+-----+-----+-----+----+
|   |                |        School        |  Conf   | Class | Pos | G  | Cmp | Att  | Pct  |  Yds  | Y/A  | AY/A | TD  | Int | Rate  |        School        |  Conf   | Class | Pos | G  | Att | Yds | Avg | TD |
+---+----------------+----------------------+---------+-------+-----+----+-----+------+------+-------+------+------+-----+-----+-------+----------------------+---------+-------+-----+----+-----+-----+-----+----+
| 1 |                |                      |         |       |     |    |     |      |      |       |      |      |     |     |       |                      |         |       |     |    |     |     |     |    |
| 2 | Russell Wilson | North Carolina State | ACC     | FR    | QB  | 11 | 150 |  275 | 54.5 |  1955 |  7.1 |  8.2 |  17 |   1 | 133.9 | North Carolina State | ACC     | FR    | QB  | 11 | 150 | 467 | 6.7 |  3 |
| 3 | Russell Wilson | North Carolina State | ACC     | SO    | QB  | 12 | 224 |  378 | 59.3 |  3027 |    8 |  8.3 |  31 |  11 | 147.8 | North Carolina State | ACC     | SO    | QB  | 12 | 129 | 300 | 6.8 |  2 |
| 4 | Russell Wilson | North Carolina State | ACC     | JR    | QB  | 13 | 308 |  527 | 58.4 |  3563 |  6.8 |  6.6 |  28 |  14 | 127.5 | North Carolina State | ACC     | JR    | QB  | 13 | 190 | 560 | 7.1 |  5 |
| 5 | Russell Wilson | Wisconsin            | Big Ten | SR    | QB  | 14 | 225 |  309 | 72.8 |  3175 | 10.3 | 11.8 |  33 |   4 | 191.8 | Wisconsin            | Big Ten | SR    | QB  | 14 | 210 | 671 | 7.3 |  7 |
| 6 | Russell Wilson | Overall              |         |       |     |    | 907 | 1489 | 60.9 | 11720 |  7.9 |  8.4 | 109 |  30 | 147.2 | Overall              |         |       |     |    |     |     |     |    |
| 7 | Russell Wilson | North Carolina State |         |       |     |    | 682 | 1180 | 57.8 |  8545 |  7.2 |  7.5 |  76 |  26 | 135.5 | North Carolina State |         |       |     |    |     |     |     |    |
| 8 | Russell Wilson | Wisconsin            |         |       |     |    | 225 |  309 | 72.8 |  3175 | 10.3 | 11.8 |  33 |   4 | 191.8 | Wisconsin            |         |       |     |    |     |     |     |    |
| 1 |                |                      |         |       |     |    |     |      |      |       |      |      |     |     |       |                      |         |       |     |    |     |     |     |    |
| 2 | Cam Newton     | Florida              | SEC     | FR    | QB  |  5 |   5 |   10 |   50 |    40 |    4 |    4 |   0 |   0 |  83.6 | Florida              | SEC     | FR    | QB  |  5 | 210 | 456 | 7.1 |  2 |
| 3 | Cam Newton     | Florida              | SEC     | SO    | QB  |  1 |   1 |    2 |   50 |    14 |    7 |    7 |   0 |   0 | 108.8 | Florida              | SEC     | SO    | QB  |  1 | 212 | 478 | 4.5 |  5 |
| 4 | Cam Newton     | Auburn               | SEC     | JR    | QB  | 14 | 185 |  280 | 66.1 |  2854 | 10.2 | 11.2 |  30 |   7 |   182 | Auburn               | SEC     | JR    | QB  | 14 | 219 | 481 | 6.7 |  6 |
| 5 | Cam Newton     | Overall              |         |       |     |    | 191 |  292 | 65.4 |  2908 |   10 | 10.9 |  30 |   7 | 178.2 | Overall              |         |       |     |    |     |     | 3.4 |  7 |
| 6 | Cam Newton     | Florida              |         |       |     |    |   6 |   12 |   50 |    54 |  4.5 |  4.5 |   0 |   0 |  87.8 | Florida              |         |       |     |    |     |     |     |    |
| 7 | Cam Newton     | Auburn               |         |       |     |    | 185 |  280 | 66.1 |  2854 | 10.2 | 11.2 |  30 |   7 |   182 | Auburn               |         |       |     |    |     |     |     |    |
+---+----------------+----------------------+---------+-------+-----+----+-----+------+------+-------+------+------+-----+-----+-------+----------------------+---------+-------+-----+----+-----+-----+-----+----+

So basically I'd wanna append the second table (Only the columns mentioned) to the end of the first table and add the player name (read from the URL) to each row

```

答:
```<code>import requests
import pandas as pd
from bs4 import BeautifulSoup

COLUMNS = ['School', 'Conf', 'Class', 'Pos', 'G', 'Cmp', 'Att', 'Pct', 'Yds','Y/A', 'AY/A', 'TD', 'Int', 'Rate']
COLUMNS2 = ['School', 'Conf', 'Class', 'Pos', 'G', 'Att', 'Yds','Avg', 'TD', 'Rec', 'Yds', 'Avg', 'TD', 'Plays', 'Yds', 'Avg', 'TD']

urls = ['https://www.sports-reference.com/cfb/players/russell-wilson-1.html',
        'https://www.sports-reference.com/cfb/players/cam-newton-1.html',
        'https://www.sports-reference.com/cfb/players/peyton-manning-1.html']
#scrape elements

dataframes = []
dataframes2 = []
for url in urls:
    a = url
    print(a)
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")
    #print(soup)
    table = soup.find_all('table')[0] # Find the first "table" tag in the page
    rows = table.find_all("tr")
    cy_data = []
    for row in rows:
        cells = row.find_all("td")
        cells = cells[0:14]
        cy_data.append([cell.text for cell in cells]) # For each "td" tag, get the text inside it
    cy_data = pd.DataFrame(cy_data, columns=COLUMNS)

    #Create player column in first column and derive the player from the URL
    cy_data.insert(0, 'Player', url)
    cy_data['Player'] = cy_data['Player'].str.split('/').str[5].str.split('-').str[0].str.title() + ' ' + cy_data['Player'].str.split('/').str[5].str.split('-').str[1].str.title()
    dataframes.append(cy_data)

    table2 = soup.find_all('table')[1] # Find the second "table" tag in the page
    rows2 = table2.find_all("tr")
    cy_data2 = []
    for row2 in rows2:
        cells2 = row2.find_all("td")
        cells2 = cells2[0:14]
        cy_data2.append([cell.text for cell in cells2]) # For each "td" tag, get the text inside it
    cy_data2 = pd.DataFrame(cy_data2, columns=COLUMNS2)
    cy_data2.insert(0, 'Player', url)
    cy_data2['Player'] = cy_data2['Player'].str.split('/').str[5].str.split('-').str[0].str.title() + ' ' + cy_data2['Player'].str.split('/').str[5].str.split('-').str[1].str.title()
    dataframes2.append(cy_data2)

data = pd.concat(dataframes).reset_index()
data2 = pd.concat(dataframes).reset_index()
data3 = data.merge(data2, on=['index', 'Player'], suffixes=('',' '))
#Filter on None rows
data3 = data3.loc[data3['School'].notnull()].drop('index', axis=1)
display(data, data2, data3)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm a total newbie at Python and have what I think is a pretty complex problem. I'd like to parse two tables from a website for about 80 URLs, example of one of the pages: https://www.sports-reference.com/cfb/players/sam-darnold-1.html

I'd need the first table "Passing" and the second table "Rushing and Receiving" from each of the 80 URLs (I know how to get the first and second table). But the problem is I need it for all 80 URLs in one csv.

This is my code so far and how the data looks:

import requests
import pandas as pd

COLUMNS = ['School', 'Conf', 'Class', 'Pos', 'G', 'Cmp', 'Att', 'Pct', 'Yds','Y/A', 'AY/A', 'TD', 'Int', 'Rate']

urls = ['https://www.sports-reference.com/cfb/players/russell-wilson-1.html',
        'https://www.sports-reference.com/cfb/players/cam-newton-1.html',
        'https://www.sports-reference.com/cfb/players/peyton-manning-1.html']
#scrape elements

dataframes = []
try:
    for url in urls:
        response = requests.get(url)
        soup = BeautifulSoup(response.content, "html.parser")
        #print(soup)
        table = soup.find_all('table')[0] # Find the first "table" tag in the page
        rows = table.find_all("tr")
        cy_data = []
        for row in rows:
            cells = row.find_all("td")
            cells = cells[0:14]
            cy_data.append([cell.text for cell in cells]) # For each "td" tag, get the text inside it

        dataframes.append(pd.DataFrame(cy_data, columns=COLUMNS).drop(0, axis=0))
except:
    pass

data = pd.concat(dataframes)
data.to_csv('testcsv3.csv', sep=',') ```

+---+--+----------------------+---------+-------+-----+----+-----+------+------+-------+------+------+-----+-----+-------+
|   |  |        School        |  Conf   | Class | Pos | G  | Cmp | Att  | Pct  |  Yds  | Y/A  | AY/A | TD  | Int | Rate  |
+---+--+----------------------+---------+-------+-----+----+-----+------+------+-------+------+------+-----+-----+-------+
| 1 |  |                      |         |       |     |    |     |      |      |       |      |      |     |     |       |
| 2 |  | North Carolina State | ACC     | FR    | QB  | 11 | 150 |  275 | 54.5 |  1955 |  7.1 |  8.2 |  17 |   1 | 133.9 |
| 3 |  | North Carolina State | ACC     | SO    | QB  | 12 | 224 |  378 | 59.3 |  3027 |    8 |  8.3 |  31 |  11 | 147.8 |
| 4 |  | North Carolina State | ACC     | JR    | QB  | 13 | 308 |  527 | 58.4 |  3563 |  6.8 |  6.6 |  28 |  14 | 127.5 |
| 5 |  | Wisconsin            | Big Ten | SR    | QB  | 14 | 225 |  309 | 72.8 |  3175 | 10.3 | 11.8 |  33 |   4 | 191.8 |
| 6 |  | Overall              |         |       |     |    | 907 | 1489 | 60.9 | 11720 |  7.9 |  8.4 | 109 |  30 | 147.2 |
| 7 |  | North Carolina State |         |       |     |    | 682 | 1180 | 57.8 |  8545 |  7.2 |  7.5 |  76 |  26 | 135.5 |
| 8 |  | Wisconsin            |         |       |     |    | 225 |  309 | 72.8 |  3175 | 10.3 | 11.8 |  33 |   4 | 191.8 |
| 1 |  |                      |         |       |     |    |     |      |      |       |      |      |     |     |       |
| 2 |  | Florida              | SEC     | FR    | QB  |  5 |   5 |   10 |   50 |    40 |    4 |    4 |   0 |   0 |  83.6 |
| 3 |  | Florida              | SEC     | SO    | QB  |  1 |   1 |    2 |   50 |    14 |    7 |    7 |   0 |   0 | 108.8 |
| 4 |  | Auburn               | SEC     | JR    | QB  | 14 | 185 |  280 | 66.1 |  2854 | 10.2 | 11.2 |  30 |   7 |   182 |
| 5 |  | Overall              |         |       |     |    | 191 |  292 | 65.4 |  2908 |   10 | 10.9 |  30 |   7 | 178.2 |
| 6 |  | Florida              |         |       |     |    |   6 |   12 |   50 |    54 |  4.5 |  4.5 |   0 |   0 |  87.8 |
| 7 |  | Auburn               |         |       |     |    | 185 |  280 | 66.1 |  2854 | 10.2 | 11.2 |  30 |   7 |   182 |
+---+--+----------------------+---------+-------+-----+----+-----+------+------+-------+------+------+-----+-----+-------+

And this is how I'd like the data to look, note the player name is missing from each grouping which ideally can be added from the sample website/url and I've added the second table which I need help appending:

+---+----------------+----------------------+---------+-------+-----+----+-----+------+------+-------+------+------+-----+-----+-------+----------------------+---------+-------+-----+----+-----+-----+-----+----+
|   |                |        School        |  Conf   | Class | Pos | G  | Cmp | Att  | Pct  |  Yds  | Y/A  | AY/A | TD  | Int | Rate  |        School        |  Conf   | Class | Pos | G  | Att | Yds | Avg | TD |
+---+----------------+----------------------+---------+-------+-----+----+-----+------+------+-------+------+------+-----+-----+-------+----------------------+---------+-------+-----+----+-----+-----+-----+----+
| 1 |                |                      |         |       |     |    |     |      |      |       |      |      |     |     |       |                      |         |       |     |    |     |     |     |    |
| 2 | Russell Wilson | North Carolina State | ACC     | FR    | QB  | 11 | 150 |  275 | 54.5 |  1955 |  7.1 |  8.2 |  17 |   1 | 133.9 | North Carolina State | ACC     | FR    | QB  | 11 | 150 | 467 | 6.7 |  3 |
| 3 | Russell Wilson | North Carolina State | ACC     | SO    | QB  | 12 | 224 |  378 | 59.3 |  3027 |    8 |  8.3 |  31 |  11 | 147.8 | North Carolina State | ACC     | SO    | QB  | 12 | 129 | 300 | 6.8 |  2 |
| 4 | Russell Wilson | North Carolina State | ACC     | JR    | QB  | 13 | 308 |  527 | 58.4 |  3563 |  6.8 |  6.6 |  28 |  14 | 127.5 | North Carolina State | ACC     | JR    | QB  | 13 | 190 | 560 | 7.1 |  5 |
| 5 | Russell Wilson | Wisconsin            | Big Ten | SR    | QB  | 14 | 225 |  309 | 72.8 |  3175 | 10.3 | 11.8 |  33 |   4 | 191.8 | Wisconsin            | Big Ten | SR    | QB  | 14 | 210 | 671 | 7.3 |  7 |
| 6 | Russell Wilson | Overall              |         |       |     |    | 907 | 1489 | 60.9 | 11720 |  7.9 |  8.4 | 109 |  30 | 147.2 | Overall              |         |       |     |    |     |     |     |    |
| 7 | Russell Wilson | North Carolina State |         |       |     |    | 682 | 1180 | 57.8 |  8545 |  7.2 |  7.5 |  76 |  26 | 135.5 | North Carolina State |         |       |     |    |     |     |     |    |
| 8 | Russell Wilson | Wisconsin            |         |       |     |    | 225 |  309 | 72.8 |  3175 | 10.3 | 11.8 |  33 |   4 | 191.8 | Wisconsin            |         |       |     |    |     |     |     |    |
| 1 |                |                      |         |       |     |    |     |      |      |       |      |      |     |     |       |                      |         |       |     |    |     |     |     |    |
| 2 | Cam Newton     | Florida              | SEC     | FR    | QB  |  5 |   5 |   10 |   50 |    40 |    4 |    4 |   0 |   0 |  83.6 | Florida              | SEC     | FR    | QB  |  5 | 210 | 456 | 7.1 |  2 |
| 3 | Cam Newton     | Florida              | SEC     | SO    | QB  |  1 |   1 |    2 |   50 |    14 |    7 |    7 |   0 |   0 | 108.8 | Florida              | SEC     | SO    | QB  |  1 | 212 | 478 | 4.5 |  5 |
| 4 | Cam Newton     | Auburn               | SEC     | JR    | QB  | 14 | 185 |  280 | 66.1 |  2854 | 10.2 | 11.2 |  30 |   7 |   182 | Auburn               | SEC     | JR    | QB  | 14 | 219 | 481 | 6.7 |  6 |
| 5 | Cam Newton     | Overall              |         |       |     |    | 191 |  292 | 65.4 |  2908 |   10 | 10.9 |  30 |   7 | 178.2 | Overall              |         |       |     |    |     |     | 3.4 |  7 |
| 6 | Cam Newton     | Florida              |         |       |     |    |   6 |   12 |   50 |    54 |  4.5 |  4.5 |   0 |   0 |  87.8 | Florida              |         |       |     |    |     |     |     |    |
| 7 | Cam Newton     | Auburn               |         |       |     |    | 185 |  280 | 66.1 |  2854 | 10.2 | 11.2 |  30 |   7 |   182 | Auburn               |         |       |     |    |     |     |     |    |
+---+----------------+----------------------+---------+-------+-----+----+-----+------+------+-------+------+------+-----+-----+-------+----------------------+---------+-------+-----+----+-----+-----+-----+----+

So basically I'd wanna append the second table (Only the columns mentioned) to the end of the first table and add the player name (read from the URL) to each row


问:
If Godot scripts A and B both extend script C, do A and B share the same variable names of those from C?
I'm new to the Godot engine.

If gd scripts A and B both extend script C and var_c is a variable in the script C, is var_c used in A different from var_c used in B?

So my scripts A and B extend script C.
A and B represent different states in a finite statement machine.
For example, in the finite state machine demo that came with the initial installment of Godot (from Steam), say C is motion.gd and A, B are move.gd and jump.gd.

I'm introducing a variable var_c in C hoping that it is "shared" by A and B in the sense that if var_c is updated in state A (say I write

```<code>var_c = 123
</code>```

in script A) and when I enter state B, I wish to access the updated value of var_c like

```<code>if var_c == 123:
     print("A and B seem to share the same value of var_c!")
</code>```

Unfortunately, it looks like var_c that I call in state A is independent of var_c called in state B. I might have made a mistake, but I want to know if it is true in general.

Are var_c used in A and var_c used in B the same? If they are different, how do I access one from the other? Like A.var_c and B.var_c?

Thank you.

答:
If the scripts each have unique names (ex: examplescriptA.gd and examplescriptB.gd), the variables contained within should be local to that script, as Godot doesn't really recognize global variables in the strictest sense.
If you want the equivalent of a global variable system (ie: a set of variables that can be accessed and updated from any other script), you should look into using singletons.

Documentation is here - https://docs.godotengine.org/en/stable/getting_started/step_by_step/singletons_autoload.html

I have also read about the notion of "extending" a script, and apparrently it is possible. It seems you can change the node inheritance in a script to extend another script (ex: extends "res://your_script.gd"). The only quirk, it seems, is you have to call .ready() in the _ready() function of the "parent" script. I have not had a chance to test this myself, however, and I'm not sure it works in both directions - for that, I would go the singleton route. Regardless, if you need a better reference the full discussion I took this from, you can find it here: https://godotengine.org/qa/2391/can-you-inherit-from-a-script

I hope you find least one of these helpful.

Body:
I'm new to the Godot engine.

If gd scripts A and B both extend script C and var_c is a variable in the script C, is var_c used in A different from var_c used in B?

So my scripts A and B extend script C.
A and B represent different states in a finite statement machine.
For example, in the finite state machine demo that came with the initial installment of Godot (from Steam), say C is motion.gd and A, B are move.gd and jump.gd.

I'm introducing a variable var_c in C hoping that it is "shared" by A and B in the sense that if var_c is updated in state A (say I write

var_c = 123

in script A) and when I enter state B, I wish to access the updated value of var_c like

if var_c == 123:
     print("A and B seem to share the same value of var_c!")

Unfortunately, it looks like var_c that I call in state A is independent of var_c called in state B. I might have made a mistake, but I want to know if it is true in general.

Are var_c used in A and var_c used in B the same? If they are different, how do I access one from the other? Like A.var_c and B.var_c?

Thank you.


问:
Unable to upload Azure Storage File Share File from browser using Rest API (JavaScript)
I am attempting to upload a file from a browser directly to a File Share File. The operation's spec is pretty straight forward, send an HTTP PUT request to a URL (with a SAS token) along with some headers. I attempted to implement this with a simple HTML form and some backing JavaScript in this jsfiddle. To my surprise the system fails, and responds XML indicating that the Content-Length header is incorrect:

<?xml version="1.0" encoding="utf-8"?>
<Error>
  InvalidHeaderValue
  <Message>The value for one of the HTTP headers is not in the correct format.
RequestId:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
Time:0000-00-00T00:00:00.0000000Z</Message>
  <HeaderName>Content-Length</HeaderName>
  <HeaderValue>12345</HeaderValue>
</Error>
```

I double checked the documentation, and it indicates that the Content-Length header should not be present, or it should have a value specifically containing 0. I did some digging, and Content-Length is a forbidden header name, which means you can't adjust the value programmatically.

To my puzzle, using the embeddd Azure Storage Explorer within Azure Portal jumps through some kind of hoops in order to specify Content-Length:0.

My goals are to:

Use the REST API from the browser

Not introduce any external libraries

Not introduce any servers

Is there way to use the REST API from the browser?

Some things that I have already checked:

I have tried forcing Content-Length:0 via the headers property.

I have ensured that CORS settings in my Azure Storage Account (for Files) have been updated to account for my browser's location.

I have attempted to integrate with Blobs as a comparison, which works great in the sample, but not what I am interested in for my project.

I have tried working with the API out of the browser, and I have no issues sending in the same request (of course Content-Length:0 deviates as requested by the specification).

I have tried mimicking the request headers as much as possible from a recorded XHR that was made from the Azure Portal.

答:
Creating a file in File Storage is different than uploading a blob.

In File Storage, first thing you would need to do is create an empty file using Create File REST operation. During this operation you specify the size of file you wish to create (your content's length) in x-ms-content-length request header.

Once an empty file is created, you send the content to write to the file using Put Range operation. This is where you actually send the content. You would need to use either Range or x-ms-range request header to specify where exactly in that empty file you wish to write the data you're sending.

Based on these, I modified your code. Here're the modified methods:

```<code>async function upload(url, headers, content) {
    if (!url) { return; }

    const init = {
        method: 'PUT',
        body: content,
        headers: headers
    };
    console.log(init);
    const response = await fetch(url, init);

    document.getElementById('response-content').innerText = await response.text();
}

async function uploadToFileStorage() {
    console.log('creating empty file');
    const url = document.getElementById('url').value;
    const content = document.getElementById('content').value;
    const headers = {
      'content-length': 0,
      'x-ms-type': 'file',
      'x-ms-content-length': content.length
    }
    await upload(url, headers, '');
    console.log('empty file created.');
    const url2 = url + '&comp=range';
    const headers2 = {
        'Content-Length': content.length,
        'x-ms-version': '2015-02-21',
        'Range': 'bytes=0-' + (content.length-1),
        'x-ms-write': 'update'
    };
    await upload(url2, headers2, content);
}
</code>```

Body:
I am attempting to upload a file from a browser directly to a File Share File. The operation's spec is pretty straight forward, send an HTTP PUT request to a URL (with a SAS token) along with some headers. I attempted to implement this with a simple HTML form and some backing JavaScript in this jsfiddle. To my surprise the system fails, and responds XML indicating that the Content-Length header is incorrect:

<?xml version="1.0" encoding="utf-8"?>
<Error>
  InvalidHeaderValue
  <Message>The value for one of the HTTP headers is not in the correct format.
RequestId:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
Time:0000-00-00T00:00:00.0000000Z</Message>
  <HeaderName>Content-Length</HeaderName>
  <HeaderValue>12345</HeaderValue>
</Error>

I double checked the documentation, and it indicates that the Content-Length header should not be present, or it should have a value specifically containing 0. I did some digging, and Content-Length is a forbidden header name, which means you can't adjust the value programmatically.

To my puzzle, using the embeddd Azure Storage Explorer within Azure Portal jumps through some kind of hoops in order to specify Content-Length:0.

My goals are to:

Use the REST API from the browser

Not introduce any external libraries

Not introduce any servers

Is there way to use the REST API from the browser?

Some things that I have already checked:

I have tried forcing Content-Length:0 via the headers property.

I have ensured that CORS settings in my Azure Storage Account (for Files) have been updated to account for my browser's location.

I have attempted to integrate with Blobs as a comparison, which works great in the sample, but not what I am interested in for my project.

I have tried working with the API out of the browser, and I have no issues sending in the same request (of course Content-Length:0 deviates as requested by the specification).

I have tried mimicking the request headers as much as possible from a recorded XHR that was made from the Azure Portal.

Body:
Creating a file in File Storage is different than uploading a blob.

In File Storage, first thing you would need to do is create an empty file using Create File REST operation. During this operation you specify the size of file you wish to create (your content's length) in x-ms-content-length request header.

Once an empty file is created, you send the content to write to the file using Put Range operation. This is where you actually send the content. You would need to use either Range or x-ms-range request header to specify where exactly in that empty file you wish to write the data you're sending.

Based on these, I modified your code. Here're the modified methods:

async function upload(url, headers, content) {
    if (!url) { return; }

    const init = {
        method: 'PUT',
        body: content,
        headers: headers
    };
    console.log(init);
    const response = await fetch(url, init);

    document.getElementById('response-content').innerText = await response.text();
}

async function uploadToFileStorage() {
    console.log('creating empty file');
    const url = document.getElementById('url').value;
    const content = document.getElementById('content').value;
    const headers = {
      'content-length': 0,
      'x-ms-type': 'file',
      'x-ms-content-length': content.length
    }
    await upload(url, headers, '');
    console.log('empty file created.');
    const url2 = url + '&comp=range';
    const headers2 = {
        'Content-Length': content.length,
        'x-ms-version': '2015-02-21',
        'Range': 'bytes=0-' + (content.length-1),
        'x-ms-write': 'update'
    };
    await upload(url2, headers2, content);
}


问:
Character Picture Grid
This is my first question in stackoverflow. Happy to join the community

This is a question in one of the books:

Say you have a list of lists where each value in the inner lists is a one-charac string, like this:

```<code>grid = [['.', '.', '.', '.', '.', '.'],
    ['.', '0', '0', '.', '.', '.'],
    ['0', '0', '0', '0', '.', '.'],
    ['0', '0', '0', '0', '0', '.'],
    ['.', '0', '0', '0', '0', '0'],
    ['0', '0', '0', '0', '0', '.'],
    ['0', '0', '0', '0', '.', '.'],
    ['.', '0', '0', '.', '.', '.'],
    ['.', '.', '.', '.', '.', '.']]
</code>```

result should be:

```<code>..00.00..
.0000000.
.0000000.
..00000..
...000...
....0....
</code>```

I managed to get the answer with this code:

```<code>Num_of_grid = range(len(grid))
for y in Num_of_grid:
    for x in Num_of_grid:
        print(grid[x][y], end = "")
    print("")
</code>```

However, even tho it solves the problem but for some reason I get the following error:
Click here for error image

When I write the following
print(x, y); it shows exactly the right number of range I used in the loop... which is (0,8) but still it gives me out of range.

答:
The problem her is that your grid is not square. You have 9 rows of 6 items in each. Yet, in both your loops, you are iterating over the same range of indices. To fix this, use the code:

```<code>Num_of_grid = range(len(grid))
Num_of_item = range(len(grid[0]))
for y in Num_of_item:
    for x in Num_of_grid:
        print(grid[x][y], end = "")
    print("")
</code>```

Better yet, use numpy, to make an array, transpose it, and print the result, this way:

```<code>import numpy as np
g = np.array(grid)
print("\n".join("".join(l) for l in g.T))
</code>```

Title: Character Picture Grid

Body:
This is my first question in stackoverflow. Happy to join the community

This is a question in one of the books:

Say you have a list of lists where each value in the inner lists is a one-charac string, like this:

grid = [['.', '.', '.', '.', '.', '.'],
    ['.', '0', '0', '.', '.', '.'],
    ['0', '0', '0', '0', '.', '.'],
    ['0', '0', '0', '0', '0', '.'],
    ['.', '0', '0', '0', '0', '0'],
    ['0', '0', '0', '0', '0', '.'],
    ['0', '0', '0', '0', '.', '.'],
    ['.', '0', '0', '.', '.', '.'],
    ['.', '.', '.', '.', '.', '.']]

result should be:

..00.00..
.0000000.
.0000000.
..00000..
...000...
....0....

I managed to get the answer with this code:

Num_of_grid = range(len(grid))
for y in Num_of_grid:
    for x in Num_of_grid:
        print(grid[x][y], end = "")
    print("")

However, even tho it solves the problem but for some reason I get the following error:
Click here for error image

When I write the following
print(x, y); it shows exactly the right number of range I used in the loop... which is (0,8) but still it gives me out of range.

Body:
The problem her is that your grid is not square. You have 9 rows of 6 items in each. Yet, in both your loops, you are iterating over the same range of indices. To fix this, use the code:

Num_of_grid = range(len(grid))
Num_of_item = range(len(grid[0]))
for y in Num_of_item:
    for x in Num_of_grid:
        print(grid[x][y], end = "")
    print("")

Better yet, use numpy, to make an array, transpose it, and print the result, this way:

import numpy as np
g = np.array(grid)
print("\n".join("".join(l) for l in g.T))


问:
Is Haskell a Lisp?
I've been reading The Haskell Road to Logic, Maths and Programming by Doets and Eijck 2004. It seems to be a well respected book, but I was struck when it claims that Haskell is a member of the Lisp family. Is this accurate? I would characterise Lisps with s-expressions, impure functions, and lists as the only composite data structure. Haskell has none of that. What justification is there for that claim?</p>

答:
I think Haskell is a Lisp in the sense that they're both based on the λ calculus.  Haskell is an implementation of λ.

Though most people would say that Haskell belongs to the ML family.  ML is also based on λ, as are all functional languages I know of.

Under the hood, OCam (descended from ML) is compiled to combinatory logic, a formalism that is equivalent to λ calculus, and was invented by Haskell Curry, the logician whom Haskell is named after.  But the use of combinatory logic for functional langauge compilation seems to be less popular nowadays, so I'm not sure about modern compilers like GHC.

Lisp's syntax is almost identical with λ calculus, which makes this family (Scheme, Clojure, etc) very special.

Title: Is Haskell a Lisp?

ContentLicense: CC BY-SA 3.0


问:
modify dataframe values based on other column
```<code>data = {'Payment_type' =['Mastercard','Visa','Visa','Diners'],'Price' = [1200,600,300,5000]}

</code>```

I'm struggling with how can I modify the price based on the payment type.
This is what I code and it is wrong

```<code>for i in df['Payment_Type']:
    if i == 'Visa':
        df['Price']*0.01
    elif i=='Matercard':
        df['Price']*0.02
    elif  i == 'Diners':
        df['Price']*0.03
    else:
        df['Price']*0.04
</code>```

答:
Let us try create dict with map

```<code>d = dict(zip(cards, [0.01,0.02,0.03]))
data.price = data.price*data.card.map(d).fillna(0.04)
</code>```

Body:
data = {'Payment_type' =['Mastercard','Visa','Visa','Diners'],'Price' = [1200,600,300,5000]}

I'm struggling with how can I modify the price based on the payment type.
This is what I code and it is wrong

for i in df['Payment_Type']:
    if i == 'Visa':
        df['Price']*0.01
    elif i=='Matercard':
        df['Price']*0.02
    elif  i == 'Diners':
        df['Price']*0.03
    else:
        df['Price']*0.04

Body:
Let us try create dict with map

d = dict(zip(cards, [0.01,0.02,0.03]))
data.price = data.price*data.card.map(d).fillna(0.04)


问:
Why can't I exclude dependent columns from `GROUP BY` when I aggregate by a key?
If I have the following tables (as an example using PostgreSQL, but could be any other relational database), where car has two keys (id and vin):

```<code>create table car (
  id int primary key not null,
  color varchar(10),
  brand varchar(10),
  vin char(17) unique not null
);

create table appraisal (
  id int primary key not null,
  recorded date not null,
  car_id int references car (id),
  car_vin char(17) references car (vin),
  price int
);
</code>```

I can successfully include c.color and c.brand in the select list without aggregating them, since they depend on c.id:

```<code>select
  c.id, c.color, c.brand,
  min(price) as min_appraisal,
  max(price) as max_appraisal
from car c
left join appraisal a on a.car_id = c.id
group by c.id; -- c.color, c.brand are not needed here
</code>```

However, the following query fails since it doesn't allow me to include c.color and c.brand in the select list, even though it does depend on c.vin (that is a key) of the table.

```<code>select
  c.vin, c.color, c.brand,
  min(price) as min_appraisal,
  max(price) as max_appraisal
from car c
left join appraisal a on a.car_vin = c.vin
group by c.vin; -- Why are c.color, c.brand needed here?
</code>```

Error: ERROR: column "c.color" must appear in the GROUP BY clause or be used in an aggregate function
  Position: 18

Example in DB Fiddle.

答:
Because only the PK covers all columns of an underlying table in the GROUP BY clause. Hence your first query works. A UNIQUE constraint does not.

The combination of a non-deferrable UNIQUE and a NOT NULL constraint would also qualify. But that's not implemented - as well as some other functional dependencies known to the SQL standard. Peter Eisentraut, the principal author of the feature, had more in mind, but it was determined at the time that the demand is low and associated costs might be high. See the discussion about the feature on pgsql-hackers.

The manual:

When GROUP BY is present, or any aggregate functions are present, it
  is not valid for the SELECT list expressions to refer to ungrouped
  columns except within aggregate functions or when the ungrouped column
  is functionally dependent on the grouped columns, since there would
  otherwise be more than one possible value to return for an ungrouped
  column. A functional dependency exists if the grouped columns (or a
  subset thereof) are the primary key of the table containing the
  ungrouped column.

And more explicitly:

PostgreSQL recognizes functional dependency (allowing columns to be
  omitted from GROUP BY) only when a table's primary key is included in
  the GROUP BY list. The SQL standard specifies additional conditions
  that should be recognized.

Since c.vin is UNIQUE NOT NULL, you can fix your second query by using the PK column instead:

```<code>...
group by c.id;
</code>```

Aside, while referential integrity is enforced and the whole table is queried, both of the given queries can be substantially cheaper: aggregate rows in appraisal before the join. This removes the need to GROUP BY in the outer SELECT a priori. Like:

```<code>SELECT c.vin, c.color, c.brand
     , a.min_appraisal
     , a.max_appraisal
FROM   car c
LEFT   JOIN (
   SELECT car_vin
        , min(price) AS min_appraisal
        , max(price) AS max_appraisal
   FROM   appraisal
   GROUP  BY car_vin
   ) a ON a.car_vin = c.vin;
</code>```

See:

Multiple array_agg() calls in a single query

Related:

SQL statement working in MySQL not working in Postgresql - Sum & group_by rails 3

PostgreSQL - GROUP BY clause

Body:
If I have the following tables (as an example using PostgreSQL, but could be any other relational database), where car has two keys (id and vin):

create table car (
  id int primary key not null,
  color varchar(10),
  brand varchar(10),
  vin char(17) unique not null
);

create table appraisal (
  id int primary key not null,
  recorded date not null,
  car_id int references car (id),
  car_vin char(17) references car (vin),
  price int
);

I can successfully include c.color and c.brand in the select list without aggregating them, since they depend on c.id:

select
  c.id, c.color, c.brand,
  min(price) as min_appraisal,
  max(price) as max_appraisal
from car c
left join appraisal a on a.car_id = c.id
group by c.id; -- c.color, c.brand are not needed here

However, the following query fails since it doesn't allow me to include c.color and c.brand in the select list, even though it does depend on c.vin (that is a key) of the table.

select
  c.vin, c.color, c.brand,
  min(price) as min_appraisal,
  max(price) as max_appraisal
from car c
left join appraisal a on a.car_vin = c.vin
group by c.vin; -- Why are c.color, c.brand needed here?

Error: ERROR: column "c.color" must appear in the GROUP BY clause or be used in an aggregate function
  Position: 18

Example in DB Fiddle.

Body:
Because only the PK covers all columns of an underlying table in the GROUP BY clause. Hence your first query works. A UNIQUE constraint does not.

The combination of a non-deferrable UNIQUE and a NOT NULL constraint would also qualify. But that's not implemented - as well as some other functional dependencies known to the SQL standard. Peter Eisentraut, the principal author of the feature, had more in mind, but it was determined at the time that the demand is low and associated costs might be high. See the discussion about the feature on pgsql-hackers.

The manual:

When GROUP BY is present, or any aggregate functions are present, it
  is not valid for the SELECT list expressions to refer to ungrouped
  columns except within aggregate functions or when the ungrouped column
  is functionally dependent on the grouped columns, since there would
  otherwise be more than one possible value to return for an ungrouped
  column. A functional dependency exists if the grouped columns (or a
  subset thereof) are the primary key of the table containing the
  ungrouped column.

And more explicitly:

PostgreSQL recognizes functional dependency (allowing columns to be
  omitted from GROUP BY) only when a table's primary key is included in
  the GROUP BY list. The SQL standard specifies additional conditions
  that should be recognized.

Since c.vin is UNIQUE NOT NULL, you can fix your second query by using the PK column instead:

...
group by c.id;

Aside, while referential integrity is enforced and the whole table is queried, both of the given queries can be substantially cheaper: aggregate rows in appraisal before the join. This removes the need to GROUP BY in the outer SELECT a priori. Like:

SELECT c.vin, c.color, c.brand
     , a.min_appraisal
     , a.max_appraisal
FROM   car c
LEFT   JOIN (
   SELECT car_vin
        , min(price) AS min_appraisal
        , max(price) AS max_appraisal
   FROM   appraisal
   GROUP  BY car_vin
   ) a ON a.car_vin = c.vin;

See:

Multiple array_agg() calls in a single query

Related:

SQL statement working in MySQL not working in Postgresql - Sum & group_by rails 3

PostgreSQL - GROUP BY clause