问:
Change icon color on scroll for vertical navigation in react
I am building a react app with vertical navigation
I am trying to add the feature where the colour of the icon changed on the scroll
the scroll looks like this
enter image description here

Is there any method that lets you keep track of what section you currently are on in react?

答:
You should listen for a scroll event in a page. When a section crosses, for example, the middle of the viewport, then change color of an appropriate icon. You can also use IntersectionObserver</p>
```<code> window.addEventListener('scroll', () => {
   //watch for the window.scrollY changes and compare with the
  //section offset, when they intersects, change the colour of the
  //icon
 })
</code>```

Body:
You should listen for a scroll event in a page. When a section crosses, for example, the middle of the viewport, then change color of an appropriate icon. You can also use IntersectionObserver

 window.addEventListener('scroll', () => {
   //watch for the window.scrollY changes and compare with the
  //section offset, when they intersects, change the colour of the
  //icon
 })


来源: stackexchange

问:
Adding a Nested Statement
The problem,

Write an application that reads three nonzero values entered by the user and determines and prints whether they could represent the sides of a triangle.

I currently have

```<code>import java.util.Scanner;
public class FourDecimalThirtySix {
    public static void main (String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter three sizes, speparated by spaces");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();
        input.close();

        if ( (a + b) > c) {
            if ( (a + c) > b) {
                if ( (b + c) > a)
                    System.out.printf("A triangle can be made of %.2f, %.2f, by %.2f.", a,
                        b, c);
                return;
            }
        }
    }
}
</code>```

I am trying to add an else statement to this for it to say "these values cannot make a triangle" if the original conditions are not meet.  Currently the program does not do anything if the 3 conditions are not met

答:
If you fix the indentation that would make it easier for you to see the format of the code. Then, if you want the logic of the code block to only show the statement "these values cannot make a triangle" if the 3 preceding conditions are not met then you can add the else {} after the third (inner most) if {}.

This will result in the else block executing only if the first two ifs are evaluated to be true. So you might need to consider what you want to print after each statement, not just if the first two are true and the last if {} evaluates to false.

You can find useful documentation on java code styling here (link I added is specifically for indentation rules):
https://www.cs.cornell.edu/courses/JavaAndDS/JavaStyle.html#Indentation

ContentLicense: CC BY-SA 4.0

Title: Adding a Nested Statement

Body:
The problem,

Write an application that reads three nonzero values entered by the user and determines and prints whether they could represent the sides of a triangle.

I currently have

import java.util.Scanner;
public class FourDecimalThirtySix {
    public static void main (String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter three sizes, speparated by spaces");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();
        input.close();

        if ( (a + b) > c) {
            if ( (a + c) > b) {
                if ( (b + c) > a)
                    System.out.printf("A triangle can be made of %.2f, %.2f, by %.2f.", a,
                        b, c);
                return;
            }
        }
    }
}

I am trying to add an else statement to this for it to say "these values cannot make a triangle" if the original conditions are not meet.  Currently the program does not do anything if the 3 conditions are not met


问:
Python Twitter API program returns error code 403: Forbidden
I am a beginner working through the python basics course on Freecodecamp.com. I am using Mac OS, python3.10.

I am trying to connect to twitter's API using an http request, gather data and then parse that data.

I made a twitter developer account and got my keys and tokens and all that stuff.

Here is a link to the exact problem I am working through (scroll down to where it says "Application 2: Twitter" in bold).

Here is the code I am trying to run:

```<code>import urllib.request, urllib.parse, urllib.error
import twurl
import ssl

# https://apps.twitter.com/
# Create App and get the four strings, put them in hidden.py

TWITTER_URL = 'https://api.twitter.com/1.1/statuses/user_timeline.json'

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

while True:
    print('')
    acct = input('Enter Twitter Account:')
    if (len(acct) < 1): break
    url = twurl.augment(TWITTER_URL,
                        {'screen_name': acct, 'count': '2'})
    print('Retrieving', url)
    connection = urllib.request.urlopen(url, context=ctx)
    data = connection.read().decode()
    print(data[:250])
    headers = dict(connection.getheaders())
    # print headers
    print('Remaining', headers['x-rate-limit-remaining'])
</code>```

And here is the error that code returns:

```<code>Enter Twitter Account:drchuck
Retrieving https://api.twitter.com/1.1/statuses/user_timeline.json?oauth_consumer_key=9uxUyq33IRxCL5CZf7LyfubX3&oauth_timestamp=1641148177&oauth_nonce=80764354&oauth_version=1.0&screen_name=drchuck&count=2&oauth_token=1423673018467983360-Tg6vMoRAWO7FCgnGKhz9WgrPUoCsZa&oauth_signature_method=HMAC-SHA1&oauth_signature=C%2FQIvEhgZ8AQQooC4E%2BekJSZwjE%3D
Traceback (most recent call last):
  File "/Users/jguinn/env/twtr-api-demo/twitter1.py", line 23, in <module>
    connection = urllib.request.urlopen(url, context=ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 216, in urlopen
    return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 525, in open
    response = meth(req, response)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 634, in http_response
    response = self.parent.error(
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 563, in error
    return self._call_chain(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 496, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 643, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
</code>```

I went on the Twitter developer website to look for information about response codes and Twitter says that 403: Forbidden codes means that:

"The request is understood, but it has been refused or access is not
allowed. An accompanying error message will explain why."

As a solution they suggest:

"Check that your developer account includes access to the endpoint
you’re trying to use. You may also need to get your App allowlisted
(e.g. Engagement API or Ads API) or sign up for access."

I am not really sure what any of this means. Any help would be greatly appreciated. Thanks.

答:
I don't know if you resolved the issue yet but here's how I did it.

You have to go on your developer portal on twitter and apply for Elevated access. It's a pretty smooth process and once you've done that you'll be good.

Body:
I am a beginner working through the python basics course on Freecodecamp.com. I am using Mac OS, python3.10.

I am trying to connect to twitter's API using an http request, gather data and then parse that data.

I made a twitter developer account and got my keys and tokens and all that stuff.

Here is a link to the exact problem I am working through (scroll down to where it says "Application 2: Twitter" in bold).

Here is the code I am trying to run:

import urllib.request, urllib.parse, urllib.error
import twurl
import ssl

# https://apps.twitter.com/
# Create App and get the four strings, put them in hidden.py

TWITTER_URL = 'https://api.twitter.com/1.1/statuses/user_timeline.json'

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

while True:
    print('')
    acct = input('Enter Twitter Account:')
    if (len(acct) < 1): break
    url = twurl.augment(TWITTER_URL,
                        {'screen_name': acct, 'count': '2'})
    print('Retrieving', url)
    connection = urllib.request.urlopen(url, context=ctx)
    data = connection.read().decode()
    print(data[:250])
    headers = dict(connection.getheaders())
    # print headers
    print('Remaining', headers['x-rate-limit-remaining'])

And here is the error that code returns:

Enter Twitter Account:drchuck
Retrieving https://api.twitter.com/1.1/statuses/user_timeline.json?oauth_consumer_key=9uxUyq33IRxCL5CZf7LyfubX3&oauth_timestamp=1641148177&oauth_nonce=80764354&oauth_version=1.0&screen_name=drchuck&count=2&oauth_token=1423673018467983360-Tg6vMoRAWO7FCgnGKhz9WgrPUoCsZa&oauth_signature_method=HMAC-SHA1&oauth_signature=C%2FQIvEhgZ8AQQooC4E%2BekJSZwjE%3D
Traceback (most recent call last):
  File "/Users/jguinn/env/twtr-api-demo/twitter1.py", line 23, in <module>
    connection = urllib.request.urlopen(url, context=ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 216, in urlopen
    return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 525, in open
    response = meth(req, response)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 634, in http_response
    response = self.parent.error(
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 563, in error
    return self._call_chain(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 496, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 643, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden

I went on the Twitter developer website to look for information about response codes and Twitter says that 403: Forbidden codes means that:

"The request is understood, but it has been refused or access is not
allowed. An accompanying error message will explain why."

As a solution they suggest:

"Check that your developer account includes access to the endpoint
you’re trying to use. You may also need to get your App allowlisted
(e.g. Engagement API or Ads API) or sign up for access."

I am not really sure what any of this means. Any help would be greatly appreciated. Thanks.


问:
dbc.Select() setting dropdown to required doesn't automatically outline an empty dropdown in DASH
I'm creating a plotly-Dash form and using bootstraps dbc.Select() to create a dropdown.  I want it to be outlined with a red border as I have with my dbc.Input() boxes when nothing is selected, but it doesn't appear to be working.  What am I doing wrong?  I set required = True as I did with my dbc.Input() but no outline:

```<code>dbc.Select(
    id="temperature",
    required=True,
    options=[{'label': 'Heated', 'value': 'Heated'},
             {'label': 'Ambient', 'value': 'Ambient'},
             {'label': 'N/A', 'value': 'N/A'}],
             value=temperature[0]
),
</code>```

答:
Not sure why the required field is not working for dbc.Select, but there is a workaround to getting required working for it.

You could have a callback triggered either by selecting a value for the dropdown or using dcc.Interval and checking if dropdown.value is None. You could also add an empty option into the dropdown and extend the check to dropdown.value is None or dropdown.value == "" in case the user selects it. if the condition is true, then set the required attribute to true and have some css style for :required pseudo class to some color (e.g. #SOME_INPUT:required {border: 1px solid red;}).

Something like the following could be used as a template:

select = dbc.Select(
    id="dropdown-required",
    required=True,
    options=[
            {'label': '', 'value': ''},
            {'label': 'Heated', 'value': 'Heated'},
            {'label': 'Ambient', 'value': 'Ambient'},
            {'label': 'N/A', 'value': 'N/A'}],
)
app.layout = html.Div([select])

@app.callback(
    Output("dropdown-required", "required"),
    Input("dropdown-required", "value")
)
def set_dropdown_required(value):
    res = (
        True if value is None or value == ""
        else False
    )
    return res
```
<p>and some css styling under <code>assets/style.css</code>:</p>
```#dropdown-required:required {
    border: 1px solid red;
}
```

Body:
I'm creating a plotly-Dash form and using bootstraps dbc.Select() to create a dropdown.  I want it to be outlined with a red border as I have with my dbc.Input() boxes when nothing is selected, but it doesn't appear to be working.  What am I doing wrong?  I set required = True as I did with my dbc.Input() but no outline:

dbc.Select(
    id="temperature",
    required=True,
    options=[{'label': 'Heated', 'value': 'Heated'},
             {'label': 'Ambient', 'value': 'Ambient'},
             {'label': 'N/A', 'value': 'N/A'}],
             value=temperature[0]
),

Body:
Not sure why the required field is not working for dbc.Select, but there is a workaround to getting required working for it.

You could have a callback triggered either by selecting a value for the dropdown or using dcc.Interval and checking if dropdown.value is None. You could also add an empty option into the dropdown and extend the check to dropdown.value is None or dropdown.value == "" in case the user selects it. if the condition is true, then set the required attribute to true and have some css style for :required pseudo class to some color (e.g. #SOME_INPUT:required {border: 1px solid red;}).

Something like the following could be used as a template:

select = dbc.Select(
    id="dropdown-required",
    required=True,
    options=[
            {'label': '', 'value': ''},
            {'label': 'Heated', 'value': 'Heated'},
            {'label': 'Ambient', 'value': 'Ambient'},
            {'label': 'N/A', 'value': 'N/A'}],
)
app.layout = html.Div([select])

@app.callback(
    Output("dropdown-required", "required"),
    Input("dropdown-required", "value")
)
def set_dropdown_required(value):
    res = (
        True if value is None or value == ""
        else False
    )
    return res

and some css styling under assets/style.css:

#dropdown-required:required {
    border: 1px solid red;
}


问:
Search data between two tables from SQL
I want to get the data only from "products" table, the problem is if the data was found from "categories" table it will returns empty.

```<code>SELECT p.code AS CODE, p.model AS NAME
FROM products p
LEFT JOIN categories c
ON p.category = c.id
WHERE p.model LIKE "%LAPTOP%" OR c.category_name LIKE "%LAPTOP%"
</code>```

I thought this query will return exact table column you want to achieve if both were connected from this ON p.category = c.id.

答:
Assume that all your cases is as your sample data in db-fiddle, you could use this query:

```<code>SELECT p.code AS CODE, p.model, COALESCE(c.category_name, p.model) AS NAME
FROM products p
LEFT JOIN categories c
ON p.category_id = c.category_id
WHERE p.model LIKE "%LAPTOP%" OR c.category_name LIKE "%LAPTOP%"
</code>```

tested in db-fiddle

Title: Search data between two tables from SQL

Body:
I want to get the data only from "products" table, the problem is if the data was found from "categories" table it will returns empty.

SELECT p.code AS CODE, p.model AS NAME
FROM products p
LEFT JOIN categories c
ON p.category = c.id
WHERE p.model LIKE "%LAPTOP%" OR c.category_name LIKE "%LAPTOP%"

I thought this query will return exact table column you want to achieve if both were connected from this ON p.category = c.id.

Body:
Assume that all your cases is as your sample data in db-fiddle, you could use this query:

SELECT p.code AS CODE, p.model, COALESCE(c.category_name, p.model) AS NAME
FROM products p
LEFT JOIN categories c
ON p.category_id = c.category_id
WHERE p.model LIKE "%LAPTOP%" OR c.category_name LIKE "%LAPTOP%"

tested in db-fiddle


问:
How to use variables in dot notation like square bracket notation
I have been using square bracket notation in Javascript to create and call associative arrays.

In this example, I understand that square bracket notation allows you to use a variable to call a certain object in the array.

How would you do something like this in dot notation?

```<code>var item = {};
    item['1'] = 'pen';

var x = 1;

console.log(item[x]);  // console will show 'pen'
</code>```

答:
the dot notation is limited to certain chars ... see this question ... the square bracket notation allows you to break that limitation:</p>

```<code>var item = {};
item['very long variable name containing empty spaces ... and dots...'] = 'valid var';
item.1 = 'not valid var'; // will not work;
item['1'] = 'valid var'; // will do just fine...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been using square bracket notation in Javascript to create and call associative arrays.

In this example, I understand that square bracket notation allows you to use a variable to call a certain object in the array.

How would you do something like this in dot notation?

var item = {};
    item['1'] = 'pen';

var x = 1;

console.log(item[x]);  // console will show 'pen'

Body:
the dot notation is limited to certain chars ... see this question ... the square bracket notation allows you to break that limitation:

var item = {};
item['very long variable name containing empty spaces ... and dots...'] = 'valid var';
item.1 = 'not valid var'; // will not work;
item['1'] = 'valid var'; // will do just fine...


问:
How to delete files in S3 using CodePipeline
I have created a CodePipeline that takes input(files) from CodeCommit repository and deploys files to S3 bucket. When I delete files in CodeCommit repository, pipeline doesn't delete the file in the corresponding S3 bucket. In short, I want my S3 bucket to be in sync with CodeCommit repository. How can I achieve this?

My Pipeline doesn't have CodeBuild stage.

AWS-CodeCommit --> CodePipeline --> Deploy-to-Cross-Account-S3

答:
You can add a CodeBuild stage of:

```<code>      - aws s3 sync . s3://[bucket_name] --delete
</code>```

Not sure how to make it work cross-account, tho.

Body:
You can add a CodeBuild stage of:

      - aws s3 sync . s3://[bucket_name] --delete

Not sure how to make it work cross-account, tho.


问:
kernel failed to start using conda environment with Jupyter in Visual Studio Code
When using a Jupyter notebook file in Visual Studio code with the Jupyter extension I receive the error The kernel failed to start due to the missing module 'ipykernel_launcher'. Consider installing this module.  View Jupyter [log](command:jupyter.viewOutput) for further details.

This notebook works correctly from the JupyterLab web application when I select the same conda environment that was selected in Visual Studio Code.

pip list shows that ipykernel version 5.3.4 is installed, but I don't know how to install ipykernel_launcher. I tried reinstalling pyzmq and it didn't help.

Any ideas why this isn't working?

答:
Had the same problem. My solution is --

First uninstall all jupyter related modules:

```<code>python3 -m pip uninstall -y jupyter jupyter_core jupyter-client jupyter-console jupyterlab_pygments notebook qtconsole nbconvert nbformat jupyterlab-widgets nbclient ipykernel ipynb
</code>```

(from: https://stackoverflow.com/a/52912244/1516331)

And then reinstall ipykernel. I'm using VScode so when I run a cell, VSCode asked me to installipykernel. The following should work the same alternatively:

```<code>conda install -c conda-forge --update-deps --force-reinstall ipykernel -y
</code>```

Body:
Had the same problem. My solution is --

First uninstall all jupyter related modules:

python3 -m pip uninstall -y jupyter jupyter_core jupyter-client jupyter-console jupyterlab_pygments notebook qtconsole nbconvert nbformat jupyterlab-widgets nbclient ipykernel ipynb

(from: https://stackoverflow.com/a/52912244/1516331)

And then reinstall ipykernel. I'm using VScode so when I run a cell, VSCode asked me to installipykernel. The following should work the same alternatively:

conda install -c conda-forge --update-deps --force-reinstall ipykernel -y


问:
Navbar auto responsive in mobile version
I'm currently a beginner with web programming, I have a problem when the mobile screen changed then the navbar will go bottom, I don't see any good source codes of this problem since some of the people use hamburger style.

This is the current view of the mobile when im not changing it to smaller view

This is the view after changing the view to smaller size

Here is the code:

.servicebtn,
.contactbtn,
.careerbtn,
.aboutbtn {
  height: 40px;
}

@font-face {
  font-family: "bebas";
  src: url('font-family/bebas/BEBAS.woff') format('woff');
}

@font-face {
  font-family: "cairo";
  src: url('font-family/cairo/Cairoreg.ttf') format('truetype');
}

.servicebtn,
.contactbtn,
.careerbtn,
.aboutbtn {
  font-family: cairo;
  text-transform: capitalize;
}

.nav-item {
  background-color: black !important;
  border-radius: 10px 10px 0px 0px;
}

.nav-item:hover,
.nav-item:focus {
  background-color: #01FF9D !important;
  color: white;
  border-radius: 10px 10px 0px 0px;
}

.boder {
  background-color: grey !important;
  color: black;
}

.active:focus {
  background-color: #01FF9D !important;
  color: white !important;
}

.nav-link {
  color: white;
  border-radius: 10px 10px 0px 0px;
}

.nav-link:focus,
.nav-link:hover {
  color: white;
}

.nav-tabs .nav-item.show .nav-link,
.nav-tabs .nav-link.active {
  color: black;
  background-color: #01FF9D !important;
  border-color: transparent !important;
  border-radius: 10px 10px 0px 0px !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<ul class="nav nav-tabs header">
  <li class="nav-item">
    <i class="fas fa-chalkboard-teacher"></i> About Us
  </li>
  <li class="nav-item">
    <i class="fas fa-search"></i> Viewrify
  </li>
  <li class="nav-item">
    <i class="fa fa-user" aria-hidden="true"></i> Contact Us
  </li>
  <li class="nav-item">
    <i class="fa fa-camera" aria-hidden="true"></i> Careers
  </li>
</ul></code>```

Well in @media I removed it cause it's not working :/ and i don't have any idea how to do it, If i changed the width of the nav-items then it's still the same in the image

答:
It can easily be done with flexbox. Kindly try this

```<code>ul.nav.header {
    display: flex;
    flex-wrap: nowrap;
}
</code>```

Body:
I'm currently a beginner with web programming, I have a problem when the mobile screen changed then the navbar will go bottom, I don't see any good source codes of this problem since some of the people use hamburger style.

This is the current view of the mobile when im not changing it to smaller view

This is the view after changing the view to smaller size

Here is the code:

.servicebtn,
.contactbtn,
.careerbtn,
.aboutbtn {
  height: 40px;
}

@font-face {
  font-family: "bebas";
  src: url('font-family/bebas/BEBAS.woff') format('woff');
}

@font-face {
  font-family: "cairo";
  src: url('font-family/cairo/Cairoreg.ttf') format('truetype');
}

.servicebtn,
.contactbtn,
.careerbtn,
.aboutbtn {
  font-family: cairo;
  text-transform: capitalize;
}

.nav-item {
  background-color: black !important;
  border-radius: 10px 10px 0px 0px;
}

.nav-item:hover,
.nav-item:focus {
  background-color: #01FF9D !important;
  color: white;
  border-radius: 10px 10px 0px 0px;
}

.boder {
  background-color: grey !important;
  color: black;
}

.active:focus {
  background-color: #01FF9D !important;
  color: white !important;
}

.nav-link {
  color: white;
  border-radius: 10px 10px 0px 0px;
}

.nav-link:focus,
.nav-link:hover {
  color: white;
}

.nav-tabs .nav-item.show .nav-link,
.nav-tabs .nav-link.active {
  color: black;
  background-color: #01FF9D !important;
  border-color: transparent !important;
  border-radius: 10px 10px 0px 0px !important;
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

     About Us

     Viewrify

     Contact Us

     Careers

Well in @media I removed it cause it's not working :/ and i don't have any idea how to do it, If i changed the width of the nav-items then it's still the same in the image

Body:
It can easily be done with flexbox. Kindly try this

ul.nav.header {
    display: flex;
    flex-wrap: nowrap;
}


问:
Populate Dropdown from Zoho Response
I am trying to populate a dropdown from the ZOHO API response I am getting with my request. I have two files. request.php and zoho.php.

I am receiving the response from request.php as below.

```<code>object(stdClass)#2 (4) {
  ["code"]=>
  int(0)
  ["message"]=>
  string(7) "success"
  ["invoices"]=>
  array(200) {
    [0]=>
    object(stdClass)#3 (54) {
      ["invoice_id"]=>
      string(19) "2163791000003899301"
    }
  }
}
</code>```

in order to get the result I am decoding the object as below

```<code>$result = curl_exec($ch);
curl_close($ch);
$decode_data = json_decode($result);
var_dump($decode_data);
</code>```

I am having a popup in zoho.php.

```<code><select value="Select Zoho Invoice" name="zohoinvoice" id="zohoinvoice" class="SlectBox form-control">
   <?php echo zohoFunc(); ?>
</select>

function zohoFunc(){
   global $decode_data;
   $output='';
   $output .= '<option value = "Select Invoice">Select Invoice</option>';
   foreach($decode_data as $inv){
     $output[] .= '<option value = "'.$inv[0]->invoice_id.'">'.$inv[0]->invoice_number.'</option>';
   }
   return $output;
}
</code>```

The way I am looping the data I have received is below. I am trying to get as the way how we populate a dropdown from SQL which is a string and zoho's case its an array. Where I am making the mistake?

答:
You you are looking for all the invoices in your data set. So try.</p>
```<code>foreach($decode_data->invoices  as $myCurrentInvoice) {
    echo $myCurrentInvoice->invoice_id;
    echo '<br>';
    //$output[] .= '<option value = "'.$myCurrentInvoice->invoice_id.'">'.$myCurrentInvoice->invoice_number.'</option>';

}
</code>```

Title: Populate Dropdown from Zoho Response

Body:
I am trying to populate a dropdown from the ZOHO API response I am getting with my request. I have two files. request.php and zoho.php.

I am receiving the response from request.php as below.

object(stdClass)#2 (4) {
  ["code"]=>
  int(0)
  ["message"]=>
  string(7) "success"
  ["invoices"]=>
  array(200) {
    [0]=>
    object(stdClass)#3 (54) {
      ["invoice_id"]=>
      string(19) "2163791000003899301"
    }
  }
}

in order to get the result I am decoding the object as below

$result = curl_exec($ch);
curl_close($ch);
$decode_data = json_decode($result);
var_dump($decode_data);

I am having a popup in zoho.php.

<select value="Select Zoho Invoice" name="zohoinvoice" id="zohoinvoice" class="SlectBox form-control">
   <?php echo zohoFunc(); ?>
</select>

function zohoFunc(){
   global $decode_data;
   $output='';
   $output .= '<option value = "Select Invoice">Select Invoice</option>';
   foreach($decode_data as $inv){
     $output[] .= '<option value = "'.$inv[0]->invoice_id.'">'.$inv[0]->invoice_number.'</option>';
   }
   return $output;
}

The way I am looping the data I have received is below. I am trying to get as the way how we populate a dropdown from SQL which is a string and zoho's case its an array. Where I am making the mistake?

Body:
You you are looking for all the invoices in your data set. So try.

foreach($decode_data->invoices  as $myCurrentInvoice) {
    echo $myCurrentInvoice->invoice_id;
    echo '<br>';
    //$output[] .= '<option value = "'.$myCurrentInvoice->invoice_id.'">'.$myCurrentInvoice->invoice_number.'</option>';

}


问:
RMarkdown: is it possible to return a table and a chart from the same cell?
I write a function that takes some data and outputs a table and a plot. And I want to show the table and the plot one after the other.

But I can't seem to find a function in Rmarkdown that can do that and instead have to break it up into two.

E.g this is what I want to have

```<code>plot_and_table <- function(input_data) {
  output_data = ... do some to input_data
  plot = plot(.... something about output_data)
  list(plot, output_data)
}

plot_and_table(input_data)
</code>```

and have the plot plotted before printing the table in the same flow.

答:
Consider using patchwork?

```<code>library(patchwork)
plot_and_table <- function(input_data){
    output_data = input_data[1:5, c('mpg', 'disp')]

    p1 <- ggplot(output_data) +
        geom_point(aes(mpg, disp)) +
        ggtitle('Plot 1')
    p2 <- gridExtra::tableGrob(output_data)
 return(p1/p2)
}

plot_and_table(mtcars)

</code>```

Body:
I write a function that takes some data and outputs a table and a plot. And I want to show the table and the plot one after the other.

But I can't seem to find a function in Rmarkdown that can do that and instead have to break it up into two.

E.g this is what I want to have

plot_and_table <- function(input_data) {
  output_data = ... do some to input_data
  plot = plot(.... something about output_data)
  list(plot, output_data)
}

plot_and_table(input_data)

and have the plot plotted before printing the table in the same flow.

Body:
Consider using patchwork?

library(patchwork)
plot_and_table <- function(input_data){
    output_data = input_data[1:5, c('mpg', 'disp')]

    p1 <- ggplot(output_data) +
        geom_point(aes(mpg, disp)) +
        ggtitle('Plot 1')
    p2 <- gridExtra::tableGrob(output_data)
 return(p1/p2)
}

plot_and_table(mtcars)


问:
ClassNotFoundException: java.security.acl.Group on WildFly 19.1 using Java 14
I migrated a Web application that worked fine on WildFly 17 on Java 11 to the latest versions of both: WildFly 19 on Java 14. In the end I'm getting a ClassNotFoundException: java.security.acl.Group, probably because the Web application uses JAAS.

Note that a similar Web application built following a tutorial of my own worked fine, but it doesn't use JAAS. That and the package java.security.acl made me think JAAS is related.

Searching the Web I found issue WFCORE-4282 at WildFly's JIRA which seems to imply that although they knew this java.security.acl.Group class was deprecated more than a year ago, WildFly 19 still requires it and Java 14 did actually remove it, thus causing the ClassNotFoundException for me.

Is my interpretation correct? Does WildFly 19 + Java 14 + JAAS = ClassNotFoundException necessarily or has anyone managed to make it work? Or maybe I'm doing something wrong? It just seems to me such a huge problem for JBoss to have overlooked on WildFly...

Update: I removed Java 14, installed Java 13, reinstalled Eclipse and WildFly and redeployed de application and it worked, so WildFly 19 + Java 13 + JAAS = OK!

答:
This has been resolved as of late 2021 (better late than never!). So you can now use JDK 17+ with WildFly 26+. Note, however, you have to make the non-trivial move from:

```<code><subsystem xmlns="urn:jboss:domain:security:1.2">
...
<login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" flag="required">
...
</login-module>
</subsystem>
</code>```

...to...

```<code><subsystem xmlns="urn:wildfly:elytron:15.0">
...
<security-realms>
    <jdbc-realm>
    ...
    </jdbc-realm>
</security-realms>
</subsystem>
</code>```

YMMV depending on your architecture, but basically you have to embrace Elytron.

Body:
This has been resolved as of late 2021 (better late than never!). So you can now use JDK 17+ with WildFly 26+. Note, however, you have to make the non-trivial move from:

<subsystem xmlns="urn:jboss:domain:security:1.2">
...
<login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" flag="required">
...
</login-module>
</subsystem>

...to...

<subsystem xmlns="urn:wildfly:elytron:15.0">
...
<security-realms>
    <jdbc-realm>
    ...
    </jdbc-realm>
</security-realms>
</subsystem>

YMMV depending on your architecture, but basically you have to embrace Elytron.


问:
Is there method able to block some blocks until some conditions satisfied?
I want to block some blocks until one variable is set to a particular value. So I write this code to test if a simple do-while loop will work.

```<code>__device__ int tag = 0;
__global__ void kernel() {
    if ( threadIdx.x == 0 ) {
        volatile int v;
        do {
            v = tag;
        }
        while ( v == 0 );
    }
    __syncthreads();
    return ;
}
</code>```

However, it doesn't work(No dead loop occurs, very strange).

I want to ask if any other method is able to block some blocks until some conditions satisfied or if some changes on the code will work.

答:
Here is a hackish way I tried to see if it will work.

```<code>#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_runtime_api.h>

__global__ static
void kernel(int *count, float *data)
{
    count += threadIdx.x;
    data += gridDim.x * threadIdx.x;
    int i = blockIdx.x;
    if (i < gridDim.x - 1) {
        data[i] = i + 1;
        atomicAdd(count, 1);
        return;
    }

    while (atomicMin(count, i) != i);

    float tmp = i + 1;
    for (int j = 0; j < i; j++) tmp += data[j];

    data[i] = tmp;
}

int main(int argc, char **args)
{
        int num = 100;
    if (argc >= 2) num = atoi(args[1]);

    int bytes = num * sizeof(float) * 32;
    float *d_data; cudaMalloc((void **)&d_data, bytes);
    float *h_data = (float *)malloc(bytes);
    for (int i = 0; i < 32 * num; i++) h_data[i] = -1; // Being safe

    int h_count[32] = {1};
    int *d_count; cudaMalloc((void **)&d_count, 32 * sizeof(int));
    cudaMemcpy(d_count, &h_count, 32 * sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_data, h_data, bytes, cudaMemcpyHostToDevice);
    kernel<<<num, 32>>>(d_count, d_data);
    cudaMemcpy(&h_count, d_count, 32 * sizeof(int), cudaMemcpyDeviceToHost);
    cudaMemcpy(h_data, d_data, bytes, cudaMemcpyDeviceToHost);

    for (int i = 0; i < 32; i++) {
        printf("sum of first %d from thread %d is %d \n", num, i, (int)h_data[num -1]);
        h_data += num;
    }

    cudaFree(d_count);
    cudaFree(d_data);
    free(h_data - num * 32);
}
</code>```

I can not guarantee this will always work. But the breaking point on my card (320M) seems to be for num = 5796. Perhaps a hardware limit of some kind different for each card ?

EDIT

The answer to this is that n * (n + 1) / 2 > 2^24 for n > 5795 (which is the single precision limit). The accuracy of integer values beyond this point is undefined. Thanks to talonmies for pointing it out.

```<code>./a.out 5795
sum of first 5795 from thread 0 is 16793910
sum of first 5795 from thread 1 is 16793910
sum of first 5795 from thread 2 is 16793910
sum of first 5795 from thread 3 is 16793910
sum of first 5795 from thread 4 is 16793910
sum of first 5795 from thread 5 is 16793910
sum of first 5795 from thread 6 is 16793910
sum of first 5795 from thread 7 is 16793910
sum of first 5795 from thread 8 is 16793910
sum of first 5795 from thread 9 is 16793910
sum of first 5795 from thread 10 is 16793910
sum of first 5795 from thread 11 is 16793910
sum of first 5795 from thread 12 is 16793910
sum of first 5795 from thread 13 is 16793910
sum of first 5795 from thread 14 is 16793910
sum of first 5795 from thread 15 is 16793910
sum of first 5795 from thread 16 is 16793910
sum of first 5795 from thread 17 is 16793910
sum of first 5795 from thread 18 is 16793910
sum of first 5795 from thread 19 is 16793910
sum of first 5795 from thread 20 is 16793910
sum of first 5795 from thread 21 is 16793910
sum of first 5795 from thread 22 is 16793910
sum of first 5795 from thread 23 is 16793910
sum of first 5795 from thread 24 is 16793910
sum of first 5795 from thread 25 is 16793910
sum of first 5795 from thread 26 is 16793910
sum of first 5795 from thread 27 is 16793910
sum of first 5795 from thread 28 is 16793910
sum of first 5795 from thread 29 is 16793910
sum of first 5795 from thread 30 is 16793910
sum of first 5795 from thread 31 is 16793910
</code>```

--

I edited my former code which was using just one block. This is more representative of a real world threads / blocks (the memory accesses are weird and will be slow as hell, but they were done to quickly port my old test code to use multiple threads).

Looks like there are some cases when you can synchronize across blocks, but mostly depends on you knowing certain things before hand (for this particular case, I was only syncing n - 1 blocks before performing an insanely useless count on the last block).

This is a proof of concept only, do not take the code seriously

Body:
I want to block some blocks until one variable is set to a particular value. So I write this code to test if a simple do-while loop will work.

__device__ int tag = 0;
__global__ void kernel() {
    if ( threadIdx.x == 0 ) {
        volatile int v;
        do {
            v = tag;
        }
        while ( v == 0 );
    }
    __syncthreads();
    return ;
}

However, it doesn't work(No dead loop occurs, very strange).

I want to ask if any other method is able to block some blocks until some conditions satisfied or if some changes on the code will work.

Body:
Here is a hackish way I tried to see if it will work.

#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_runtime_api.h>

__global__ static
void kernel(int *count, float *data)
{
    count += threadIdx.x;
    data += gridDim.x * threadIdx.x;
    int i = blockIdx.x;
    if (i < gridDim.x - 1) {
        data[i] = i + 1;
        atomicAdd(count, 1);
        return;
    }

    while (atomicMin(count, i) != i);

    float tmp = i + 1;
    for (int j = 0; j < i; j++) tmp += data[j];

    data[i] = tmp;
}

int main(int argc, char **args)
{
        int num = 100;
    if (argc >= 2) num = atoi(args[1]);

    int bytes = num * sizeof(float) * 32;
    float *d_data; cudaMalloc((void **)&d_data, bytes);
    float *h_data = (float *)malloc(bytes);
    for (int i = 0; i < 32 * num; i++) h_data[i] = -1; // Being safe

    int h_count[32] = {1};
    int *d_count; cudaMalloc((void **)&d_count, 32 * sizeof(int));
    cudaMemcpy(d_count, &h_count, 32 * sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_data, h_data, bytes, cudaMemcpyHostToDevice);
    kernel<<<num, 32>>>(d_count, d_data);
    cudaMemcpy(&h_count, d_count, 32 * sizeof(int), cudaMemcpyDeviceToHost);
    cudaMemcpy(h_data, d_data, bytes, cudaMemcpyDeviceToHost);

    for (int i = 0; i < 32; i++) {
        printf("sum of first %d from thread %d is %d \n", num, i, (int)h_data[num -1]);
        h_data += num;
    }

    cudaFree(d_count);
    cudaFree(d_data);
    free(h_data - num * 32);
}

I can not guarantee this will always work. But the breaking point on my card (320M) seems to be for num = 5796. Perhaps a hardware limit of some kind different for each card ?

EDIT

The answer to this is that n * (n + 1) / 2 > 2^24 for n > 5795 (which is the single precision limit). The accuracy of integer values beyond this point is undefined. Thanks to talonmies for pointing it out.

./a.out 5795
sum of first 5795 from thread 0 is 16793910
sum of first 5795 from thread 1 is 16793910
sum of first 5795 from thread 2 is 16793910
sum of first 5795 from thread 3 is 16793910
sum of first 5795 from thread 4 is 16793910
sum of first 5795 from thread 5 is 16793910
sum of first 5795 from thread 6 is 16793910
sum of first 5795 from thread 7 is 16793910
sum of first 5795 from thread 8 is 16793910
sum of first 5795 from thread 9 is 16793910
sum of first 5795 from thread 10 is 16793910
sum of first 5795 from thread 11 is 16793910
sum of first 5795 from thread 12 is 16793910
sum of first 5795 from thread 13 is 16793910
sum of first 5795 from thread 14 is 16793910
sum of first 5795 from thread 15 is 16793910
sum of first 5795 from thread 16 is 16793910
sum of first 5795 from thread 17 is 16793910
sum of first 5795 from thread 18 is 16793910
sum of first 5795 from thread 19 is 16793910
sum of first 5795 from thread 20 is 16793910
sum of first 5795 from thread 21 is 16793910
sum of first 5795 from thread 22 is 16793910
sum of first 5795 from thread 23 is 16793910
sum of first 5795 from thread 24 is 16793910
sum of first 5795 from thread 25 is 16793910
sum of first 5795 from thread 26 is 16793910
sum of first 5795 from thread 27 is 16793910
sum of first 5795 from thread 28 is 16793910
sum of first 5795 from thread 29 is 16793910
sum of first 5795 from thread 30 is 16793910
sum of first 5795 from thread 31 is 16793910

--

I edited my former code which was using just one block. This is more representative of a real world threads / blocks (the memory accesses are weird and will be slow as hell, but they were done to quickly port my old test code to use multiple threads).

Looks like there are some cases when you can synchronize across blocks, but mostly depends on you knowing certain things before hand (for this particular case, I was only syncing n - 1 blocks before performing an insanely useless count on the last block).

This is a proof of concept only, do not take the code seriously


问:
I can't install anything with pip
i tried installing numPy using this command

$  pip install numpy

and this is what i get

Fatal error in launcher: Unable to create process using '"C:\Python310\python.exe"  "C:\Python310\Scripts\pip.exe" install numpy': The system cannot find the file specified.

答:
Because the path of pip is not "C:\Python310\Scripts\pip.exe"
You can install numpy with python -m pip install numpy, or download pip in https://bootstrap.pypa.io/get-pip.py and run python get-pip.py to install pip, after that you can install package with pip install numpy

Title: I can't install anything with pip


问:
Send AWS API Gateway Key Name to Server
Let's say I have an AWS API Gateway.  I have a resource in said gateway that requires the use of a gateway API Key.  I would like my server to know which of my various keys are being used to authenticate (just for logging; there's no access control happening based on this).

How do I include the name of the gateway API Key in the request that is being sent to the server?

答:
Firstly, you mentioned logging which keys are used for authentication. API GW API Keys are intended to be used with usage plans, not authentication/authorization (link).

For user authentication and authorization, don't use API keys. Use an IAM role, a Lambda authorizer, or an Amazon Cognito user pool.

I think it is because of this reason, AWS does not forward the key further to the backend. Furthermore, if you have used one of the authorizers like Lambda or Cognito, your backend will have a way to log the authenticated identity.

If you really want to log the API keys though, I think you can use a mapping template to explicitly tell API GW to forward the x-api-key header.

Title: Send AWS API Gateway Key Name to Server


问:
No connection is available to service this operation (Redis Client )
My app is hosted in azure and i am using azure redis cache.

RedisClient version
Redis.StrongName - 1.2.6
.Net Core - 2.1
.Net Framework 4.7.1

My app is getting intermittent Redis Connection exception, and it gets resolved once i restart the app service.
I have 1 - secondary and 1 - primary instance, which Redis cache of 6GB capacity

This is exception i got from my client

outer message:
No connection is available to service this operation: HSETNX KEYNAME; SocketClosed on MY REDIS SERVER NAME/Interactive, origin: ProcessReadBytes, input-buffer: 0, outstanding: 0, last-read: 0s ago, last-write: 0s ago, unanswered-write: 280531s ago, keep-alive: 60s, pending: 0, state: ConnectedEstablished, in: 0, ar: 0, last-heartbeat: 0s ago, last-mbeat: 0s ago, global: 0s ago, mgr: Inactive, err: never; IOCP: (Busy=1,Free=999,Min=8,Max=1000), WORKER: (Busy=1,Free=32766,Min=8,Max=32767), Local-CPU: n/a

Inner Message:
SocketClosed on MY REDIS SERVER NAME/Interactive, origin: ProcessReadBytes, input-buffer: 0, outstanding: 0, last-read: 0s ago, last-write: 0s ago, unanswered-write: 280531s ago, keep-alive: 60s, pending: 0, state: ConnectedEstablished, in: 0, ar: 0, last-heartbeat: 0s ago, last-mbeat: 0s ago, global: 0s ago, mgr: Inactive, err: never

Not sure what went wrong, it is resolved once I restarted the app service.

Please guide me on
What went wrong?
How to debug Redis exceptions?
How to interpret the exception messages?

I referred some already posted issues in stackexchange.Redis, but nothing providing good info on the root cause of this issue
https://github.com/StackExchange/StackExchange.Redis/issues/559

My CPU percentage and Redis Server Load, looks fine no anomolies

need to find out the root cause what went wrong and

答:
Under Azure portal check the connected clients while performing any operations on Redis. In my case, I was sending around 4k request without disposing the object which results in socket failure. After implementing IDisposable interface, I am able to process 10k/20k request without any issue

Update your connection string

Set abortConnect to false

Adjust your syncTimeout and asyncTimeout as needed.

If you are using a secure TLS connection set the ssl=True,sslprotocols=tls12 in your configuration to force it to the latest version.

Upgrade your StackExchange.Redis nuget package to latest if you can.

Set the config option for ReconnectRetryPolicy in your C# code to be ExponentialRetry
https://stackexchange.github.io/StackExchange.Redis/Configuration.html#reconnectretrypolicy

```<code>private static readonly Lazy<ConfigurationOptions> configOptions  = new Lazy<ConfigurationOptions>(() =>
{
    var connections = ConfigurationManager.ConnectionStrings["redis-connection"].ConnectionString;
    var configOptions = ConfigurationOptions.Parse(connections);

    configOptions.ClientName = "MyApp-RedisCacheProvider";
    //configOptions.SyncTimeout = 100000; // don`t do this in code, set it in your connection string
    //configOptions.AbortOnConnectFail = false; // don`t do this in code, set it in your connection string

    /*
     * The default is LinearRetry which can cause congestion at virtually the same time on multiple parallel threads.
     * Use ExponentialRetry so that a degree of randomness is used in the timing across multiple threads.
     */
    configOptions.ReconnectRetryPolicy = new ExponentialRetry(5000, 10000);

    return configOptions;
});

 private static readonly Lazy<ConnectionMultiplexer> connection = new Lazy<ConnectionMultiplexer>(
         () => ConnectionMultiplexer.Connect(configOptions.Value));
</code>```

Implement IDisposable to dispose the object after its use

```<code>     public void Dispose()
     {
         try {
             if (connection.IsValueCreated)
             {
                 connection.Value.Dispose();
             }
         } catch { }
     }
</code>```

Body:
Under Azure portal check the connected clients while performing any operations on Redis. In my case, I was sending around 4k request without disposing the object which results in socket failure. After implementing IDisposable interface, I am able to process 10k/20k request without any issue

Update your connection string

Set abortConnect to false

Adjust your syncTimeout and asyncTimeout as needed.

If you are using a secure TLS connection set the ssl=True,sslprotocols=tls12 in your configuration to force it to the latest version.

Upgrade your StackExchange.Redis nuget package to latest if you can.

Set the config option for ReconnectRetryPolicy in your C# code to be ExponentialRetry
https://stackexchange.github.io/StackExchange.Redis/Configuration.html#reconnectretrypolicy

private static readonly Lazy<ConfigurationOptions> configOptions  = new Lazy<ConfigurationOptions>(() =>
{
    var connections = ConfigurationManager.ConnectionStrings["redis-connection"].ConnectionString;
    var configOptions = ConfigurationOptions.Parse(connections);

    configOptions.ClientName = "MyApp-RedisCacheProvider";
    //configOptions.SyncTimeout = 100000; // don`t do this in code, set it in your connection string
    //configOptions.AbortOnConnectFail = false; // don`t do this in code, set it in your connection string

    /*
     * The default is LinearRetry which can cause congestion at virtually the same time on multiple parallel threads.
     * Use ExponentialRetry so that a degree of randomness is used in the timing across multiple threads.
     */
    configOptions.ReconnectRetryPolicy = new ExponentialRetry(5000, 10000);

    return configOptions;
});

 private static readonly Lazy<ConnectionMultiplexer> connection = new Lazy<ConnectionMultiplexer>(
         () => ConnectionMultiplexer.Connect(configOptions.Value));

Implement IDisposable to dispose the object after its use

     public void Dispose()
     {
         try {
             if (connection.IsValueCreated)
             {
                 connection.Value.Dispose();
             }
         } catch { }
     }


问:
ERROR CREATING REACT APP WITH npx create-react-app
it won't let me install react because this error comes out
i am trying to install react but i get this error message

```<code>npm ERR! code ERR_SOCKET_TIMEOUT

npm ERR! errno ERR_SOCKET_TIMEOUT

npm ERR! network Invalid response body while trying to fetch https://registry.npmjs.org/html-webpack-plugin: Socket timeout

npm ERR! network This is a problem related to network connectivity.

npm ERR! network In most cases you are behind a proxy or have bad network settings.

npm ERR! network

npm ERR! network If you are behind a proxy, please make sure that the

npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:

npm ERR!     C:\Users\Hector\AppData\Local\npm-cache\_logs\2022-02-08T01_35_21_593Z-debug-0.log

Aborting installation.
  npm install --no-audit --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed.

</code>```

I already tried clearing the cache

答: Try npx create-react-app client. The word client can be replaced with any word you would like to be the name of your folder.

Body:
it won't let me install react because this error comes out
i am trying to install react but i get this error message

npm ERR! code ERR_SOCKET_TIMEOUT

npm ERR! errno ERR_SOCKET_TIMEOUT

npm ERR! network Invalid response body while trying to fetch https://registry.npmjs.org/html-webpack-plugin: Socket timeout

npm ERR! network This is a problem related to network connectivity.

npm ERR! network In most cases you are behind a proxy or have bad network settings.

npm ERR! network

npm ERR! network If you are behind a proxy, please make sure that the

npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:

npm ERR!     C:\Users\Hector\AppData\Local\npm-cache\_logs\2022-02-08T01_35_21_593Z-debug-0.log

Aborting installation.
  npm install --no-audit --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed.

I already tried clearing the cache


问:
Multiple figures in a single window
I want to create a function which plot on screen a set of figures in a single window. By now I write this code:

```<code>import pylab as pl

def plot_figures(figures):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary

    """
    for title in figures:
        pl.figure()
        pl.imshow(figures[title])
        pl.gray()
        pl.title(title)
        pl.axis('off')
</code>```

It works perfectly but I would like to have the option for plotting all the figures in single window. And this code doesn't. I read something about subplot but it looks quite tricky.

答:
import numpy as np

def save_image(data, ws=0.1, hs=0.1, sn='save_name'):
    import matplotlib.pyplot as plt
    m = n = int(np.sqrt(data.shape[0])) # (36, 1, 32, 32)

    fig, ax = plt.subplots(m,n, figsize=(m*6,n*6))
    ax = ax.ravel()
    for i in range(data.shape[0]):
        ax[i].matshow(data[i,0,:,:])
        ax[i].set_xticks([])
        ax[i].set_yticks([])

    plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9,
                        top=0.9, wspace=ws, hspace=hs)
    plt.tight_layout()
    plt.savefig('{}.png'.format(sn))

data = np.load('img_test.npy')

save_image(data, ws=0.1, hs=0.1, sn='multiple_plot')
```

Title: Multiple figures in a single window

Body:
I want to create a function which plot on screen a set of figures in a single window. By now I write this code:

import pylab as pl

def plot_figures(figures):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary

    """
    for title in figures:
        pl.figure()
        pl.imshow(figures[title])
        pl.gray()
        pl.title(title)
        pl.axis('off')

It works perfectly but I would like to have the option for plotting all the figures in single window. And this code doesn't. I read something about subplot but it looks quite tricky.


问:
How to correctly use jq's in() function
I'm trying to understand in() function of jq.

https://jqplay.org/s/BR1KbCjP8u

```<code>filter:
map( in(["ms", "is", "bad"]) )
input:
["apple","is","bad"]
</code>```

I expected the output [false,true,true] because for each element of the input array:

"apple" is not in ["ms", "is", "bad"] so false

"is" is in ["ms", "is", "bad"] so true

"bad" is in ["ms", "is", "bad"] so true

Obviously this is wrong because I get error:

```<code>jq: error (at <stdin>:0): Cannot check whether array has a string key
exit status 5
</code>```

What is wrong with this and how to correctly use the in() function when passing ["ms","is","bad"] in the filter? I want to check if each element in the input array is found in this list.

答:
Maybe you were looking for the IN (not in) function. Also, it takes a stream of elements, not an array.

```<code>map(IN("ms", "is", "bad"))
</code>```

[false,true,true]
```

Demo

From the manual:

in

The builtin function in returns whether or not the input key is in the given object, or the input index corresponds to an element in the given array. It is, essentially, an inversed version of has.

IN

This builtin outputs true if . appears in the given stream, otherwise it outputs false.

Title: How to correctly use jq's in() function

Body:
I'm trying to understand in() function of jq.

https://jqplay.org/s/BR1KbCjP8u

filter:
map( in(["ms", "is", "bad"]) )
input:
["apple","is","bad"]

I expected the output [false,true,true] because for each element of the input array:

"apple" is not in ["ms", "is", "bad"] so false

"is" is in ["ms", "is", "bad"] so true

"bad" is in ["ms", "is", "bad"] so true

Obviously this is wrong because I get error:

jq: error (at <stdin>:0): Cannot check whether array has a string key
exit status 5

What is wrong with this and how to correctly use the in() function when passing ["ms","is","bad"] in the filter? I want to check if each element in the input array is found in this list.

Body:
Maybe you were looking for the IN (not in) function. Also, it takes a stream of elements, not an array.

map(IN("ms", "is", "bad"))

[false,true,true]

Demo

From the manual:

in

The builtin function in returns whether or not the input key is in the given object, or the input index corresponds to an element in the given array. It is, essentially, an inversed version of has.

IN

This builtin outputs true if . appears in the given stream, otherwise it outputs false.


问:
How to determine if a pandas column type can be reduced from int64 to int32 or from float64 to float32?
I have a dataframe which is huge(8 gb). I am trying to find if i will loose any information if i downsize the columns from int64 to int32 or from float64 to float32.

How to find out if the information in dataframe will be lost or not in conversion?

答:
I have a dataframe which is huge(8 gb). I am trying to find if i will loose any information if i downsize the columns from int64 to int32 ...

The simplest way to cast integers to a smaller type and make sure that you are not losing information is to use

```<code>df['col'] = pd.to_numeric(df['col'], downcast='integer')
</code>```

This will both do the conversion, and check that the conversion didn't lose data. You'll need to do that for each integer column in your dataframe.

... or from float64 to float32.

Casting a number to a smaller floating point number always loses some information, unless you are dealing with an exact binary fraction. In practice, you can use 32-bit float if you need around 7 digits or fewer of precision.

Body:
I have a dataframe which is huge(8 gb). I am trying to find if i will loose any information if i downsize the columns from int64 to int32 ...

The simplest way to cast integers to a smaller type and make sure that you are not losing information is to use

df['col'] = pd.to_numeric(df['col'], downcast='integer')

This will both do the conversion, and check that the conversion didn't lose data. You'll need to do that for each integer column in your dataframe.

... or from float64 to float32.

Casting a number to a smaller floating point number always loses some information, unless you are dealing with an exact binary fraction. In practice, you can use 32-bit float if you need around 7 digits or fewer of precision.


问:
How to get user_id f,facebook_id: ,facebook_access_token usin new facebook sdk
Now new facebook sdk support oath concept. so i am confuse to getting these variable.
Any help or documentation will be appreciated. </p>

答:
Here is a link to the appropriate doc.

https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

You should be able to access:

```<code>{
status: 'connected',
authResponse: {
    access_token: '...',
    expiresIn:'...',
    signedRequest:'...',
    userID:'...'
}
}
</code>```

Body:
Here is a link to the appropriate doc.

https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

You should be able to access:

{
status: 'connected',
authResponse: {
    access_token: '...',
    expiresIn:'...',
    signedRequest:'...',
    userID:'...'
}
}


问:
Why is my csv file not printing after I import it?
```<code>import pandas as pd
tbl1 = pd.import_csv('sample_prices.csv')
tbl1.print()
</code>```

and still not receiving anything? It does not even come up with an error.

答:
pd.import_csv doesn't exist. You probably meant to use pd.read_csv instead.

```<code>import pandas as pd
tbl1 = pd.read_csv('sample_prices.csv')
tbl1.print()
</code>```

That said, I'm not sure why it wouldn't raise an error...

If you have a custom function called import_csv, you'll want to call it like this:

```<code>import pandas as pd
tbl1 = import_csv('sample_prices.csv')
tbl1.print()
</code>```

...without the pd. prefix.

Body:
import pandas as pd
tbl1 = pd.import_csv('sample_prices.csv')
tbl1.print()

and still not receiving anything? It does not even come up with an error.

Body:
pd.import_csv doesn't exist. You probably meant to use pd.read_csv instead.

import pandas as pd
tbl1 = pd.read_csv('sample_prices.csv')
tbl1.print()

That said, I'm not sure why it wouldn't raise an error...

If you have a custom function called import_csv, you'll want to call it like this:

import pandas as pd
tbl1 = import_csv('sample_prices.csv')
tbl1.print()

...without the pd. prefix.


问:
How can I refactor my code to return a collection of dictionaries?
```<code>def read_data(service_client):
    data = list_data(domain, realm) # This returns a data frame
    building_data = []
    building_names = {}
    all_buildings = {}

    for elem in data.iterrows():
        building = elem[1]['building_name']
        region_id = elem[1]['region_id']
        bandwith = elem[1]['bandwith']
        building_id = elem[1]['building_id']

       return {
       'Building': building,
       'Region Id': region_id,
       'Bandwith': bandwith,
       'Building Id': building_id,
       }
</code>```

Basically I am able to return a single dictionary value upon a iteration here in this example. I have tried printing it as well and others.

I am trying to find a way to store multiple dictionary values on each iteration and return it, instead of just returning one.. Does anyone know any ways to achieve this?

答:
You may replace your for-loop with the following to get all dictionaries in a list.

```<code>naming = {
    'building_name': 'Building',
    'region_id': 'Region Id',
    'bandwith': 'Bandwith',
    'building_id': 'Building Id',
}

return [
    row[list(naming.values())].to_dict()
        for idx, row in data.rename(naming, axis=1).iterrows()
]
</code>```

Body:
def read_data(service_client):
    data = list_data(domain, realm) # This returns a data frame
    building_data = []
    building_names = {}
    all_buildings = {}

    for elem in data.iterrows():
        building = elem[1]['building_name']
        region_id = elem[1]['region_id']
        bandwith = elem[1]['bandwith']
        building_id = elem[1]['building_id']

       return {
       'Building': building,
       'Region Id': region_id,
       'Bandwith': bandwith,
       'Building Id': building_id,
       }

Basically I am able to return a single dictionary value upon a iteration here in this example. I have tried printing it as well and others.

I am trying to find a way to store multiple dictionary values on each iteration and return it, instead of just returning one.. Does anyone know any ways to achieve this?

Body:
You may replace your for-loop with the following to get all dictionaries in a list.

naming = {
    'building_name': 'Building',
    'region_id': 'Region Id',
    'bandwith': 'Bandwith',
    'building_id': 'Building Id',
}

return [
    row[list(naming.values())].to_dict()
        for idx, row in data.rename(naming, axis=1).iterrows()
]


问:
How to fill in a property in a collection with help of stream operators?
I have two lists of objects builders of type Builder and adminUsers of type AdminUser.

Here are type defenitions of the classes:

```<code>public class Builder {
    @Id
    private String id;
    private String name;
    @Field("company_name")
    private String companyName;
    @Indexed(unique=true)
    private String email;
    private UserRole userRole;
}

public class AdminUser {
    @Id
    private String id;
    @Indexed(unique=true)
    private String email;
    private List<GrantedAuthority> authorities;
}

public enum UserRole {
    ROLE_ADMIN,
    ROLE_DATA,
    ROLE_BUILDER
}
</code>```

I try to fill property which is called UserRole of the builders collection
with a UserRole property from adminUser collection of each item in builders collection.

Here is how I am doing it in imperative attitude:

```<code>List<Builder> builders = builderRepository.findAllBy();
List<AdminUser> adminUsers = adminUserRepository.findAllBy();

for (Builder builder : builders) {
    for (AdminUser adminUser : adminUsers) {

        if (builder.getEmail().equals(adminUser.getEmail()))
            builder.setUserRole(UserRole.valueOf(adminUser.getAuthorities().get(0).getAuthority()));
    }
}
</code>```

The code above works.

I tried to achieve the same with a declarative attitude with streams operators.
But I got confused and ended up writing it the good old imperative way.
Could you help me and show me an example of how the code above can be written with help of streams and intermediate operators, in a declarative way?

答:
Streams can be used for filtering, transformation, or some other operation. Generally, one or more collections are converted to other collections, or the size of a collection is changed. However, in your example, there is no collection conversion or size change. At most, replace the for loop in your example with forEach, but it doesn't make sense.

When the number of Builders and AdminUsers is large, the complexity of this code is O(n^2). You can use hash to reduce complexity.

```<code>Map<String, String> emailAuthMap = adminUsers.stream()
                .collect(Collectors.toMap(AdminUser::getEmail, u -> u.getAuthorities().size() > 0 ? u.getAuthorities().get(0).getAuthority() : null));
for (Builder builder : builders) {
    String auth = emailAuthMap.get(builder.getUserRole());
    builder.setUserRole(auth != null ? UserRole.valueOf(auth) : null);
}
</code>```

Body:
I have two lists of objects builders of type Builder and adminUsers of type AdminUser.

Here are type defenitions of the classes:

public class Builder {
    @Id
    private String id;
    private String name;
    @Field("company_name")
    private String companyName;
    @Indexed(unique=true)
    private String email;
    private UserRole userRole;
}

public class AdminUser {
    @Id
    private String id;
    @Indexed(unique=true)
    private String email;
    private List<GrantedAuthority> authorities;
}

public enum UserRole {
    ROLE_ADMIN,
    ROLE_DATA,
    ROLE_BUILDER
}

I try to fill property which is called UserRole of the builders collection
with a UserRole property from adminUser collection of each item in builders collection.

Here is how I am doing it in imperative attitude:

List<Builder> builders = builderRepository.findAllBy();
List<AdminUser> adminUsers = adminUserRepository.findAllBy();

for (Builder builder : builders) {
    for (AdminUser adminUser : adminUsers) {

        if (builder.getEmail().equals(adminUser.getEmail()))
            builder.setUserRole(UserRole.valueOf(adminUser.getAuthorities().get(0).getAuthority()));
    }
}

The code above works.

I tried to achieve the same with a declarative attitude with streams operators.
But I got confused and ended up writing it the good old imperative way.
Could you help me and show me an example of how the code above can be written with help of streams and intermediate operators, in a declarative way?

Body:
Streams can be used for filtering, transformation, or some other operation. Generally, one or more collections are converted to other collections, or the size of a collection is changed. However, in your example, there is no collection conversion or size change. At most, replace the for loop in your example with forEach, but it doesn't make sense.

When the number of Builders and AdminUsers is large, the complexity of this code is O(n^2). You can use hash to reduce complexity.

Map<String, String> emailAuthMap = adminUsers.stream()
                .collect(Collectors.toMap(AdminUser::getEmail, u -> u.getAuthorities().size() > 0 ? u.getAuthorities().get(0).getAuthority() : null));
for (Builder builder : builders) {
    String auth = emailAuthMap.get(builder.getUserRole());
    builder.setUserRole(auth != null ? UserRole.valueOf(auth) : null);
}


问:
How to generate a string of random characters from a given list of characters?
How can I generate a string of random characters from a given list of characters?

Private Sub Command0_Click()
    Dim pool As String
    pool = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Dim count
    count = 0
    result.Text = ""
    Randomize
    Dim cc
    cc As New Rnd
    Dim strpos
    strpos = ""
    While count <= Lengthh.Text
        strpos = cc.Next(0, pool.length)
        result.Text = result.Text & pool(strpos)
        count = count + 1
    Wend
End Sub
```

答:
For those wanting speed, you would want to avoid string concatenation with &.  Concatenation can be done much faster with an array of characters and Join(), as documented in the answer to this question.

The function below skips Join() and uses byte arrays for an additional speed boost (for more on that, see this answer).

```<code>Function RandStringFromPool(stringLength As Long, charPool As String) As String

    Randomize
    Dim returnByteArray() As Byte
    Dim poolByteArray() As Byte: poolByteArray = StrConv(charPool, vbFromUnicode)
    Dim poolSize As Long: poolSize = Len(charPool)

    ReDim returnByteArray(0 To stringLength * 2 - 1)
    For i = 0 To UBound(returnByteArray) Step 2
        returnByteArray(i) = poolByteArray(Int(Rnd() * poolSize))
    Next
    RandStringFromPool = returnByteArray

End Function
</code>```

Body:
For those wanting speed, you would want to avoid string concatenation with &.  Concatenation can be done much faster with an array of characters and Join(), as documented in the answer to this question.

The function below skips Join() and uses byte arrays for an additional speed boost (for more on that, see this answer).

Function RandStringFromPool(stringLength As Long, charPool As String) As String

    Randomize
    Dim returnByteArray() As Byte
    Dim poolByteArray() As Byte: poolByteArray = StrConv(charPool, vbFromUnicode)
    Dim poolSize As Long: poolSize = Len(charPool)

    ReDim returnByteArray(0 To stringLength * 2 - 1)
    For i = 0 To UBound(returnByteArray) Step 2
        returnByteArray(i) = poolByteArray(Int(Rnd() * poolSize))
    Next
    RandStringFromPool = returnByteArray

End Function


问:
C++ cannot open source file
In C++ with Visual studio 2017,

I copied some header files into my project folder, then added them under the "solution explorer" in c++. Now when I write

```<code>#include "name.h"
</code>```

it prints an error under include, and says "cannot open source file".

Why, and what can I potentially do to fix it?

I only just downloaded VS and am learning c++ for the first time.

答: For anyone still scratching their heads, you're not "supposed to" #include your own headerfiles with triangle quotes (<>), You're supposed to use "Quotation marks". It is a common mistake.</p>

Title: C++ cannot open source file

Body:
In C++ with Visual studio 2017,

I copied some header files into my project folder, then added them under the "solution explorer" in c++. Now when I write

#include "name.h"

it prints an error under include, and says "cannot open source file".

Why, and what can I potentially do to fix it?

I only just downloaded VS and am learning c++ for the first time.


问:
Map within a map in react, getting unexpected token expected ","
I'm trying to iterate through an array of objects and for each object also iterate through the nested array of specs. My data structure looks something like this:

```<code>export const jobList = [
    {
        name: "Death Knight",
        specs:  [{name: "Blood"},
                 {name: "FrostDK"},
                 {name:"Unholy"}]
    },

    {
        name: "Shaman",
        specs: [{name:"Elemental"},
                {name:"Enhancement"},
                {name:"RestoShaman"}]
    },
</code>```

My desired output is

Death Knight

Blood

FrostDK

Unholy

Shaman

Elemental

Enhancement

RestoShaman

Here's the problem code:

```<code>return(
<div className="col-sm">
   {jobList.map((job, i) =>
      <p>{job.name)</p>
      job.specs.map((spec, i) =>
         <img className="spec" src={window.location.origin + '/icons/' + spec.name + '.png'} alt={spec.name} onClick={this.handleClick.bind(this, i)} />
      )
   )}
</div>
)
</code>```

This is throwing a 'Parsing error: Unexpected token, expected ","' on job.specs.map. If I remove
{job.name)
 it lists all of the specs as expected. If I throw a comma after
{job.name)
 then I got "'job' is not defined" on job.specs.map. I'm not understanding why it can't call job.name for each job and then run job.specs.map() afterwards.

答:
Surround

```<code> job.specs.map((spec, i) =>
  <img className="spec"
     src={window.location.origin +
     '/icons/' + spec.name + '.png'}
     alt={spec.name} onClick=.
     {this.handleClick.bind(this, i)} />
 )
</code>```

with a curly braces, like you did with joblist.map()

Body:
I'm trying to iterate through an array of objects and for each object also iterate through the nested array of specs. My data structure looks something like this:

export const jobList = [
    {
        name: "Death Knight",
        specs:  [{name: "Blood"},
                 {name: "FrostDK"},
                 {name:"Unholy"}]
    },

    {
        name: "Shaman",
        specs: [{name:"Elemental"},
                {name:"Enhancement"},
                {name:"RestoShaman"}]
    },

My desired output is

Death Knight

Blood

FrostDK

Unholy

Shaman

Elemental

Enhancement

RestoShaman

Here's the problem code:

return(

   {jobList.map((job, i) =>

{job.name)

      job.specs.map((spec, i) =>

      )
   )}

)

This is throwing a 'Parsing error: Unexpected token, expected ","' on job.specs.map. If I remove
{job.name)
 it lists all of the specs as expected. If I throw a comma after
{job.name)
 then I got "'job' is not defined" on job.specs.map. I'm not understanding why it can't call job.name for each job and then run job.specs.map() afterwards.

Body:
Surround

 job.specs.map((spec, i) =>
  <img className="spec"
     src={window.location.origin +
     '/icons/' + spec.name + '.png'}
     alt={spec.name} onClick=.
     {this.handleClick.bind(this, i)} />
 )

with a curly braces, like you did with joblist.map()


问:
Should I Avoid Getting the Size of a Collection in a Loop?
According to https://www.geeksforgeeks.org/12-tips-to-optimize-java-code-performance/ at number 3, it says that during a for loop, you should define size beforehand and call that in the comparator. At first, that made sense to me assuming that the .size() method has to count up the elements every time it is called.

To verify this, I went to the source code for an ArrayList and went to the size method. What I found though was that it would just return an integer size that is stored as a value in the object. This is more of what I was expecting to find, but if this is the case, then why does the article say to avoid it? It does not explain why, it merely says to never do it. From what I saw, the list is already calling a variable that is stored in memory.

So, my question is: Is it actually going to help, or is it just something that the article got wrong?

答:
The answer is: "it depends".

It depends on what List class you are using.

It depends on how smart the JIT compiler is.

It depends on whether the size of the list changes during the loop execution.

For the most common List implementations, the current size is held in a field, and the size() method simply returns that field.  In such cases, the code of the size() method will typically be inlined so that a size() call is a efficient as accessing the field directly.   If the JIT compiler is able to deduce that the field doesn't change (and if there are no relevant Java Memory Model related constraints) then it could conceivably cache the size() result in a register.

But the flipside is that some List implementations may compute the size, and the JIT compiler may not be able to do some or all of those optimizations.

But the flipside of the flipside is that if size() is cheap, the overhead of calling it on each loop iteration may be too small to be significant.

Bottom line:

Beware of premature optimization.

Beware of articles that give overly simplistic / overly generalized advice.

Beware of articles that contain arrant nonsense like this:

If possible, we can use primitive types instead of objects since data access from stack memory is faster than heap memory1.

 1 - This appears in "5. Use Primitive Types Wherever Possible".  Stack and heap memory use the same hardware and have the same access times.  The real point he should be making in that context is that getting the value of an Integer involves an extra memory fetch, compared with accessing an int.


问:
TypeScript compiler equality narrowing is incorrect after non-local mutation
The TypeScript compiler can perform equality narrowing to infer that a value has a specific literal type. However, that inference may last longer than is actually valid. In the example below, the compiler thinks that this.state must have the literal type "ALIVE" longer than it actually does.

class GameData {
    state: string = "ALIVE";

    maybeUpdateState() {
        if (Math.random() < 0.5) {
            this.state = "DEAD";
        }
    }

    doTick() {
        if (this.state == "ALIVE") {
            console.log("Game is alive");
            this.maybeUpdateState();
            if (this.state == "DEAD") { // <-- Compiler error here!
                console.log("Game died");
            }
        }
    }
}

new GameData().doTick();
```

This results in the following (incorrect) compiler error:

This condition will always return 'false' since the types '"ALIVE"' and '"DEAD"' have no overlap.

(Playground link)

This is obviously not true. I've figured out that there are ways I could work around this at the line where I do the second equality test -- for instance, I could rewrite it as if (this.state as string == "DEAD").

But instead of potentially having to do that every place I want to do an equality test against that property, is there any way that I can update maybeUpdateState() to let the compiler know that it mutates the object such that inferences about the object's properties may no longer be valid after it is called?

I haven't been able to find any other discussion about this specific issue in my online searching, so references to other Q&As/issues/posts would also be appreciated.

答:
This should fix it:

if (this.state.includes("DEAD")) {}
```
<p>Now, if you wanna make this mutation a bit more predictable use a type:</p>
<pre class="lang-js prettyprint-override"><code>type GameState = "ALIVE" | "DEAD";

state: GameState = "ALIVE";
</code>```

So even if you fudge up the codes and typo this.state = "DEAAD", for example, the compiler then flunks the build which is desirable.

Body:
The TypeScript compiler can perform equality narrowing to infer that a value has a specific literal type. However, that inference may last longer than is actually valid. In the example below, the compiler thinks that this.state must have the literal type "ALIVE" longer than it actually does.

class GameData {
    state: string = "ALIVE";

    maybeUpdateState() {
        if (Math.random() < 0.5) {
            this.state = "DEAD";
        }
    }

    doTick() {
        if (this.state == "ALIVE") {
            console.log("Game is alive");
            this.maybeUpdateState();
            if (this.state == "DEAD") { // <-- Compiler error here!
                console.log("Game died");
            }
        }
    }
}

new GameData().doTick();

This results in the following (incorrect) compiler error:

This condition will always return 'false' since the types '"ALIVE"' and '"DEAD"' have no overlap.

(Playground link)

This is obviously not true. I've figured out that there are ways I could work around this at the line where I do the second equality test -- for instance, I could rewrite it as if (this.state as string == "DEAD").

But instead of potentially having to do that every place I want to do an equality test against that property, is there any way that I can update maybeUpdateState() to let the compiler know that it mutates the object such that inferences about the object's properties may no longer be valid after it is called?

I haven't been able to find any other discussion about this specific issue in my online searching, so references to other Q&As/issues/posts would also be appreciated.

Body:
This should fix it:

if (this.state.includes("DEAD")) {}

Now, if you wanna make this mutation a bit more predictable use a type:

type GameState = "ALIVE" | "DEAD";

state: GameState = "ALIVE";

So even if you fudge up the codes and typo this.state = "DEAAD", for example, the compiler then flunks the build which is desirable.


答:
I was using in() incorrectly.

https://jqplay.org/s/FJcNTgplG6

```<code>filter:
map(in(["apple","is","bad"]))
input:
[3, 2, 1, 0]
output:
[
  false,
  true,
  true,
  true
]
</code>```

It's testing if the indexes of the filter array are found in the input array.

Title: How to correctly use jq's in() function

Body:
I was using in() incorrectly.

https://jqplay.org/s/FJcNTgplG6

filter:
map(in(["apple","is","bad"]))
input:
[3, 2, 1, 0]
output:
[
  false,
  true,
  true,
  true
]

It's testing if the indexes of the filter array are found in the input array.


问:
Adding multiple columns from a pandas data frame into a new column
I ran some code which resulted in either a 1 if something happened or a 0 if it did not.  The results are stored in 8 separate columns (count600, count800, etc) which visual studio has as a list type.  I then added the 8 columns together and have the results appear in a new column titled SUM_OVER90th.  The value stored in the SUM_OVER90th appears like 11111.0 instead of the value 5.  I tried a few different scripts which all seem to give a similar result.  I'm not sure why I'm not able to add these column together.  Thanks for any advice on what I might be doing wrong!

```<code>COLS_TO_ADD = ['600_COUNT','800_COUNT','1000_COUNT','1200_COUNT','1400_COUNT','1600_COUNT','1800_COUNT','2000_COUNT']
Q_ETL_sub['SUM_OVER90th'] = Q_ETL_sub[COLS_TO_ADD].sum(axis=1)
</code>```

enter image description here

答:
One possible reason is that your columns to add are strings, not numbers. You can verify this with

```<code>Q_ETL_sub.dtypes
</code>```

and if they are not numbers, try convert them into integer with

```<code>Q_ETL_sub[COLS_TO_ADD] = Q_ETL_sub[COLS_TO_ADD].astype(int)
</code>```

Body:
I ran some code which resulted in either a 1 if something happened or a 0 if it did not.  The results are stored in 8 separate columns (count600, count800, etc) which visual studio has as a list type.  I then added the 8 columns together and have the results appear in a new column titled SUM_OVER90th.  The value stored in the SUM_OVER90th appears like 11111.0 instead of the value 5.  I tried a few different scripts which all seem to give a similar result.  I'm not sure why I'm not able to add these column together.  Thanks for any advice on what I might be doing wrong!

COLS_TO_ADD = ['600_COUNT','800_COUNT','1000_COUNT','1200_COUNT','1400_COUNT','1600_COUNT','1800_COUNT','2000_COUNT']
Q_ETL_sub['SUM_OVER90th'] = Q_ETL_sub[COLS_TO_ADD].sum(axis=1)

enter image description here

Body:
One possible reason is that your columns to add are strings, not numbers. You can verify this with

Q_ETL_sub.dtypes

and if they are not numbers, try convert them into integer with

Q_ETL_sub[COLS_TO_ADD] = Q_ETL_sub[COLS_TO_ADD].astype(int)


问:
Is there a way to use a cleaner to omit specific cases? (R)
I have a dataframe where I want to omit cases where ages 30 or less are omitted. I know you can use na.omit to omit NA cases, but how would I omit specific cases like this?</p>

答:
Seems to be more a filtering problem than omitting missing values:</p>
```<code>> df <- tibble(age = c(20,25,30,35,40))
>
> df %>% filter(age < 30)
# A tibble: 2 × 1
    age
  <dbl>
1    20
2    25
>
</code>```

Body:
Seems to be more a filtering problem than omitting missing values:

> df <- tibble(age = c(20,25,30,35,40))
>
> df %>% filter(age < 30)
# A tibble: 2 × 1
    age
  <dbl>
1    20
2    25
>


问:
How do I disconnect a user from a discord channel with discord js?
The main issue seems to be that things are undefined. For example, a very simple version of something I have tried:

```<code>else if (message.content.startsWith("!dc")) {
    message.author.voice.setChannel(null);
}
</code>```

Resulting in the terminal returning:

TypeError: Cannot read properties of undefined (reading 'setChannel')

I'm not quite sure how to "define" these as some solutions I've found online seem to do what I am trying to do in a similar way. Am I just missing something obvious?

I also have these Intents declared at the top.

```<code>const client = new Discord.Client({
intents: [
    Discord.Intents.FLAGS.GUILDS,
    Discord.Intents.FLAGS.GUILD_MESSAGES,
    Discord.Intents.FLAGS.GUILD_VOICE_STATES,
    Discord.Intents.FLAGS.GUILD_MEMBERS
    ]
});
</code>```

答:
As @Bee said in the comments to my question:

it'd be msg.member

Body:
The main issue seems to be that things are undefined. For example, a very simple version of something I have tried:

else if (message.content.startsWith("!dc")) {
    message.author.voice.setChannel(null);
}

Resulting in the terminal returning:

TypeError: Cannot read properties of undefined (reading 'setChannel')

I'm not quite sure how to "define" these as some solutions I've found online seem to do what I am trying to do in a similar way. Am I just missing something obvious?

I also have these Intents declared at the top.

const client = new Discord.Client({
intents: [
    Discord.Intents.FLAGS.GUILDS,
    Discord.Intents.FLAGS.GUILD_MESSAGES,
    Discord.Intents.FLAGS.GUILD_VOICE_STATES,
    Discord.Intents.FLAGS.GUILD_MEMBERS
    ]
});


问:
Static UILabel not showing in uiview
I have create a few static UILabel text in Interface Builder, but when running the application. the label is not shown in the application itself, i do not know why.

all other stuff like textfield, buttons except the label is not working
can anybody advise me what had gone wrong ?

This is in IB

this is in App

```<code>#import "SettingsViewController.h"

@implementation SettingsViewController

@synthesize drinkLimitText;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    appDelegate = (DrinkTabsAndNavAppDelegate *)[[UIApplication sharedApplication] delegate];
    [super viewDidLoad];

    NSLog(@"subView:%d",[self.view.subviews count]);
}

- (void) viewWillAppear:(BOOL)animated {

    if ([appDelegate.drinkLimit floatValue] >= 0)
        drinkLimitText.text = [NSString stringWithFormat:@"%.0f", [appDelegate.drinkLimit floatValue]];
    else
        drinkLimitText.text = @"0";

    [super viewWillAppear:animated];
}

- (IBAction)textFieldDoneEditing:(id)sender{
    NSDecimalNumber *tempValue = [[NSDecimalNumber alloc] initWithString:drinkLimitText.text];
    if (tempValue == [NSDecimalNumber notANumber] || [tempValue doubleValue] < 0) {
        NSString *msg = [[NSString alloc] initWithFormat: @"Make sure to enter a positive number."];
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Hang on..."
                              message:msg
                              delegate:self
                              cancelButtonTitle:@"Ok"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        [msg release];
    } else {
        [sender resignFirstResponder];
        [self updateDrinkLimit];
    }
    [tempValue release];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)updateDrinkLimit {

    NSDecimalNumber *newLimit = [[NSDecimalNumber alloc] initWithString:[drinkLimitText text]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([newLimit floatValue] >= 0) {
        [defaults setFloat:[newLimit floatValue] forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = newLimit;
    } else {
        [defaults setFloat:0 forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = 0;
    }
    [newLimit release];
}

- (IBAction)openOntrackWebsite {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.ontrack.org.au/"]];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [drinkLimitText release];

    [super dealloc];
}

@end
</code>```

答:
Your hierarchy in interface builder should be as shown below:

```<code>UIView
   --- Label
   --- TextField
   --- Label
   --- UIButton
</code>```

I suspect it is :

```<code>UIView
   --- Label
   --- UIButton
Label
Label
</code>```

Title: Static UILabel not showing in uiview

Body:
I have create a few static UILabel text in Interface Builder, but when running the application. the label is not shown in the application itself, i do not know why.

all other stuff like textfield, buttons except the label is not working
can anybody advise me what had gone wrong ?

This is in IB

this is in App

#import "SettingsViewController.h"

@implementation SettingsViewController

@synthesize drinkLimitText;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    appDelegate = (DrinkTabsAndNavAppDelegate *)[[UIApplication sharedApplication] delegate];
    [super viewDidLoad];

    NSLog(@"subView:%d",[self.view.subviews count]);
}

- (void) viewWillAppear:(BOOL)animated {

    if ([appDelegate.drinkLimit floatValue] >= 0)
        drinkLimitText.text = [NSString stringWithFormat:@"%.0f", [appDelegate.drinkLimit floatValue]];
    else
        drinkLimitText.text = @"0";

    [super viewWillAppear:animated];
}

- (IBAction)textFieldDoneEditing:(id)sender{
    NSDecimalNumber *tempValue = [[NSDecimalNumber alloc] initWithString:drinkLimitText.text];
    if (tempValue == [NSDecimalNumber notANumber] || [tempValue doubleValue] < 0) {
        NSString *msg = [[NSString alloc] initWithFormat: @"Make sure to enter a positive number."];
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Hang on..."
                              message:msg
                              delegate:self
                              cancelButtonTitle:@"Ok"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        [msg release];
    } else {
        [sender resignFirstResponder];
        [self updateDrinkLimit];
    }
    [tempValue release];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)updateDrinkLimit {

    NSDecimalNumber *newLimit = [[NSDecimalNumber alloc] initWithString:[drinkLimitText text]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([newLimit floatValue] >= 0) {
        [defaults setFloat:[newLimit floatValue] forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = newLimit;
    } else {
        [defaults setFloat:0 forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = 0;
    }
    [newLimit release];
}

- (IBAction)openOntrackWebsite {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.ontrack.org.au/"]];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [drinkLimitText release];

    [super dealloc];
}

@end

Body:
Your hierarchy in interface builder should be as shown below:

UIView
   --- Label
   --- TextField
   --- Label
   --- UIButton

I suspect it is :

UIView
   --- Label
   --- UIButton
Label
Label


问:
error ClientException: Links are not supported when networkMode=awsvpc in fargate terraform
I got an error in terraform:

```<code>ClientException: Links are not supported when networkMode=awsvpc.
</code>```

I link nginx with my nodejs application. I want nodejs to run on 3000 port, and nginx run on 80 and when the request is incoming then nginx will do proxy to nodejs. ( I have defined nginx.conf with proxy to 3000).

Its happens in fargate mode. but I don't have choice here, the network mode is only a awsvpc.

What I can do? there is a way to link between the containers? one conatiner, nginx and nodejs inside? just nodejs? other solution?

here my terraform settings:

```<code>resource "aws_ecs_service" "nginx" {
  name            = "nginx-${var.app}"
  cluster         = aws_ecs_cluster.demo.id
  task_definition = aws_ecs_task_definition.nginx.arn
  desired_count   = 4
  launch_type = "FARGATE"

  lifecycle {
    ignore_changes = [task_definition]
  }
 ...
}

resource "aws_ecs_task_definition" "nginx" {
  family = "nginx-${var.app}"

  container_definitions = file("container_definitions.json")

  requires_compatibilities = ["FARGATE"]
  network_mode = "awsvpc"
}
</code>```

container_definitions.json:

```<code>[
  {
    "name": "nginx-...nginx-www",
    "image": "311443.dkr.ecr.us-east-2.amazonaws.com/...-nginx:latest",
    "cpu": 256,
    "memory": 256,
    "essential": true,
    "links": ["www-app"],
    "portMappings": [
      {
        "protocol": "tcp",
        "containerPort": 80
      }
    ],
    "logConfiguration": {
      "logDriver": "awslogs",
      "options": {
        "awslogs-group": "...",
        "awslogs-region": "us-east-2",
        "awslogs-stream-prefix": "ecs"
      }
    }
  },
  {
    "name": "www-app",
    "image": "93934.dkr.ecr.us-east-2.amazonaws.com/..../www-app:latest",
    "cpu": 256,
    "memory": 256,
    "essential": true,
    "logConfiguration": {
      "logDriver": "awslogs",
      "options": {
        "awslogs-group": "/ecs-..../nginx",
        "awslogs-region": "us-east-2",
        "awslogs-stream-prefix": "ecs"
      }
    }
  }
]
</code>```

答:
TL;DR

I recommend you link config file that is located s3 to ecs nginx.

Between ecs containers, each other is linked on same network. And AWS enforces network mode if you use fargates.

There are two ways solutions.

Configure nginx config for container nginx image.

just forward web port 80 to 3000 node port. Nginx is primarily designed that subject.

upload nginx.config file to s3 and then link that s3 arn to ecs with "EnvironmentFile" field.

Or you can build own nginx image with custom config (not recommended).

just give up using nginx. Web port can be forward with application load balancer.

you can forward from 80 to 3000 on Application Load Balancer. It is depends on your app size. If that is simple app, You have not to use nginx.

Normally Nginx is used as reverse proxy, but can be used control http buffering(proxy buffer), graceful restart, queueing request etc..

Body:
I got an error in terraform:

ClientException: Links are not supported when networkMode=awsvpc.

I link nginx with my nodejs application. I want nodejs to run on 3000 port, and nginx run on 80 and when the request is incoming then nginx will do proxy to nodejs. ( I have defined nginx.conf with proxy to 3000).

Its happens in fargate mode. but I don't have choice here, the network mode is only a awsvpc.

What I can do? there is a way to link between the containers? one conatiner, nginx and nodejs inside? just nodejs? other solution?

here my terraform settings:

resource "aws_ecs_service" "nginx" {
  name            = "nginx-${var.app}"
  cluster         = aws_ecs_cluster.demo.id
  task_definition = aws_ecs_task_definition.nginx.arn
  desired_count   = 4
  launch_type = "FARGATE"

  lifecycle {
    ignore_changes = [task_definition]
  }
 ...
}

resource "aws_ecs_task_definition" "nginx" {
  family = "nginx-${var.app}"

  container_definitions = file("container_definitions.json")

  requires_compatibilities = ["FARGATE"]
  network_mode = "awsvpc"
}

container_definitions.json:

[
  {
    "name": "nginx-...nginx-www",
    "image": "311443.dkr.ecr.us-east-2.amazonaws.com/...-nginx:latest",
    "cpu": 256,
    "memory": 256,
    "essential": true,
    "links": ["www-app"],
    "portMappings": [
      {
        "protocol": "tcp",
        "containerPort": 80
      }
    ],
    "logConfiguration": {
      "logDriver": "awslogs",
      "options": {
        "awslogs-group": "...",
        "awslogs-region": "us-east-2",
        "awslogs-stream-prefix": "ecs"
      }
    }
  },
  {
    "name": "www-app",
    "image": "93934.dkr.ecr.us-east-2.amazonaws.com/..../www-app:latest",
    "cpu": 256,
    "memory": 256,
    "essential": true,
    "logConfiguration": {
      "logDriver": "awslogs",
      "options": {
        "awslogs-group": "/ecs-..../nginx",
        "awslogs-region": "us-east-2",
        "awslogs-stream-prefix": "ecs"
      }
    }
  }
]