问:
Implementing multiple line code in Python
So I've been trying to recreate some basic Python programs using Python. For example, using Python, I tell the user to input some code. That code goes through a series of tests to, so far, examine what function you want (I.e 'print'), and what you want to do with that function (in this case, printing what's in the quotes and parentheses). I also coded my program so that it can be easily added to and more functions can be added to the 'dictionary' my program determines your wanted function by. I'm trying to add code to upgrade my program from only accepting a single line of code to using this:

```<code>line_number=10
for number in range(1,line_number+1):
    inp=input(f"    Line {number}: ")
</code>```

So far my program is this, and it's still in development:

```<code>def tutorial():
    print("Python Tutorial:\nType your program:")
tutorial()
def program():
    textbox=input()
    print("--------------")
    command=None #I put four different command variables for situations like this for example: print(len(pow(3,4)))
    command2=None
    command3=None
    command4=None
    letter_start=0
    letter_end=0
    command_end=0
    textbox_input=None
    print_type=1 #1 = string: 2 = variable

    #def defining_variable(string):

    #This system is like a dictionary and is very useful when adding new functions besides print.
    #The first "if" statement tests whether the function you want starts with P. This applies for the Print function.
    #If you wanted to use a function like "def", you could add a section for words that start with 'd', then 'de', then 'def'.

    if textbox.startswith('p'):
        if textbox.startswith("pr"):
            if textbox.startswith("print("):
                command=print #You can change what command is used
                if print_type == 1:
                    letter_start=7 #"letter_start" is the variable that holds the position of the first letter (not including parentheses "" or brackets())
                    command_end=5
                elif print_type == 2:
                    letter_start=6
                    command_end=5
            else:
                print("Only Print")
                program()
        else:
            print("Only Print")
            program()
    else:
        print("Only Print")
        program()

    if textbox.startswith('(', command_end):
        if textbox.startswith('("', command_end):
            if textbox.endswith(')'):
                if textbox.endswith('")'):
                    print_type=1
                    letter_end=textbox.index(')')-1
                else:
                    print(f"-->{textbox}<--: Missing quotes")
            else:
                print(f"-->{textbox}<--: Missing parenthesis") ;
        elif textbox.endswith(')'):
            if textbox.endswith('")'):
                print(f"-->{textbox}<--: Missing quotes")
            else:
                print_type=2
                letter_end=textbox.index(')')

        else:
            print(f"-->{textbox}<--: Missing parenthesis")

    else:
        print(f"-->{textbox}<--: Missing parenthesis")

    textbox_input = textbox[letter_start:letter_end]

    try:
        command(textbox_input)
        print("--------------")
        program()
    except:
        print("ERROR")
program()
</code>```

I tried creating the original Python error messages as well to inform the reader of their mistake. This program was intended as a tutorial for Python beginners. Thanks for any help!

答:
To allow the user to input multiple lines you can do something like this:

```<code>commands = []
while True:
  line = input()
  if line:
     commands.append(line)
  else:   #if the line is empty finish inputting commands
     break
</code>```

then your main program should execute command after command, so you can do

```<code>for command in commands:
    execute_command(command)
</code>```

Body:
So I've been trying to recreate some basic Python programs using Python. For example, using Python, I tell the user to input some code. That code goes through a series of tests to, so far, examine what function you want (I.e 'print'), and what you want to do with that function (in this case, printing what's in the quotes and parentheses). I also coded my program so that it can be easily added to and more functions can be added to the 'dictionary' my program determines your wanted function by. I'm trying to add code to upgrade my program from only accepting a single line of code to using this:

line_number=10
for number in range(1,line_number+1):
    inp=input(f"    Line {number}: ")

So far my program is this, and it's still in development:

def tutorial():
    print("Python Tutorial:\nType your program:")
tutorial()
def program():
    textbox=input()
    print("--------------")
    command=None #I put four different command variables for situations like this for example: print(len(pow(3,4)))
    command2=None
    command3=None
    command4=None
    letter_start=0
    letter_end=0
    command_end=0
    textbox_input=None
    print_type=1 #1 = string: 2 = variable

    #def defining_variable(string):

    #This system is like a dictionary and is very useful when adding new functions besides print.
    #The first "if" statement tests whether the function you want starts with P. This applies for the Print function.
    #If you wanted to use a function like "def", you could add a section for words that start with 'd', then 'de', then 'def'.

    if textbox.startswith('p'):
        if textbox.startswith("pr"):
            if textbox.startswith("print("):
                command=print #You can change what command is used
                if print_type == 1:
                    letter_start=7 #"letter_start" is the variable that holds the position of the first letter (not including parentheses "" or brackets())
                    command_end=5
                elif print_type == 2:
                    letter_start=6
                    command_end=5
            else:
                print("Only Print")
                program()
        else:
            print("Only Print")
            program()
    else:
        print("Only Print")
        program()

    if textbox.startswith('(', command_end):
        if textbox.startswith('("', command_end):
            if textbox.endswith(')'):
                if textbox.endswith('")'):
                    print_type=1
                    letter_end=textbox.index(')')-1
                else:
                    print(f"-->{textbox}<--: Missing quotes")
            else:
                print(f"-->{textbox}<--: Missing parenthesis") ;
        elif textbox.endswith(')'):
            if textbox.endswith('")'):
                print(f"-->{textbox}<--: Missing quotes")
            else:
                print_type=2
                letter_end=textbox.index(')')

        else:
            print(f"-->{textbox}<--: Missing parenthesis")

    else:
        print(f"-->{textbox}<--: Missing parenthesis")

    textbox_input = textbox[letter_start:letter_end]

    try:
        command(textbox_input)
        print("--------------")
        program()
    except:
        print("ERROR")
program()

I tried creating the original Python error messages as well to inform the reader of their mistake. This program was intended as a tutorial for Python beginners. Thanks for any help!

Body:
To allow the user to input multiple lines you can do something like this:

commands = []
while True:
  line = input()
  if line:
     commands.append(line)
  else:   #if the line is empty finish inputting commands
     break

then your main program should execute command after command, so you can do

for command in commands:
    execute_command(command)


来源: stackexchange

问:
What is "->" operator called and purpose does it serve?
I'm looking at C-based Solana Smart Contracts and I see -> operator in the code.  How do I search for this as I don't even know what to call it (I have tried with no results)?

```<code>/**
 * @brief C-based Helloworld BPF program
 */
#include <solana_sdk.h>

uint64_t helloworld(SolParameters *params) {

  if (params->ka_num < 1) {
    sol_log("Greeted account not included in the instruction");
    return ERROR_NOT_ENOUGH_ACCOUNT_KEYS;
  }

  // Get the account to say hello to
  SolAccountInfo *greeted_account = &params->ka[0];

}

</code>```

答:
the -> operator is related to the . operator.

The . operator expects a variable with struct or union type on the left and the name of a member of that struct or union on the right.

The -> does the same thing, except that the left operand is a pointer to a struct or union.

That means that this:

```<code>params->ka_num
</code>```

Is an equivalent and cleaner way of writing this:

```<code>(*params).ka_num
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm looking at C-based Solana Smart Contracts and I see -> operator in the code.  How do I search for this as I don't even know what to call it (I have tried with no results)?

/**
 * @brief C-based Helloworld BPF program
 */
#include <solana_sdk.h>

uint64_t helloworld(SolParameters *params) {

  if (params->ka_num < 1) {
    sol_log("Greeted account not included in the instruction");
    return ERROR_NOT_ENOUGH_ACCOUNT_KEYS;
  }

  // Get the account to say hello to
  SolAccountInfo *greeted_account = &params->ka[0];

}

Body:
the -> operator is related to the . operator.

The . operator expects a variable with struct or union type on the left and the name of a member of that struct or union on the right.

The -> does the same thing, except that the left operand is a pointer to a struct or union.

That means that this:

params->ka_num

Is an equivalent and cleaner way of writing this:

(*params).ka_num


问:
Replace a parent class with another class without keeping the old parent
What I have in an external library:

# external package content

class Foo:

    def func(): ...

class Bar(Foo):

    def func():
        super().func()
```
<p>What I need in my code:</p>
<pre class="lang-py prettyprint-override"><code>from external_library import Bar

class MyOwnCustomFoo:

    def func(): ...

# Do some magic here to replace a parent class with another class without keeping the old parent

# Class name can be not 'Bar', but the class must have all 'Bar' attributes
class Bar(MyOwnCustomFoo):

    def func():
        super().func()
</code>```

Goals I need to achieve:

I must have all Bar methods without copy/pasting them.

Bar must inherit from my own class, not from another one.

答:
You could assign the methods from the external library class to your own class, mimicking inheritance (AFAIK this is called monkey-patching):

from external_library import Bar as _Bar

class Bar(MyOwnCustomFoo):
    func = _Bar.func
    ...
```

Body:
What I have in an external library:

# external package content

class Foo:

    def func(): ...

class Bar(Foo):

    def func():
        super().func()

What I need in my code:

from external_library import Bar

class MyOwnCustomFoo:

    def func(): ...

# Do some magic here to replace a parent class with another class without keeping the old parent

# Class name can be not 'Bar', but the class must have all 'Bar' attributes
class Bar(MyOwnCustomFoo):

    def func():
        super().func()

Goals I need to achieve:

I must have all Bar methods without copy/pasting them.

Bar must inherit from my own class, not from another one.


问:
Rmarkdown: Cannot insert image with knitr::include_graphics after R updated
I'm trying to render and old rmarkdown file after I've updated R and RStudio, and all packages, but I'm getting:

```<code>Error: pandoc document conversion failed with error 99
</code>```

However, the path is correct. I've rendered to HTML yesterday and everything worked fine.

```<code>```{r, echo=FALSE, fig.cap="", out.width = '50%', fig.align='center'}
knitr::include_graphics("/img/posts/que-es-un-api/mastercard-blockchain-api.jpg")
```
</code>```

It says the path to the image is wrong, but hope you can see from
  image path is right.

```<code>"C:/PROGRA~1/Pandoc/pandoc" +RTS -K512m -RTS que-es-un-api.utf8.md --to html4 --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash+smart --output que-es-un-api.html --email-obfuscation none --self-contained --standalone --section-divs --template "C:\Users\OGONZALES\Documents\R\win-library\3.6\rmarkdown\rmd\h\default.html" --no-highlight --variable highlightjs=1 --variable "theme:bootstrap" --include-in-header "C:\Users\OGONZA~1\AppData\Local\Temp\RtmpSsSNeA\rmarkdown-str1340bc36ef.html" --mathjax --variable "mathjax-url:https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
File /img/posts/que-es-un-api/mastercard-blockchain-api.jpg not found in resource path
Error: pandoc document conversion failed with error 99
Execution halted
</code>```

I've even tried to reinstall Pandoc with:

```<code># installing/loading the package:
if(!require(installr)) { install.packages("installr"); require(installr)} #load / install+load installr

# Installing pandoc
install.pandoc()
</code>```

sessionInfo:

```<code>R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] compiler_3.6.1  htmltools_0.3.6 tools_3.6.1     yaml_2.2.0      Rcpp_1.0.2
 [6] rmarkdown_1.14  knitr_1.24      xfun_0.8        digest_0.6.20   evaluate_0.14
</code>```

答:
This issue is discussed here and here which is not a bug per se. The solution which worked for me is to use:

```<code>```{r example, echo = FALSE, out.width='80%', out.height='50%'}
knitr::include_graphics(paste0(getwd(), "/images/example_image.png"))
```
</code>```

If you are working within an Rstudio project, it will help to specify the directory first:

```<code>```{r example, echo = FALSE, out.width='80%', out.height='50%'}
setwd(rprojroot::find_rstudio_root_file())
knitr::include_graphics(paste0(getwd(), "/images/example_image.png"))
```
</code>```

See here and here.

Body:
I'm trying to render and old rmarkdown file after I've updated R and RStudio, and all packages, but I'm getting:

Error: pandoc document conversion failed with error 99

However, the path is correct. I've rendered to HTML yesterday and everything worked fine.

```{r, echo=FALSE, fig.cap="", out.width = '50%', fig.align='center'}
knitr::include_graphics("/img/posts/que-es-un-api/mastercard-blockchain-api.jpg")
```

It says the path to the image is wrong, but hope you can see from
  image path is right.

"C:/PROGRA~1/Pandoc/pandoc" +RTS -K512m -RTS que-es-un-api.utf8.md --to html4 --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash+smart --output que-es-un-api.html --email-obfuscation none --self-contained --standalone --section-divs --template "C:\Users\OGONZALES\Documents\R\win-library\3.6\rmarkdown\rmd\h\default.html" --no-highlight --variable highlightjs=1 --variable "theme:bootstrap" --include-in-header "C:\Users\OGONZA~1\AppData\Local\Temp\RtmpSsSNeA\rmarkdown-str1340bc36ef.html" --mathjax --variable "mathjax-url:https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
File /img/posts/que-es-un-api/mastercard-blockchain-api.jpg not found in resource path
Error: pandoc document conversion failed with error 99
Execution halted

I've even tried to reinstall Pandoc with:

# installing/loading the package:
if(!require(installr)) { install.packages("installr"); require(installr)} #load / install+load installr

# Installing pandoc
install.pandoc()

sessionInfo:

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] compiler_3.6.1  htmltools_0.3.6 tools_3.6.1     yaml_2.2.0      Rcpp_1.0.2
 [6] rmarkdown_1.14  knitr_1.24      xfun_0.8        digest_0.6.20   evaluate_0.14

Body:
This issue is discussed here and here which is not a bug per se. The solution which worked for me is to use:

```{r example, echo = FALSE, out.width='80%', out.height='50%'}
knitr::include_graphics(paste0(getwd(), "/images/example_image.png"))
```

If you are working within an Rstudio project, it will help to specify the directory first:

```{r example, echo = FALSE, out.width='80%', out.height='50%'}
setwd(rprojroot::find_rstudio_root_file())
knitr::include_graphics(paste0(getwd(), "/images/example_image.png"))
```

See here and here.


问:
INSERT INTO database table, from form not working. SQL
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):

"Connected to databaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test' ('name') VALUES ('daniel')' at line 1"

The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?

Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.

HTML

```<code><form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>
</code>```

PHP (insert.php)

```<code><?php
$dbhost  = 'localhost';
$dbname  = 'carbon_db';
$dbuser  = 'username';
$dbpass  = 'password';

$con = mysql_connect($dbhost, $dbuser, $dbpass);

if($con == FALSE)
{
    echo 'Cannot connect to database' . mysql_error();
}
else
{
    echo 'Connected to database';
}

mysql_select_db($dbname, $con);

$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";

if (!mysql_query($sql, $con))
{
    die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>
</code>```

答:
Drop the quotes around the table name or change them to back ticks:

Change:

```<code>$sql="INSERT INTO 'test' ('name') VALUES ('$_POST[namefield]')";
</code>```

To:

```<code>$sql="INSERT INTO test ('name') VALUES ('$_POST[namefield]')";
</code>```

Or

```<code>$sql="INSERT INTO `test` ('name') VALUES ('$_POST[namefield]')";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):

"Connected to databaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test' ('name') VALUES ('daniel')' at line 1"

The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?

Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.

HTML

<form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>

PHP (insert.php)

<?php
$dbhost  = 'localhost';
$dbname  = 'carbon_db';
$dbuser  = 'username';
$dbpass  = 'password';

$con = mysql_connect($dbhost, $dbuser, $dbpass);

if($con == FALSE)
{
    echo 'Cannot connect to database' . mysql_error();
}
else
{
    echo 'Connected to database';
}

mysql_select_db($dbname, $con);

$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";

if (!mysql_query($sql, $con))
{
    die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>

Body:
Drop the quotes around the table name or change them to back ticks:

Change:

$sql="INSERT INTO 'test' ('name') VALUES ('$_POST[namefield]')";

To:

$sql="INSERT INTO test ('name') VALUES ('$_POST[namefield]')";

Or

$sql="INSERT INTO `test` ('name') VALUES ('$_POST[namefield]')";


问:
How do I collapse sections of code in Visual Studio Code for Windows?
How do I fold or collapse sections of code in Visual Studio Code?

Is this feature supported?

答:
This is the latest built-in(default) keyboard shortcuts for folding and unfolding the code

vscode Keyboard shortcut

```<code>Ctrl+Shift+[ Fold (collapse) region
Ctrl+Shift+] Unfold (uncollapse) region
Ctrl+K Ctrl+[ Fold (collapse) all subregions
Ctrl+K Ctrl+] Unfold (uncollapse) all subregions
Ctrl+K Ctrl+0 Fold (collapse) all regions
Ctrl+K Ctrl+J Unfold (uncollapse) all
</code>```

Nb: But in some cases, your vs code extension or user will alter the keyboard binding(shortcut). So best option that Checks like this

view->command palette OR cntrl+shift+p

type "fold" .It will suggest the fold and unfold and there shortcut. You can type that shortcut instead of command-palette

eg:

Fold All

UnFold All

Body:
This is the latest built-in(default) keyboard shortcuts for folding and unfolding the code

vscode Keyboard shortcut

Ctrl+Shift+[ Fold (collapse) region
Ctrl+Shift+] Unfold (uncollapse) region
Ctrl+K Ctrl+[ Fold (collapse) all subregions
Ctrl+K Ctrl+] Unfold (uncollapse) all subregions
Ctrl+K Ctrl+0 Fold (collapse) all regions
Ctrl+K Ctrl+J Unfold (uncollapse) all

Nb: But in some cases, your vs code extension or user will alter the keyboard binding(shortcut). So best option that Checks like this

view->command palette OR cntrl+shift+p

type "fold" .It will suggest the fold and unfold and there shortcut. You can type that shortcut instead of command-palette

eg:

Fold All

UnFold All


问:
Extract fetched data using map method
I am trying to fetching data from newsapi website. It gives me data as array like object format.

Now, my goal is to iterate this data and display my newsItem component. Here is my code below.

```<code>export class News extends Component {
    constructor(){
        super()
        this.state = {
            articles: this.articles
        }
    }
    componentDidMount(){
        fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey=d21fe13361b94006b816f98a7c005003`)
        .then(res =>res.json())
        .then(data => this.setState({articles:data.articles}))
    }
  render() {
    return <div className='container my-3'>
        <h1 className='my-3'>NewsDonkey - Top Headlines</h1>
        <div className="row">
                {this.state.articles.map(element=> console.log(element))}
            <div className="col-md-4">
                <NewsItem/>
            </div>
        </div>
    </div>;
  }
}

export default News;
</code>```

but, browser shows can't read properties of undefined. Here is the error image.

Now, you may say that data may be in object format that's why map method is not working. I tried same coding in JS: articles.map(element=> console.log(element)) it extracted data perfectly. Please help me if you find any error in my coding.

答:
The initial value of state.articles is this.articles which is undefined.

At some point in the future, you'll assign a useful value to that property, but until then you can't treat it like the array it will be in the future but isn't yet.

Test the value and do something different.

e.g.

```<code>(!this.state.articles && <Loading />}
{this.state.articles && this.state.articles.map(element=> console.log(element))}
</code>```

Title: Extract fetched data using map method

Body:
I am trying to fetching data from newsapi website. It gives me data as array like object format.

Now, my goal is to iterate this data and display my newsItem component. Here is my code below.

export class News extends Component {
    constructor(){
        super()
        this.state = {
            articles: this.articles
        }
    }
    componentDidMount(){
        fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey=d21fe13361b94006b816f98a7c005003`)
        .then(res =>res.json())
        .then(data => this.setState({articles:data.articles}))
    }
  render() {
    return

NewsDonkey - Top Headlines

                {this.state.articles.map(element=> console.log(element))}

                <NewsItem/>

;
  }
}

export default News;

but, browser shows can't read properties of undefined. Here is the error image.

Now, you may say that data may be in object format that's why map method is not working. I tried same coding in JS: articles.map(element=> console.log(element)) it extracted data perfectly. Please help me if you find any error in my coding.

Body:
The initial value of state.articles is this.articles which is undefined.

At some point in the future, you'll assign a useful value to that property, but until then you can't treat it like the array it will be in the future but isn't yet.

Test the value and do something different.

e.g.

(!this.state.articles && <Loading />}
{this.state.articles && this.state.articles.map(element=> console.log(element))}


问:
Django retrieve filter value in views.py
I would like to prompt the user a dropdown box with all the values of a specific attribute, and retrieve this value in views.py to use it as function argument (to filter the output of a view function).

Example:

models.py

class User(models.Model):
    name = models.CharField(max_length=30)
    email = models.CharField(max_length=30)
    address = models.CharField(max_length=30)

    def __str__(self):
        return self.name

```
<p><code>views.py</code></p>
<pre class="lang-py prettyprint-override"><code>
def users(request):
    users= User.objects.all()
    context = {'users': users}
    return render(request, 'users.html', context)
</code>```

users.html

{% block content %}

                Name
                E mail
                Address

        {% for i in users%}

                {{i.name}}
                {{i.email}}
                {{i.address}}

        {% endfor %}

{% endblock content%}
```

I would like to display in my html a dropdown with all the User.name values, and when selected use the selected_user value as an argument in views.users() to filter the displayed table.

Any idea on how to proceed ?

答:
In your html add select element and append users data first with
 body empty.

```<code><div>
    <select class="form-control" id="user" name="user">
        {% for i in users %}
            <option value="{{i.id}}">{{i.name}}</option>
        {% endfor %}
    </select>
    <table id="userTable" style="width:100%" class="table table-hover table-sm table-stripped">
        <thead class="thead-dark">
            <tr>
                <th>Name</th>
                <th>E mail</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
</code>```

And in your script call new url using jQuery.ajax() with every .change() event of <select> element to get corresponsing user value with provided userid value and append data to the table. By this way you don't need to refresh the page and get your data with every change event.

```<code><script>
    $('#user').on('change', function() {
        $.ajax({
            url: "/user/" + $(this).val(),
            method: 'GET',
            contentType : 'application/json',
            success: function (data) {
                var tr = '<tr><td>'+ data.name +'</td><td>'+ data.email +'</td><td>'+ data.address +'</td></tr>';
                $('#userTable tbody').append(tr);
            },
            error : function(x) {
                console.log(x);
            }
        });
    });
</script>
</code>```

Then in your urls.py add new url as

```<code>path('user/<str:user_id>/', views.user_data, name='user-data')
</code>```

Add in your views.py

```<code>from django.shortcuts import get_object_or_404
from django.http import JsonResponse

def user_data(request, user_id):
    user = get_object_or_404(GuruUsers, id=user_id)
    user_data = {
        'name' : user.name,
        'email' : user.email,
        'address' : user.address
    }
    return JsonResponse(user_data, status=200)
</code>```

Body:
I would like to prompt the user a dropdown box with all the values of a specific attribute, and retrieve this value in views.py to use it as function argument (to filter the output of a view function).

Example:

models.py

class User(models.Model):
    name = models.CharField(max_length=30)
    email = models.CharField(max_length=30)
    address = models.CharField(max_length=30)

    def __str__(self):
        return self.name

views.py

def users(request):
    users= User.objects.all()
    context = {'users': users}
    return render(request, 'users.html', context)

users.html

{% block content %}

                Name
                E mail
                Address

        {% for i in users%}

                {{i.name}}
                {{i.email}}
                {{i.address}}

        {% endfor %}

{% endblock content%}

I would like to display in my html a dropdown with all the User.name values, and when selected use the selected_user value as an argument in views.users() to filter the displayed table.

Any idea on how to proceed ?

Body:
In your html add select element and append users data first with <table> body empty.

<div>
    <select class="form-control" id="user" name="user">
        {% for i in users %}
            <option value="{{i.id}}">{{i.name}}</option>
        {% endfor %}
    </select>
    <table id="userTable" style="width:100%" class="table table-hover table-sm table-stripped">
        <thead class="thead-dark">
            <tr>
                <th>Name</th>
                <th>E mail</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

And in your script call new url using jQuery.ajax() with every .change() event of <select> element to get corresponsing user value with provided userid value and append data to the table. By this way you don't need to refresh the page and get your data with every change event.

<script>
    $('#user').on('change', function() {
        $.ajax({
            url: "/user/" + $(this).val(),
            method: 'GET',
            contentType : 'application/json',
            success: function (data) {
                var tr = '<tr><td>'+ data.name +'</td><td>'+ data.email +'</td><td>'+ data.address +'</td></tr>';
                $('#userTable tbody').append(tr);
            },
            error : function(x) {
                console.log(x);
            }
        });
    });
</script>

Then in your urls.py add new url as

path('user/<str:user_id>/', views.user_data, name='user-data')

Add in your views.py

from django.shortcuts import get_object_or_404
from django.http import JsonResponse

def user_data(request, user_id):
    user = get_object_or_404(GuruUsers, id=user_id)
    user_data = {
        'name' : user.name,
        'email' : user.email,
        'address' : user.address
    }
    return JsonResponse(user_data, status=200)


问:
How does this while loop exit?
So, how does this code exit the while statement when the thread is started? (Please do not consider indentation)

```<code>class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()
</code>```

** EDIT *

The code that starts the thread:

```<code>def main():

#spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

    queue.join()
</code>```

答:
Your code will only breaks if an exception occurs during the execution of the content of the while True loop.... not the better way to exit from a thread, but it could work.

If you want to exit properly from your thread, try to replace the while True with something like while self.continue_loop:

```<code>class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue
        self.continue_loop = True

    def run(self):
        while self.continue_loop:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()
</code>```

And to start/stop the threads :

```<code>def main():

#spawn a pool of threads, and pass them queue instance
    threads = []
    for i in range(5):
        t = ThreadUrl(queue, out_queue)
        t.setDaemon(True)
        t.start()
        threads.append(t)

    for t in threads:
       t.continue_loop = False
       t.join()

    queue.join()
</code>```

Title: How does this while loop exit?

Body:
So, how does this code exit the while statement when the thread is started? (Please do not consider indentation)

class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()

** EDIT *

The code that starts the thread:

def main():

#spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

    queue.join()

Body:
Your code will only breaks if an exception occurs during the execution of the content of the while True loop.... not the better way to exit from a thread, but it could work.

If you want to exit properly from your thread, try to replace the while True with something like while self.continue_loop:

class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue
        self.continue_loop = True

    def run(self):
        while self.continue_loop:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()

And to start/stop the threads :

def main():

#spawn a pool of threads, and pass them queue instance
    threads = []
    for i in range(5):
        t = ThreadUrl(queue, out_queue)
        t.setDaemon(True)
        t.start()
        threads.append(t)

    for t in threads:
       t.continue_loop = False
       t.join()

    queue.join()


问:
Dynamic variable names in Bash
I am confused about a bash script.

I have the following code:

```<code>function grep_search() {
    magic_way_to_define_magic_variable_$1=`ls | tail -1`
    echo $magic_variable_$1
}
</code>```

I want to be able to create a variable name containing the first argument of the command and bearing the value of e.g. the last line of ls.

So to illustrate what I want:

```<code>$ ls | tail -1
stack-overflow.txt

$ grep_search() open_box
stack-overflow.txt
</code>```

So, how should I define/declare $magic_way_to_define_magic_variable_$1 and how should I call it within the script?

I have tried eval, ${...}, \$${...}, but I am still confused.

答:
While I think declare -n is still the best way to do it there is another way nobody mentioned it, very useful in CI/CD

```<code>function dynamic(){
  export a_$1="bla"
}

dynamic 2
echo $a_2
</code>```

This function will not support spaces so dynamic "2 3" will return an error.

Title: Dynamic variable names in Bash

Body:
I am confused about a bash script.

I have the following code:

function grep_search() {
    magic_way_to_define_magic_variable_$1=`ls | tail -1`
    echo $magic_variable_$1
}

I want to be able to create a variable name containing the first argument of the command and bearing the value of e.g. the last line of ls.

So to illustrate what I want:

$ ls | tail -1
stack-overflow.txt

$ grep_search() open_box
stack-overflow.txt

So, how should I define/declare $magic_way_to_define_magic_variable_$1 and how should I call it within the script?

I have tried eval, ${...}, \$${...}, but I am still confused.

Body:
While I think declare -n is still the best way to do it there is another way nobody mentioned it, very useful in CI/CD

function dynamic(){
  export a_$1="bla"
}

dynamic 2
echo $a_2

This function will not support spaces so dynamic "2 3" will return an error.


问:
How to pass data in flutter on Stateless Widget?
I'm trying to do my school assignment, and have run into difficulty with passing data into Stateless Widgets. I have the following classes:

```<code>    class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Page1(),
    );
  }
}

class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: ElevatedButton(
        onPressed: () {
          Navigator.push(
              context, MaterialPageRoute(builder: (context) => Page2(messageData: messageData)));
        },
        child: Text('Request Chat'),
      )),
    );
  }
}

class Page2 extends StatelessWidget {
  //Navigation
  static Route route(MessageData data) => MaterialPageRoute(
        builder: (context) => Page2(
          messageData: data,
        ),
      );

  const Page2({Key? key, required this.messageData}) : super(key: key);

  final MessageData messageData;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: Theme.of(context).iconTheme,
        centerTitle: false,
),
),
},

@immutable
class MessageData {
  const MessageData(
      {required this.senderName,
      required this.message,
      required this.messageDate,
      required this.dateMessage,
      required this.profilePicture});

  final String senderName;
  final String message;
  final DateTime messageDate;
  final String dateMessage;
  final String profilePicture;
}

</code>```

There is my messageData above that I need to pass.

Basically, I want to be able to Navigate to Page2 but I keep getting an error at Navigator.push() .
Error details: Type' can't be assigned to the parameter type 'MessageData'.

And when there are no arguments on Page2() the error message: The named parameter 'messageData' is required, but there's no corresponding argument.

答: You have to pass data using Constructor. I hope you will get an idea from this link.</p>

Body:
I'm trying to do my school assignment, and have run into difficulty with passing data into Stateless Widgets. I have the following classes:

    class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Page1(),
    );
  }
}

class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: ElevatedButton(
        onPressed: () {
          Navigator.push(
              context, MaterialPageRoute(builder: (context) => Page2(messageData: messageData)));
        },
        child: Text('Request Chat'),
      )),
    );
  }
}

class Page2 extends StatelessWidget {
  //Navigation
  static Route route(MessageData data) => MaterialPageRoute(
        builder: (context) => Page2(
          messageData: data,
        ),
      );

  const Page2({Key? key, required this.messageData}) : super(key: key);

  final MessageData messageData;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: Theme.of(context).iconTheme,
        centerTitle: false,
),
),
},

@immutable
class MessageData {
  const MessageData(
      {required this.senderName,
      required this.message,
      required this.messageDate,
      required this.dateMessage,
      required this.profilePicture});

  final String senderName;
  final String message;
  final DateTime messageDate;
  final String dateMessage;
  final String profilePicture;
}

There is my messageData above that I need to pass.

Basically, I want to be able to Navigate to Page2 but I keep getting an error at Navigator.push() .
Error details: Type' can't be assigned to the parameter type 'MessageData'.

And when there are no arguments on Page2() the error message: The named parameter 'messageData' is required, but there's no corresponding argument.


问:
Can I find by a list of IDs instead the classic findById() in Spring Data JPA?
I am working on a Spring Boot project using Spring Data JPA and I am wondering if exist a nice and elegant solution to the following use case.

Originally I had a service method like this (it works fine):

```<code>@Override
public Page<LogDTO> findAll(Integer logType, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable) throws NotFoundException {

    if(startDate == null) startDate = LocalDateTime.of(1900,1,1,0,0,0);
    if(endDate == null) endDate = LocalDateTime.now();

    Page<EventLog> eventLogs = null;
    if(logType != null) {
        Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);
        logTypeEntity.orElseThrow(  () -> new NotFoundException(String.format("Log type doesn't exists with id: ", Integer.toString(logType))));
        eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);
    } else {
        eventLogs = logRepository.findByTimestampBetween(startDate,endDate,pageable);
    }
    return eventLogs.map(m -> conversionService.convert(m, LogDTO.class));
}
</code>```

As you can see in this old method take this Integer logType input parameter representing the ID of single log type. Then retrieve the related LogType object by:

```<code> Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);
</code>```

and uses this logTypeEntity instance in order to retrieve all the EventLog object related to this specific single retrieve LogType, by this line:

```<code>eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);
</code>```

Now I was refactoring this method in order to try to obtains the logs related to multiple LogType. So I am changing my original service method in this way:

```<code>@Override
public Page<LogDTO> findAll(List<Integer> logTypesList,
                            LocalDateTime startDate,
                            LocalDateTime endDate,
                            Pageable pageable) throws NotFoundException {

    if(startDate == null) startDate = LocalDateTime.of(1900,1,1,0,0,0);
    if(endDate == null) endDate = LocalDateTime.now();

    Page<EventLog> eventLogs = null;

    if(logTypesList != null & logTypesList.size() > 0) {

        Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);

        logTypeEntity.orElseThrow(  () -> new NotFoundException(String.format("Log type doesn't exists with id: ", Integer.toString(logType))));

        eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);

    } else {
        eventLogs = logRepository.findByTimestampBetween(startDate,endDate,pageable);
    }
    return eventLogs.map(m -> conversionService.convert(m, LogDTO.class));
}
</code>```

As you can see my service method now take a List logTypesList parameter instead a single Integer logType). Then in my code I am checking if this list contains element.

Now I am wondering if exist a smart way in Spring Data JPA to replace this line:

```<code>Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);
</code>```

in order to retrieve the collection of the LogType belonging to all the IDs contained into my List logTypesList. I know that I can simply interate on this collection and add the retrieved objects to a result list but I am wondering if I can implement this behavior in a smarter way.

Following a similar doubt related to how to replace in a smart and elegant way this line:

```<code>            eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);
</code>```

Exist a way to pass a collection of LogType objects in order to retrieve all the returned LogEvent objects?

答:
This one (findAllById) should work</p>
```<code>List<T> findAllById(Iterable<ID> var1);
</code>```

Body:
I am working on a Spring Boot project using Spring Data JPA and I am wondering if exist a nice and elegant solution to the following use case.

Originally I had a service method like this (it works fine):

@Override
public Page<LogDTO> findAll(Integer logType, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable) throws NotFoundException {

    if(startDate == null) startDate = LocalDateTime.of(1900,1,1,0,0,0);
    if(endDate == null) endDate = LocalDateTime.now();

    Page<EventLog> eventLogs = null;
    if(logType != null) {
        Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);
        logTypeEntity.orElseThrow(  () -> new NotFoundException(String.format("Log type doesn't exists with id: ", Integer.toString(logType))));
        eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);
    } else {
        eventLogs = logRepository.findByTimestampBetween(startDate,endDate,pageable);
    }
    return eventLogs.map(m -> conversionService.convert(m, LogDTO.class));
}

As you can see in this old method take this Integer logType input parameter representing the ID of single log type. Then retrieve the related LogType object by:

 Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);

and uses this logTypeEntity instance in order to retrieve all the EventLog object related to this specific single retrieve LogType, by this line:

eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);

Now I was refactoring this method in order to try to obtains the logs related to multiple LogType. So I am changing my original service method in this way:

@Override
public Page<LogDTO> findAll(List<Integer> logTypesList,
                            LocalDateTime startDate,
                            LocalDateTime endDate,
                            Pageable pageable) throws NotFoundException {

    if(startDate == null) startDate = LocalDateTime.of(1900,1,1,0,0,0);
    if(endDate == null) endDate = LocalDateTime.now();

    Page<EventLog> eventLogs = null;

    if(logTypesList != null & logTypesList.size() > 0) {

        Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);

        logTypeEntity.orElseThrow(  () -> new NotFoundException(String.format("Log type doesn't exists with id: ", Integer.toString(logType))));

        eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);

    } else {
        eventLogs = logRepository.findByTimestampBetween(startDate,endDate,pageable);
    }
    return eventLogs.map(m -> conversionService.convert(m, LogDTO.class));
}

As you can see my service method now take a List logTypesList parameter instead a single Integer logType). Then in my code I am checking if this list contains element.

Now I am wondering if exist a smart way in Spring Data JPA to replace this line:

Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);

in order to retrieve the collection of the LogType belonging to all the IDs contained into my List logTypesList. I know that I can simply interate on this collection and add the retrieved objects to a result list but I am wondering if I can implement this behavior in a smarter way.

Following a similar doubt related to how to replace in a smart and elegant way this line:

            eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);

Exist a way to pass a collection of LogType objects in order to retrieve all the returned LogEvent objects?

Body:
This one (findAllById) should work

List<T> findAllById(Iterable<ID> var1);


问:
How to list AWS RDS instances that are stopped
I'm trying to use the AWS CLI to list all the AWS RDS instances that I have that are in a Stopped status.

It's possible with EC2 with aws ec2 describe-instances and adding a filter --filters  "Name=instance-state-name,Values=stopped".

However, with aws rds describe-db-instances, I do not find an equivalent. There is a --filter option, but only had the following options as filters: db-cluster-id, db-instance-id, dbi-resource-id, domain, engine.

So what AWS CLI command can I use to list all the RDS instances that are currently Stopped (Status=stopped)?

答:
You can do something like this:

```<code>aws rds describe-db-instances --query 'DBInstances[].DBInstanceStatus[]'
</code>```

output:

```<code>[
   "available"
]
</code>```

Body:
You can do something like this:

aws rds describe-db-instances --query 'DBInstances[].DBInstanceStatus[]'

output:

[
   "available"
]


答:
You can pass arguments to widgets just like you pass to Flutter's widgets:

///Creating Page2 instances
Page2(text: 'text');
Page2.otherConstructor('text');

///This is how you pass values to widgets
class Page2 extends StatelessWidget {
  //Pass `this.field` to the constructor so that you are asking for the field you created.
  const Page2({Key? key, required this.text}) : super(key: key);
  const Page2.otherConstructor(this.text);

  final String text;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text(text),
    );
  }
}

```

And in case it's a StatefulWidget in the State you can access the values with widget.field.

Title: How to pass data in flutter on Stateless Widget?

Body:
You can pass arguments to widgets just like you pass to Flutter's widgets:

///Creating Page2 instances
Page2(text: 'text');
Page2.otherConstructor('text');

///This is how you pass values to widgets
class Page2 extends StatelessWidget {
  //Pass `this.field` to the constructor so that you are asking for the field you created.
  const Page2({Key? key, required this.text}) : super(key: key);
  const Page2.otherConstructor(this.text);

  final String text;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text(text),
    );
  }
}

And in case it's a StatefulWidget in the State you can access the values with widget.field.


问:
How can I iterate over a list of dicts inside a pandas dataframe?
I have a pandas DataFrame looking something like this:

```<code>    | ID       | col1 | col2 |     col3    |
    | -------- | ---- | ---- | ------------|
    | ID1      | val1 | val1 | [{..},{..}] |
    | ID2      | val2 | val2 | [{..},{..}] |
</code>```

the rows of col3 consist of a list of dicts looking something like this:

```<code>    [{'key1':'3', 'key2':'8', 'key3':'9'},
     {'key1':'3', 'key2':'8', 'key3':'7'},
     {'key1':'2', 'key2':'1', 'key3':'9'}]
</code>```

The keys within all dicts are the 'same' and I'm trying to add a new column "col4" to my df with a count of e.g. how often the number 8 as value apears in each dict with key2 as key, similar like:

```<code>    | ID       | col1 | col2 |     col3    | col4 |
    | -------- | ---- | ---- | ------------| ---- |
    | ID1      | val1 | val1 | [{..},{..}] |  2   |
    | ID2      | val2 | val2 | [{..},{..}] |  5   |
</code>```

I don't have any idea how to even start solving this problem, how can I iterate over a list of dicts inside a pandas dataframe?

答:
Try using a combination of explode, pd.json_normalize, unstack, and value_counts:

```<code>val = '8'
df['col4'] = df['a'].explode().pipe(lambda x: pd.json_normalize(x).set_index(x.index)).groupby(level=0).apply(lambda g: g.unstack().value_counts()[val])
</code>```

But first you might need to convert the data in your column to actually dicts/lists, because they might just be strings that look look dicts/lists:

```<code>import ast
df['col4'] = df['col4'].apply(ast.literal_eval)
</code>```

Body:
I have a pandas DataFrame looking something like this:

    | ID       | col1 | col2 |     col3    |
    | -------- | ---- | ---- | ------------|
    | ID1      | val1 | val1 | [{..},{..}] |
    | ID2      | val2 | val2 | [{..},{..}] |

the rows of col3 consist of a list of dicts looking something like this:

    [{'key1':'3', 'key2':'8', 'key3':'9'},
     {'key1':'3', 'key2':'8', 'key3':'7'},
     {'key1':'2', 'key2':'1', 'key3':'9'}]

The keys within all dicts are the 'same' and I'm trying to add a new column "col4" to my df with a count of e.g. how often the number 8 as value apears in each dict with key2 as key, similar like:

    | ID       | col1 | col2 |     col3    | col4 |
    | -------- | ---- | ---- | ------------| ---- |
    | ID1      | val1 | val1 | [{..},{..}] |  2   |
    | ID2      | val2 | val2 | [{..},{..}] |  5   |

I don't have any idea how to even start solving this problem, how can I iterate over a list of dicts inside a pandas dataframe?

Body:
Try using a combination of explode, pd.json_normalize, unstack, and value_counts:

val = '8'
df['col4'] = df['a'].explode().pipe(lambda x: pd.json_normalize(x).set_index(x.index)).groupby(level=0).apply(lambda g: g.unstack().value_counts()[val])

But first you might need to convert the data in your column to actually dicts/lists, because they might just be strings that look look dicts/lists:

import ast
df['col4'] = df['col4'].apply(ast.literal_eval)


问:
Firebase: Error .getDownloadURL is not a function
I want to get the link to the uploaded image with .getDownloadURL() but I end up with an error:

Uncaught (in promise) TypeError: uploadTask.snapshot.ref.getDownloadURL is not a function

If I remove .getDownloadURL() and .ref then everything works and I end up with:

```<code>Download URL Object { bytesTransferred: 120745, ... ref: {…} }
</code>```

Author source code:

```<code>import {upload} from './upload'
import { initializeApp } from "firebase/app";
import 'firebase/storage'
import { getStorage, ref, uploadBytesResumable } from "firebase/storage"
// Your web app's Firebase configuration

const firebaseConfig = {
  *code Firebase*
}
const app = initializeApp(firebaseConfig)
const storage = getStorage(app)

upload('#file', {
    multi: true,
    accept: ['.png', '.jpg', '.jpeg', '.gif'],
    onUpload(files, blocks) {
        files.forEach((file, index) => {
            const storageRef = ref(storage, `images/${file.name}`);
            const uploadTask = uploadBytesResumable(storageRef, file);

            uploadTask.on('state_changed', snapshot => {
                const percentage = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(0) + '%'
                const block = blocks[index].querySelector('.preview-info-progress')
                block.textContent = percentage
                block.style.width = percentage
            }, error => {
                console.log(error)
            }, () => {
                uploadTask.snapshot.ref.getDownloadURL().then(url => {  // << problem
                    console.log('Download URL', url)
                })
            })
        })
    }
})
</code>```

Thank you!

答:
You're mixing the older, namespace syntax of SDK versions 8 and before with the newer, modular syntax of SDK versions 9 and above. That won't work, so you should pick one syntax/version and stick to that.

The modular syntax for getting the download URL is:

```<code>getDownloadURL(storageRef).then(url => {
    console.log('Download URL', url)
})
</code>```

Unrelated to that, I usually find the code easier to read when I use the fact that the upload task is a promise itself. With that, the code becomes:

```<code>files.forEach((file, index) => {
    const storageRef = ref(storage, `images/${file.name}`);
    const uploadTask = uploadBytesResumable(storageRef, file);

    uploadTask.on('state_changed', snapshot => {
        const percentage = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(0) + '%'
        const block = blocks[index].querySelector('.preview-info-progress')
        block.textContent = percentage
        block.style.width = percentage
    })
    uploadTask.then(() => {
        getDownloadURL(ref).then(url => {
            console.log('Download URL', url)
        })
    })
})
</code>```

And with async/await that becomes:

```<code>files.forEach((file, index) => async {
    const storageRef = ref(storage, `images/${file.name}`);
    const uploadTask = uploadBytesResumable(storageRef, file);

    uploadTask.on('state_changed', snapshot => {
        const percentage = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(0) + '%'
        const block = blocks[index].querySelector('.preview-info-progress')
        block.textContent = percentage
        block.style.width = percentage
    })

    await uploadTask;
    const url = await getDownloadURL(ref)
    console.log('Download URL', url)
})
</code>```

Body:
I want to get the link to the uploaded image with .getDownloadURL() but I end up with an error:

Uncaught (in promise) TypeError: uploadTask.snapshot.ref.getDownloadURL is not a function

If I remove .getDownloadURL() and .ref then everything works and I end up with:

Download URL Object { bytesTransferred: 120745, ... ref: {…} }

Author source code:

import {upload} from './upload'
import { initializeApp } from "firebase/app";
import 'firebase/storage'
import { getStorage, ref, uploadBytesResumable } from "firebase/storage"
// Your web app's Firebase configuration

const firebaseConfig = {
  *code Firebase*
}
const app = initializeApp(firebaseConfig)
const storage = getStorage(app)

upload('#file', {
    multi: true,
    accept: ['.png', '.jpg', '.jpeg', '.gif'],
    onUpload(files, blocks) {
        files.forEach((file, index) => {
            const storageRef = ref(storage, `images/${file.name}`);
            const uploadTask = uploadBytesResumable(storageRef, file);

            uploadTask.on('state_changed', snapshot => {
                const percentage = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(0) + '%'
                const block = blocks[index].querySelector('.preview-info-progress')
                block.textContent = percentage
                block.style.width = percentage
            }, error => {
                console.log(error)
            }, () => {
                uploadTask.snapshot.ref.getDownloadURL().then(url => {  // << problem
                    console.log('Download URL', url)
                })
            })
        })
    }
})

Thank you!

Body:
You're mixing the older, namespace syntax of SDK versions 8 and before with the newer, modular syntax of SDK versions 9 and above. That won't work, so you should pick one syntax/version and stick to that.

The modular syntax for getting the download URL is:

getDownloadURL(storageRef).then(url => {
    console.log('Download URL', url)
})

Unrelated to that, I usually find the code easier to read when I use the fact that the upload task is a promise itself. With that, the code becomes:

files.forEach((file, index) => {
    const storageRef = ref(storage, `images/${file.name}`);
    const uploadTask = uploadBytesResumable(storageRef, file);

    uploadTask.on('state_changed', snapshot => {
        const percentage = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(0) + '%'
        const block = blocks[index].querySelector('.preview-info-progress')
        block.textContent = percentage
        block.style.width = percentage
    })
    uploadTask.then(() => {
        getDownloadURL(ref).then(url => {
            console.log('Download URL', url)
        })
    })
})

And with async/await that becomes:

files.forEach((file, index) => async {
    const storageRef = ref(storage, `images/${file.name}`);
    const uploadTask = uploadBytesResumable(storageRef, file);

    uploadTask.on('state_changed', snapshot => {
        const percentage = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(0) + '%'
        const block = blocks[index].querySelector('.preview-info-progress')
        block.textContent = percentage
        block.style.width = percentage
    })

    await uploadTask;
    const url = await getDownloadURL(ref)
    console.log('Download URL', url)
})


Title: lubridate: Finding weeks within months

Body:
I want to find weeks within months (separate numbering of weeks within months) using lubridate R package. My minimum working example is below:

library(tidyverse)
library(lubridate)
dt1 <-
  tibble(
    Date  = seq(from = ymd("2021-01-01"), to = ymd("2021-12-31"), by = '1 day')
  , Month = month(Date)
    )

dt2 <-
  dt1 %>%
  group_by(Month) %>%
  mutate(Week = week(Date))

dt2 %>%
  print(n = 40)

# A tibble: 365 x 3
# Groups:   Month [12]
   Date       Month  Week
   <date>     <dbl> <dbl>
 1 2021-01-01     1     1
 2 2021-01-02     1     1
 3 2021-01-03     1     1
 4 2021-01-04     1     1
 5 2021-01-05     1     1
 6 2021-01-06     1     1
 7 2021-01-07     1     1
 8 2021-01-08     1     2
 9 2021-01-09     1     2
10 2021-01-10     1     2
11 2021-01-11     1     2
12 2021-01-12     1     2
13 2021-01-13     1     2
14 2021-01-14     1     2
15 2021-01-15     1     3
16 2021-01-16     1     3
17 2021-01-17     1     3
18 2021-01-18     1     3
19 2021-01-19     1     3
20 2021-01-20     1     3
21 2021-01-21     1     3
22 2021-01-22     1     4
23 2021-01-23     1     4
24 2021-01-24     1     4
25 2021-01-25     1     4
26 2021-01-26     1     4
27 2021-01-27     1     4
28 2021-01-28     1     4
29 2021-01-29     1     5
30 2021-01-30     1     5
31 2021-01-31     1     5
32 2021-02-01     2     5
33 2021-02-02     2     5
34 2021-02-03     2     5
35 2021-02-04     2     5
36 2021-02-05     2     6
37 2021-02-06     2     6
38 2021-02-07     2     6
39 2021-02-08     2     6
40 2021-02-09     2     6
# ... with 325 more rows

Wondering what am I missing here. For row number 31 in output (31 2021-01-31     1     5), the value in Week column should be 1. Any lead to get the desired output.

Body:
It's not completely clear how you are defining a week. If Week 1 starts on the first day of a month, then you can do:

dt2 <- dt1 %>% mutate(Week = 1L + ((day(Date) - 1L) %/% 7L))
dt2 %>% slice(21:40) %>% print(n = 20L)

# A tibble: 20 × 3
   Date       Month  Week
   <date>     <dbl> <int>
 1 2021-01-21     1     3
 2 2021-01-22     1     4
 3 2021-01-23     1     4
 4 2021-01-24     1     4
 5 2021-01-25     1     4
 6 2021-01-26     1     4
 7 2021-01-27     1     4
 8 2021-01-28     1     4
 9 2021-01-29     1     5
10 2021-01-30     1     5
11 2021-01-31     1     5
12 2021-02-01     2     1
13 2021-02-02     2     1
14 2021-02-03     2     1
15 2021-02-04     2     1
16 2021-02-05     2     1
17 2021-02-06     2     1
18 2021-02-07     2     1
19 2021-02-08     2     2
20 2021-02-09     2     2

With base R, you could simply do:

Week <- 1L + ((as.POSIXlt(Date)$mday - 1L) %/% 7L)


问:
Partial view in NET 6
i am lost with NET6.
I created this partial view _MenuNav.cshtml :

```<code>@model IEnumerable<CateringMilano.Models.Menu>

@foreach (var item in Model)
{
    <div>
        <a alt="@item.MenuTitle)">@item.MenuName</a>
        <b>@item.MenuTitle</b>
    </div>
}
</code>```

and the cod in my controller is :

```<code>// GET: /Menus/_MenuNav/
        public ActionResult _MenuNav(string menuPosition)
        {
            // Get my db
            var model = _context.Menu.Include(m => m.ChildMenuSub) as IQueryable<Menu>;
            model = model.Where(p => p.MenuPosition == menuPosition);
// Send your collection of Mreations to the View
 return PartialView(model);
}
</code>```

and in the last project with net 4 i use to write the following code in the principal view in order to call my partial view :

```<code>@Html.Action("_MenuNav", "Menus", new { menuPosition = "Menu" })
</code>```

but it looks like it does not work anymore this with NET6

Do you know how to rewrite my code in order to get the same result?

答:
you must be mixing view components with partial views. Partial view were always used like this

```<code><div id="partialName">
<partial name="_PartialName" />
</div>
</code>```

with model

```<code><partial name="_PartialName" model="Model.MyInfo" />
</code>```

or for async

```<code><div id="partialName">
@await Html.PartialAsync("_PartialName")
</div>
</code>```

and the most popular way to update parital view is using ajax

And you can check my answer about viewcomponents here
https://stackoverflow.com/a/69698058/11392290

Title: Partial view in NET 6

Body:
i am lost with NET6.
I created this partial view _MenuNav.cshtml :

@model IEnumerable<CateringMilano.Models.Menu>

@foreach (var item in Model)
{

        @item.MenuName
        @item.MenuTitle

}

and the cod in my controller is :

// GET: /Menus/_MenuNav/
        public ActionResult _MenuNav(string menuPosition)
        {
            // Get my db
            var model = _context.Menu.Include(m => m.ChildMenuSub) as IQueryable<Menu>;
            model = model.Where(p => p.MenuPosition == menuPosition);
// Send your collection of Mreations to the View
 return PartialView(model);
}

and in the last project with net 4 i use to write the following code in the principal view in order to call my partial view :

@Html.Action("_MenuNav", "Menus", new { menuPosition = "Menu" })

but it looks like it does not work anymore this with NET6

Do you know how to rewrite my code in order to get the same result?

Body:
you must be mixing view components with partial views. Partial view were always used like this

<div id="partialName">
<partial name="_PartialName" />
</div>

with model

<partial name="_PartialName" model="Model.MyInfo" />

or for async

<div id="partialName">
@await Html.PartialAsync("_PartialName")
</div>

and the most popular way to update parital view is using ajax

And you can check my answer about viewcomponents here
https://stackoverflow.com/a/69698058/11392290


问:
How to get almost increasing sequence of integers
Given a sequence of integers as an array,i have to determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array. Example

For sequence = [1, 3, 2, 1], the output should be

```<code>almostIncreasingSequence(sequence) = false
</code>```

There is no one element in this array that can be removed in order to get a strictly increasing sequence.

For sequence = [1, 3, 2] the output should be

```<code>almostIncreasingSequence(sequence) = true
</code>```

We can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, we can remove 2 to get the strictly increasing sequence [1, 3].

The function must return true if it is possible to remove one element from the array in order to get a strictly increasing sequence, otherwise return false.

Here is what i have already tried , but it doesnt work for all situations

function almostIncreasingSequence(sequence) {
    for (var i = 0; i < sequence.length; i++) {
        if (sequence[i] > sequence[i + 1]) {
            sequence.splice(i, 1);
           return true;
        };
        return false;
    };
}```

答:
This is my optimized solution with python:</p>
```<code>def solution(sequence):
    if len(sequence) > 2:
        for i in range(len(sequence)-1):
            if sequence[i]>sequence[i+1]:
                news = sequence[:i]+sequence[i+1:]
                if news == sorted(news) and len(set(news)) == len(news):
                    return True
                else:
                    news = sequence[:i+1]+sequence[i+2:]
                    if news == sorted(news) and len(set(news)) == len(news):
                        return True
        return False
    else:
        return True
</code>```

Body:
Given a sequence of integers as an array,i have to determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array. Example

For sequence = [1, 3, 2, 1], the output should be

almostIncreasingSequence(sequence) = false

There is no one element in this array that can be removed in order to get a strictly increasing sequence.

For sequence = [1, 3, 2] the output should be

almostIncreasingSequence(sequence) = true

We can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, we can remove 2 to get the strictly increasing sequence [1, 3].

The function must return true if it is possible to remove one element from the array in order to get a strictly increasing sequence, otherwise return false.

Here is what i have already tried , but it doesnt work for all situations

function almostIncreasingSequence(sequence) {
    for (var i = 0; i < sequence.length; i++) {
        if (sequence[i] > sequence[i + 1]) {
            sequence.splice(i, 1);
           return true;
        };
        return false;
    };
}

Body:
This is my optimized solution with python:

def solution(sequence):
    if len(sequence) > 2:
        for i in range(len(sequence)-1):
            if sequence[i]>sequence[i+1]:
                news = sequence[:i]+sequence[i+1:]
                if news == sorted(news) and len(set(news)) == len(news):
                    return True
                else:
                    news = sequence[:i+1]+sequence[i+2:]
                    if news == sorted(news) and len(set(news)) == len(news):
                        return True
        return False
    else:
        return True


问:
Dropdown Menu Does not Work in Bootstrap 5
Dropdown menu does not work in Bootstrap 5. But when I add some script codes it works.For example:

```<code><script>
    $(document).ready(function() {
        $('.dropdown-toggle').dropdown();
    });
</script>
</code>```

When I add this code block it works.But my question is: Doesn't Bootstrap have to run the dropdown menus with its own js script without adding additional script codes?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Focus Education</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

        <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton" data-mdb-toggle="dropdown" aria-expanded="false">
      Dropdown button
    </button>

Action

Another action

Something else here

```

答:
basically you had a typo/mistake at data-mdb-toggle="dropdown" it should be data-bs-toggle="dropdown" please view the docs for more explaination on the component and apis available.

Below is the working snippet

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Focus Education</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
      Dropdown button
    </button>

Action

Another action

Something else here

```

Body:
Dropdown menu does not work in Bootstrap 5. But when I add some script codes it works.For example:

When I add this code block it works.But my question is: Doesn't Bootstrap have to run the dropdown menus with its own js script without adding additional script codes?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Focus Education</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

        <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton" data-mdb-toggle="dropdown" aria-expanded="false">
      Dropdown button
    </button>

Action

Another action

Something else here

Body:
basically you had a typo/mistake at data-mdb-toggle="dropdown" it should be data-bs-toggle="dropdown" please view the docs for more explaination on the component and apis available.

Below is the working snippet

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Focus Education</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>

<body>
  <div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
      Dropdown button
    </button>
    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
      <li><a class="dropdown-item" href="#">Action</a></li>
      <li><a class="dropdown-item" href="#">Another action</a></li>
      <li><a class="dropdown-item" href="#">Something else here</a></li>
    </ul>
  </div>

</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

</html>


问:
503 ERROR The request could not be satisfied (AWS Amplify)
I have deployed a Next.js server side rendering app on AWS Amplify. I am new to AWS and don't know exactly why I am encountering this error. I have read so many articles and documentations but I am unable to solve this issue.

I am using getServerSideProps to get params and props from API etc. On Vercel and Netlify, my app is running fine but I am getting errors on Amplify AWS.

My app is loading static pages, but giving me an error on dynamic pages.
E.g. www.example.com/test-1

Here test-1 is a dynamic route "/:id"

The error I get:

503 ERROR
The request could not be satisfied.
The Lambda function associated with the CloudFront distribution is invalid or doesn't have the required permissions. We can't connect to
the server for this app or website at this time. There might be too
much traffic or a configuration error. Try again later, or contact the
app or website owner.
If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing
the CloudFront documentation.

I know this error is specifically towards permissions, but I don't know how to configure them.

答:
Firstly, do check the version of Next.js you're using as AWS Amplify officially supports version 11. Also, Next.js 11 by default uses webpack5 which is again not supported by Amplify. So, you can do a few things to fix this (like I did) -

Use Next.js to v11.1.3 and

In the next.config.js set webpack5 to false -

  //next.config.js

  const nextConfig = {
    ...
    ...
    webpack5: false,
    ...
    ...
  }

  module.exports = nextConfig
```


问:
How can I advanced search for tweets on engine with the word 'casa' but not having 'câsa' results included?
I try this method:

```<code>casa -câsa
</code>```

But that way it excludes the casa without accents too, then the search returns blank.

答:
To the best of my knowledge, Twitter flattens-out all accented latin letters and treats them the same, so...
a = á = â = à = ä = ā = ã = å.

One possible way to clean a little bit your search results is to use Twitter's advanced search language operator lang:[xx] in negation -lang:[xx], where [xx] represents the 2 letter ISO language code of the languages which might be using that particular letter (assuming you wish to filter-out from the results).

In your example, the letter Ââ (circumflex) is used by the following languages: Sami, Romanian, Vietnamese, French, Frisian, Portuguese, Turkish, Walloon and Welsh. Assuming you wish to filter-out results from these specific languages, your Twitter search query would look like this:

```<code>"casa" -lang:se -lang:ro -lang:vi -lang:fr -lang:fy -lang:pt -lang:tr -lang:wa -lang:cy
</code>```

try it...

Alternatively, you can use the same lang:[xx] operator to limit Twitter's  search results to one specific language (for example - English):

```<code>"casa" lang:en
</code>```

try it...

This might not be a water-tight solution but it can reduce a lot of false positives.

Finally, you should keep in mind that Twitter is not guaranteeing accuracy in their machine-identification of languages.

Body:
I try this method:

casa -câsa

But that way it excludes the casa without accents too, then the search returns blank.

Body:
To the best of my knowledge, Twitter flattens-out all accented latin letters and treats them the same, so...
a = á = â = à = ä = ā = ã = å.

One possible way to clean a little bit your search results is to use Twitter's advanced search language operator lang:[xx] in negation -lang:[xx], where [xx] represents the 2 letter ISO language code of the languages which might be using that particular letter (assuming you wish to filter-out from the results).

In your example, the letter Ââ (circumflex) is used by the following languages: Sami, Romanian, Vietnamese, French, Frisian, Portuguese, Turkish, Walloon and Welsh. Assuming you wish to filter-out results from these specific languages, your Twitter search query would look like this:

"casa" -lang:se -lang:ro -lang:vi -lang:fr -lang:fy -lang:pt -lang:tr -lang:wa -lang:cy

try it...

Alternatively, you can use the same lang:[xx] operator to limit Twitter's  search results to one specific language (for example - English):

"casa" lang:en

try it...

This might not be a water-tight solution but it can reduce a lot of false positives.

Finally, you should keep in mind that Twitter is not guaranteeing accuracy in their machine-identification of languages.


问:
Always gives false even though file exists and is not empty
I have a bash script:

```<code>echo " enter file name "
read $file
if [ -f "$file" ] && [ -s "$file" ]
then
   echo " file does not exist, or is empty "
else
   echo " file exists and is not empty "
fi
</code>```

No matter what I enter as a $file, it gives me the false value. I can even enter a file that does not even exist; it still will give me the false value. Why is that?

答:
This is the true solution:

```<code>if [[ -f $file && -s $file ]]
</code>```

With [[ the quotes are unnecessary because [[ handles empty strings and strings with whitespace more intuitively.

The solution that was proposed to you:

```<code>if [ -s "$file" ]
</code>```

is wrong because it is instead equivalent to:

```<code>if [[ -e $file && -s $file ]]
</code>```

which, in addition to the regular files dictated by the word -f, also looks for:

Directory

Symbolic Link

Block Special Device

Character Device

Unix Socket (local domain socket)

Named Pipe

Body:
I have a bash script:

echo " enter file name "
read $file
if [ -f "$file" ] && [ -s "$file" ]
then
   echo " file does not exist, or is empty "
else
   echo " file exists and is not empty "
fi

No matter what I enter as a $file, it gives me the false value. I can even enter a file that does not even exist; it still will give me the false value. Why is that?

Body:
This is the true solution:

if [[ -f $file && -s $file ]]

With [[ the quotes are unnecessary because [[ handles empty strings and strings with whitespace more intuitively.

The solution that was proposed to you:

if [ -s "$file" ]

is wrong because it is instead equivalent to:

if [[ -e $file && -s $file ]]

which, in addition to the regular files dictated by the word -f, also looks for:

Directory

Symbolic Link

Block Special Device

Character Device

Unix Socket (local domain socket)

Named Pipe


问:
Inserting increment for each unique value in sql
I've been tasked with a SQL problem that is outside of the limited scope of sql knowledge that I have. I have the following problem.

I have a table that currently looks like this:

```<code> widgets
---------
    a
    a
    a
    b
    b
    c
    d
    d
    d
</code>```

I would like to have another table that has each unique value incrementally numbered... Like so:

```<code>widgets  | widget_id
--------- ----------
    a    |    1
    a    |    1
    a    |    1
    b    |    2
    b    |    2
    c    |    3
    d    |    4
    d    |    4
    d    |    4
</code>```

I'm not sure how this would be done with an insert statement?

答:
Create a table with an IDENTITY column:

something like this:

```<code>CREATE TABLE widget_ids (
  widget_id INT AUTO_INCREMENT PRIMARY KEY,
  widget varchar(5)
)
</code>```

AND run this command:

```<code>INSERT INTO
  widget_ids (widget)
SELECT DISTINCT
  widget
FROM
  widgets
</code>```

Now, this is all just an example.  If you wanted a long-term solution, you would want to index your 'widget' field in the widget_ids table, and you would want to make sure that a value was entered for each new widget.

EDIT: Oh, also, to get the exact table you have listed second, you would left join the widgets table to the widget_ids table:

```<code>SELECT
    w.widget,
    wi.widget_id
FROM
    widgets w
LEFT JOIN
    widget_ids wi
  ON
    w.widget = wi.widget
</code>```

And here, of course, indexing is your friend.

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

Body:
I've been tasked with a SQL problem that is outside of the limited scope of sql knowledge that I have. I have the following problem.

I have a table that currently looks like this:

 widgets
---------
    a
    a
    a
    b
    b
    c
    d
    d
    d

I would like to have another table that has each unique value incrementally numbered... Like so:

widgets  | widget_id
--------- ----------
    a    |    1
    a    |    1
    a    |    1
    b    |    2
    b    |    2
    c    |    3
    d    |    4
    d    |    4
    d    |    4

I'm not sure how this would be done with an insert statement?

Body:
Create a table with an IDENTITY column:

something like this:

CREATE TABLE widget_ids (
  widget_id INT AUTO_INCREMENT PRIMARY KEY,
  widget varchar(5)
)

AND run this command:

INSERT INTO
  widget_ids (widget)
SELECT DISTINCT
  widget
FROM
  widgets

Now, this is all just an example.  If you wanted a long-term solution, you would want to index your 'widget' field in the widget_ids table, and you would want to make sure that a value was entered for each new widget.

EDIT: Oh, also, to get the exact table you have listed second, you would left join the widgets table to the widget_ids table:

SELECT
    w.widget,
    wi.widget_id
FROM
    widgets w
LEFT JOIN
    widget_ids wi
  ON
    w.widget = wi.widget

And here, of course, indexing is your friend.

OwnerDisplayName: John Gietzen

LastEditorDisplayName: John Gietzen


问:
size of C structure
```<code>struct st1{
    int a:1; int b:3; int c:6; int d:3;
}s1;

struct st2{
    char a:3;
}s2;

int main(){
    printf("%d : %d",sizeof(s1),sizeof(s2));
    getchar();
}
</code>```

I am getting the output as 2 : 1

will you please tell me, how this program works and whats the use of : operator (a:1) here.

Thank you

答: The : operator used there specifies sizes in bits of the fields contained there. sizeof() return byte boundary length, so for the first, 13 bits (2 bytes), and for the second, 1 byte.

Title: size of C structure

Body:
struct st1{
    int a:1; int b:3; int c:6; int d:3;
}s1;

struct st2{
    char a:3;
}s2;

int main(){
    printf("%d : %d",sizeof(s1),sizeof(s2));
    getchar();
}

I am getting the output as 2 : 1

will you please tell me, how this program works and whats the use of : operator (a:1) here.

Thank you


问:
3 column grid layout, full screen
I am new to grid. I want it fullscreen, but, not sure. Also not sure, of why the navigator and sidebar
appear as they appear.

* {
    padding: 0;
    margin: 0;
}

html, body {
    height: 100%;
    width: 100%;
}

.container {
    display: grid;
    grid-template-columns: 200px 1fr 200px;
    grid-template-rows: auto 2fr auto;
    grid-template-areas:
    "header header  header"
    "nav    article aside"
    "footer footer  footer";
    grid-column-gap: 8px;
    height: 100vh;
    width: 100%;
}

header, nav, footer, main, article, aside
{
    display: block;
    width: 100%;
    height: 100%;
}

header {
    background-color: bisque;
    grid-area: header;
}

nav {
    grid-area: nav;
}

aside {
    grid-area: side;
}

article {
    grid-area: article;
    background-color: aqua;
}

footer{
    background-color: beige;
    width: 100%;
    grid-area: footer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/base.css" type="text/css" />
</head>

<body>
    <div class="container" role="main">
        <header>{header}</header>
        <nav>{navigation}</nav>
        <article>
            <main>{main content}</main>
        </article>
        <aside>{sidebar}</aside>
        <footer>{footer}</footer>
    </div>
</body>

</html></code>```

答:
* {
    padding: 0;
    margin: 0;
}

html, body {
    height: 100%;
    width: 100%;
}

.container {
    display: grid;
    grid-template-columns: 200px 1fr 200px;
    grid-template-rows: auto 2fr auto;
    grid-template-areas:
    "header header  header"
    "nav    article aside"
    "footer footer  footer";
    grid-column-gap: 8px;
    height: 100vh;
    width: 100%;
}

header, nav, footer, main, article, aside
{
    display: block;
    width: 100%;
    height: 100%;
}

header {
    background-color: bisque;
    grid-area: header;
}

nav {
    grid-area: nav;
}

aside {
    grid-area: aside;
}

article {
    grid-area: article;
    background-color: aqua;
}

footer{
    background-color: beige;
    width: 100%;
    grid-area: footer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/base.css" type="text/css" />
</head>

<body>
    <div class="container" role="main">
        <header>{header}</header>
        <nav>{navigation}</nav>
        <article>
            <main>{main content}</main>
        </article>
        <aside>{sidebar}</aside>
        <footer>{footer}</footer>
    </div>
</body>

</html></code>```

Title: 3 column grid layout, full screen

Body:
I am new to grid. I want it fullscreen, but, not sure. Also not sure, of why the navigator and sidebar
appear as they appear.

* {
    padding: 0;
    margin: 0;
}

html, body {
    height: 100%;
    width: 100%;
}

.container {
    display: grid;
    grid-template-columns: 200px 1fr 200px;
    grid-template-rows: auto 2fr auto;
    grid-template-areas:
    "header header  header"
    "nav    article aside"
    "footer footer  footer";
    grid-column-gap: 8px;
    height: 100vh;
    width: 100%;
}

header, nav, footer, main, article, aside
{
    display: block;
    width: 100%;
    height: 100%;
}

header {
    background-color: bisque;
    grid-area: header;
}

nav {
    grid-area: nav;
}

aside {
    grid-area: side;
}

article {
    grid-area: article;
    background-color: aqua;
}

footer{
    background-color: beige;
    width: 100%;
    grid-area: footer;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/base.css" type="text/css" />

        {header}
        {navigation}

            {main content}

        {sidebar}
        {footer}

Body:
* {
    padding: 0;
    margin: 0;
}

html, body {
    height: 100%;
    width: 100%;
}

.container {
    display: grid;
    grid-template-columns: 200px 1fr 200px;
    grid-template-rows: auto 2fr auto;
    grid-template-areas:
    "header header  header"
    "nav    article aside"
    "footer footer  footer";
    grid-column-gap: 8px;
    height: 100vh;
    width: 100%;
}

header, nav, footer, main, article, aside
{
    display: block;
    width: 100%;
    height: 100%;
}

header {
    background-color: bisque;
    grid-area: header;
}

nav {
    grid-area: nav;
}

aside {
    grid-area: aside;
}

article {
    grid-area: article;
    background-color: aqua;
}

footer{
    background-color: beige;
    width: 100%;
    grid-area: footer;
}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/base.css" type="text/css" />
</head>

<body>
    <div class="container" role="main">
        <header>{header}</header>
        <nav>{navigation}</nav>
        <article>
            <main>{main content}</main>
        </article>
        <aside>{sidebar}</aside>
        <footer>{footer}</footer>
    </div>
</body>

</html>


问:
Exporting numpy array as csv imported to Tensorflow.js has no shape
I need to export numpy arrays from Python to Javascript for use in Tensorflow.js.
I had a look here and tried to do something similar but my imported tensor has no shape, it's not loaded properly.

Export from Python using Pandas dataframe looked like this (simplified):

```<code>A = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
A_df = pd.DataFrame(A)
A_df.to_csv('tmp.csv')

</code>```

The tmp.csv looks like this:

```<code>,0,1,2
0,1,2,3
1,4,5,6
2,7,8,9
3,10,11,12

</code>```

In Javascript it's loaded from url like this, when I test it on my local server:

```<code>const url = 'https://127.0.0.1/[localurlpath...]/tmp.csv'

const cols = ["", "0", "1", "2"]
let csvConfig = {
  hasHeader: true,
  columnNames: cols
}

const A = tf.data.csv(url, csvConfig)
console.log(A.shape)

</code>```

Console log says: "undefined"

I have tried:

```<code>delimiter: '\n',
delimWhitespace: true

</code>```

But to no avail.
I also tried other column names to avoid the empty position.
I get no errors in the Javascript console.

答:
Since the numpy arrays in question aren't that big,  aprox. 1000x50 at most, I ended upp using this method instead. CSV seemed overly complicated in the situation. Simplified example:

Export from Python:

```<code>A = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
with open('mtrx.json', 'w') as outfile:
    outfile.write(json.dumps(np.array(A).tolist()))

</code>```

Import in Javascript:

```<code>const url = 'http://127.0.0.1/[...local filepath...]/mtrx.json'
const res = await fetch(url)
const mtrx = await JSON.parse(await res.text())
</code>```

It turns out the imported mtrx object can be used in the tf.matMulcalculation I need to perform without any further conversion. I thought it needed to be converted to a tf.tensor. It was simpler than I thought. I still don't understand what's wrong with my first method but I'll save that for a rainy day.

Body:
I need to export numpy arrays from Python to Javascript for use in Tensorflow.js.
I had a look here and tried to do something similar but my imported tensor has no shape, it's not loaded properly.

Export from Python using Pandas dataframe looked like this (simplified):

A = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
A_df = pd.DataFrame(A)
A_df.to_csv('tmp.csv')

The tmp.csv looks like this:

,0,1,2
0,1,2,3
1,4,5,6
2,7,8,9
3,10,11,12

In Javascript it's loaded from url like this, when I test it on my local server:

const url = 'https://127.0.0.1/[localurlpath...]/tmp.csv'

const cols = ["", "0", "1", "2"]
let csvConfig = {
  hasHeader: true,
  columnNames: cols
}

const A = tf.data.csv(url, csvConfig)
console.log(A.shape)

Console log says: "undefined"

I have tried:

delimiter: '\n',
delimWhitespace: true

But to no avail.
I also tried other column names to avoid the empty position.
I get no errors in the Javascript console.

Body:
Since the numpy arrays in question aren't that big,  aprox. 1000x50 at most, I ended upp using this method instead. CSV seemed overly complicated in the situation. Simplified example:

Export from Python:

A = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
with open('mtrx.json', 'w') as outfile:
    outfile.write(json.dumps(np.array(A).tolist()))

Import in Javascript:

const url = 'http://127.0.0.1/[...local filepath...]/mtrx.json'
const res = await fetch(url)
const mtrx = await JSON.parse(await res.text())

It turns out the imported mtrx object can be used in the tf.matMulcalculation I need to perform without any further conversion. I thought it needed to be converted to a tf.tensor. It was simpler than I thought. I still don't understand what's wrong with my first method but I'll save that for a rainy day.