问:
Pass in Subnet Delegation from Parameters file
I'm trying to update the subnet delegations from a parameters file using BICEP but keep getting an error which I can't work out why.

The language expression property 'name' has an invalid array index.

BICEP File:

subnets: [for j in range(0, length(VNetSettings.subnets)): {

```<code>          {
            name: VNetSettings.subnets[j].delegations.name
            properties: {
              serviceName: VNetSettings.subnets[j].delegations.properties.serviceName
            }
          }
        ]
</code>```

Parameters File:

```<code>            "value": {
                "Name": "vnet",
                "addressPrefix": "10.230.0.0/23",
                "subnets": [
                    {
                        "name": "data",
                        "addressPrefix": "10.230.1.64/26",
                        "routeTable": "",
                        "unique": false,
                        "nsgRules": [
                            {
                                "name": "DENY-ALL-VNET-INBOUND",
                                "description": "Deny all Virtual Network traffic",
                                "priority": "4000",
                                "direction": "Inbound",
                                "access": "Deny",
                                "protocol": "*",
                                "sourcePortRange": "*",
                                "destinationPortRange": "*",
                                "sourceAddressPrefix": "VirtualNetwork",
                                "destinationAddressPrefix": "VirtualNetwork"
                            }
                        ],
                        "serviceEndpoints":[],
                        "delegations": [
                            {
                                "name": "Microsoft.Web.serverFarms",
                                "properties": {
                                    "serviceName": "Microsoft.Web/serverFarms"
                                }
                            }
                        ]
                    },
</code>```

Just can't work out where I'm going wrong.

答:
Based on the error you've received, I believe the issue has to do with the loop you're constructing. Change your loop to the following:

subnets: [for (subnet, j) in VNetSettings.subnets):

Now, subnet will contain your current subnet object and j will reflect the loop index you're currently on. This corrects the error you see - notably, it's saying you have an invalid array index because you're trying to pass in something that's not actually an index in your original question.

Then just make a few tweaks to the subnet object itself to reflect the use of the reference you're using in the loop (instead of an array index).

```<code>{
  name: subnet.delegations.name
  properties: {
    serviceName: subnet.delegations.properties.serviceName
}
</code>```

Body:
I'm trying to update the subnet delegations from a parameters file using BICEP but keep getting an error which I can't work out why.

The language expression property 'name' has an invalid array index.

BICEP File:

subnets: [for j in range(0, length(VNetSettings.subnets)): {

          {
            name: VNetSettings.subnets[j].delegations.name
            properties: {
              serviceName: VNetSettings.subnets[j].delegations.properties.serviceName
            }
          }
        ]

Parameters File:

            "value": {
                "Name": "vnet",
                "addressPrefix": "10.230.0.0/23",
                "subnets": [
                    {
                        "name": "data",
                        "addressPrefix": "10.230.1.64/26",
                        "routeTable": "",
                        "unique": false,
                        "nsgRules": [
                            {
                                "name": "DENY-ALL-VNET-INBOUND",
                                "description": "Deny all Virtual Network traffic",
                                "priority": "4000",
                                "direction": "Inbound",
                                "access": "Deny",
                                "protocol": "*",
                                "sourcePortRange": "*",
                                "destinationPortRange": "*",
                                "sourceAddressPrefix": "VirtualNetwork",
                                "destinationAddressPrefix": "VirtualNetwork"
                            }
                        ],
                        "serviceEndpoints":[],
                        "delegations": [
                            {
                                "name": "Microsoft.Web.serverFarms",
                                "properties": {
                                    "serviceName": "Microsoft.Web/serverFarms"
                                }
                            }
                        ]
                    },

Just can't work out where I'm going wrong.

Body:
Based on the error you've received, I believe the issue has to do with the loop you're constructing. Change your loop to the following:

subnets: [for (subnet, j) in VNetSettings.subnets):

Now, subnet will contain your current subnet object and j will reflect the loop index you're currently on. This corrects the error you see - notably, it's saying you have an invalid array index because you're trying to pass in something that's not actually an index in your original question.

Then just make a few tweaks to the subnet object itself to reflect the use of the reference you're using in the loop (instead of an array index).

{
  name: subnet.delegations.name
  properties: {
    serviceName: subnet.delegations.properties.serviceName
}


来源: stackexchange

问:
How to upload an image from a remote website, by using javascript?
Is there any way I can do that? For example, I have an

```<code><input type="file" id="upload_file" />
</code>```

Obviously I can't just

```<code>$('#upload_file').val('http://www.site.com/path/to/image.jpg').parent().submit();
</code>```

答:
Te begin with, you cannot do file uploads without a server-side tool. Sending a file to the server is pointless if there isn't anything on the side other to receive it.

Said that, if you already have a server-side language available and a file that's publicly reachable at a URL, the server-side language is perfectly capable of fetching the file by its own means. There's no need to use the browser as intermediary. You just need to send the URL in a regular <input type="text"> element.

If the file is not publicly reachable, e.g., it belongs to an intranet or is password-protected, it's probably simpler to instruct the user to type the URL in the browser's "Open file" dialoque. In many cases, the browser will download the file and fill the <input type="file"> control with the temporary downloaded file.

ContentLicense: CC BY-SA 3.0

Body:
Is there any way I can do that? For example, I have an

<input type="file" id="upload_file" />

Obviously I can't just

$('#upload_file').val('http://www.site.com/path/to/image.jpg').parent().submit();


问:
Invalid constant value in extended class
The following code snippet displays some styled TextFields in a flutter app:

```<code>@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Some input form')),
        body: Container(
          padding: const EdgeInsets.all(32),
            child: Column(
          children: const [
            Placeholder(fallbackHeight: 200, fallbackWidth: 200),
            SizedBox(height: 20),
            TextField(decoration: InputDecoration(labelText: 'Label0')),
            SizedBox(height: 20),
            TextField(decoration: InputDecoration(labelText: 'Label1')),
          ],
        )));
  }
</code>```

Because I want all my TextFields to look the same I thought of doing this:

```<code>class mTextField extends TextField{
  const mTextField({Key? key, String? hint}) : super(key: key, decoration: InputDecoration(labelText: hint));//this line gives the error
}
</code>```

To remodel my original code as

```<code>@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Some input form')),
        body: Container(
          padding: const EdgeInsets.all(32),
            child: Column(
          children: const [
            Placeholder(fallbackHeight: 200, fallbackWidth: 200),
            SizedBox(height: 20),
            mTextField(hint: 'Label0'),//simplified here
            SizedBox(height: 20),
            mTextField(hint: 'Label1'),//simplified here
          ],
        )));
  }
</code>```

But this gives me an "invalid constant value" error for the labelText: hint. Of course I could just make the children of the Container non-const, but as far as I see it, it should be possible to have mTextField be constant because it is no different from a regular TextField which can be const.

答:
Change

```<code>class mTextField extends TextField{
  const mTextField({Key? key, String? hint}) : super(key: key, decoration: InputDecoration(labelText: hint));//this line gives the error
}
</code>```

to

```<code>class mTextField extends TextField{
  mTextField({Key? key, String? hint}) : super(key: key, decoration: InputDecoration(labelText: hint));//this line gives the error
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The following code snippet displays some styled TextFields in a flutter app:

@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Some input form')),
        body: Container(
          padding: const EdgeInsets.all(32),
            child: Column(
          children: const [
            Placeholder(fallbackHeight: 200, fallbackWidth: 200),
            SizedBox(height: 20),
            TextField(decoration: InputDecoration(labelText: 'Label0')),
            SizedBox(height: 20),
            TextField(decoration: InputDecoration(labelText: 'Label1')),
          ],
        )));
  }

Because I want all my TextFields to look the same I thought of doing this:

class mTextField extends TextField{
  const mTextField({Key? key, String? hint}) : super(key: key, decoration: InputDecoration(labelText: hint));//this line gives the error
}

To remodel my original code as

@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Some input form')),
        body: Container(
          padding: const EdgeInsets.all(32),
            child: Column(
          children: const [
            Placeholder(fallbackHeight: 200, fallbackWidth: 200),
            SizedBox(height: 20),
            mTextField(hint: 'Label0'),//simplified here
            SizedBox(height: 20),
            mTextField(hint: 'Label1'),//simplified here
          ],
        )));
  }

But this gives me an "invalid constant value" error for the labelText: hint. Of course I could just make the children of the Container non-const, but as far as I see it, it should be possible to have mTextField be constant because it is no different from a regular TextField which can be const.

Body:
Change

class mTextField extends TextField{
  const mTextField({Key? key, String? hint}) : super(key: key, decoration: InputDecoration(labelText: hint));//this line gives the error
}

to

class mTextField extends TextField{
  mTextField({Key? key, String? hint}) : super(key: key, decoration: InputDecoration(labelText: hint));//this line gives the error
}


问:
No module named 'pymysql'
I'm trying to use PyMySQL on Ubuntu.

I've installed pymysql using both pip and pip3 but every time I use import pymysql, it returns ImportError: No module named 'pymysql'

I'm using Ubuntu 15.10 64-bit and Python 3.5.

The same .py works on Windows with Python 3.5, but not on Ubuntu.

答: You can also visit this lien pip install PyMySQL</p>

Title: No module named 'pymysql'


问:
Nextflow combine by regex match
I have a tuple channel containing entries like:

```<code>SH7794_SA119138_S1_L001, [R1.fq.gz, R2.fq.gz]
</code>```

And a csv split into 36 entries, each like:

```<code>[samplename:SH7794_SA119138_S1, mouseID:1-4, treat:vehicle, dose:NA, time:day18, tgroup:vehicle__day18, fastqsuffix:_L001_R1_001.fastq.gz, bamsuffix:_Filtered.bam, trim:fulgentTrim, species:human, host:mouse, outlier:NA, RIN:6.9]
</code>```

I was able to combine the tuple channel with the csv entries using the each keyword.  This results in a cross-product of all 36 csv rows for each tuple.  I then added a when condition to do the filtering:

```<code>  input:
    tuple sampleid, reads from fq
    each samplemeta from samplelist

  ...

  when:
    sampleid.contains(samplemeta.samplename)
</code>```

This works but I'm curious if this is an appropriate solution.  What is the correct way to dynamically join channels using a regular expression, by matching a value from one channel against multiple values from a second channel?

答:
I tend to avoid using the each qualifier like this because of this recommendation in the docs:

If you need to repeat the execution of a process over n-tuple of
elements instead a simple values or files, create a channel combining
the input values as needed to trigger the process execution multiple
times. In this regard, see the combine, cross and phase operators.

I don't actually think there's a way to join channels using a regex, but what you can do is use the combine operator to produce the Cartesian product of the items emitted by two channels. And if you supply the by parameter, you can combine the items that share a common matching key. For example, untested:

```<code>params.reads = '/path/to/fastq/*_{,L00?}_R{1,2}.fq.gz'

Channel
    .fromPath('sample_list.csv')
    .splitCsv(header: true)
    .map { row -> tuple( row.samplename, row ) }
    .set { sample_metadata }

Channel
    .fromFilePairs( params.reads )
    .combine( sample_metadata, by: 0 )
    .set { test_inputs }

process test {

    input:
    tuple val(sample_id), path(reads), val(metadata) from test_inputs

    script:
    def (fq1, fq2) = reads

    """
    echo "sample_id: ${sample_id}"
    echo "reads: ${fq1}, ${fq2}"
    echo "metadata: ${metadata}"
    """
}
</code>```

Title: Nextflow combine by regex match

Body:
I have a tuple channel containing entries like:

SH7794_SA119138_S1_L001, [R1.fq.gz, R2.fq.gz]

And a csv split into 36 entries, each like:

[samplename:SH7794_SA119138_S1, mouseID:1-4, treat:vehicle, dose:NA, time:day18, tgroup:vehicle__day18, fastqsuffix:_L001_R1_001.fastq.gz, bamsuffix:_Filtered.bam, trim:fulgentTrim, species:human, host:mouse, outlier:NA, RIN:6.9]

I was able to combine the tuple channel with the csv entries using the each keyword.  This results in a cross-product of all 36 csv rows for each tuple.  I then added a when condition to do the filtering:

  input:
    tuple sampleid, reads from fq
    each samplemeta from samplelist

  ...

  when:
    sampleid.contains(samplemeta.samplename)

This works but I'm curious if this is an appropriate solution.  What is the correct way to dynamically join channels using a regular expression, by matching a value from one channel against multiple values from a second channel?

Body:
I tend to avoid using the each qualifier like this because of this recommendation in the docs:

If you need to repeat the execution of a process over n-tuple of
elements instead a simple values or files, create a channel combining
the input values as needed to trigger the process execution multiple
times. In this regard, see the combine, cross and phase operators.

I don't actually think there's a way to join channels using a regex, but what you can do is use the combine operator to produce the Cartesian product of the items emitted by two channels. And if you supply the by parameter, you can combine the items that share a common matching key. For example, untested:

params.reads = '/path/to/fastq/*_{,L00?}_R{1,2}.fq.gz'

Channel
    .fromPath('sample_list.csv')
    .splitCsv(header: true)
    .map { row -> tuple( row.samplename, row ) }
    .set { sample_metadata }

Channel
    .fromFilePairs( params.reads )
    .combine( sample_metadata, by: 0 )
    .set { test_inputs }

process test {

    input:
    tuple val(sample_id), path(reads), val(metadata) from test_inputs

    script:
    def (fq1, fq2) = reads

    """
    echo "sample_id: ${sample_id}"
    echo "reads: ${fq1}, ${fq2}"
    echo "metadata: ${metadata}"
    """
}


问:
Focus on Table row TR for accessiblity
I have a requirement to implement accessibility on table rows. The application should ideally be div based and rows should've been li's, but it is an old application and redesigning is not an option. So am forced to tweak and make it accessible. Could any one of you please help me to get focus on a table row? Is is possible at all?

For e.g: The table below, on tab, should first focus on the first row and then the input inside it. Again tabbing should do the same on the next row.

```<code><table>
<tr>
    <td><input type="textbox" /></td>
    <td>some content</td>
<tr>
<tr>
    <td><input type="textbox" /></td>
    <td>some content</td>
<tr>
<tr>
    <td><input type="textbox" /></td>
    <td>some content</td>
<tr>
</table>
</code>```

Any help is highly appreciated.

答:
You can focus on elements that are ordinarily unfocusable by assigning a tabindex:

```<code><td tabindex="1">focus on me</td>
</code>```

Title: Focus on Table row TR for accessiblity

Body:
I have a requirement to implement accessibility on table rows. The application should ideally be div based and rows should've been li's, but it is an old application and redesigning is not an option. So am forced to tweak and make it accessible. Could any one of you please help me to get focus on a table row? Is is possible at all?

For e.g: The table below, on tab, should first focus on the first row and then the input inside it. Again tabbing should do the same on the next row.

    <input type="textbox" />
    some content

    <input type="textbox" />
    some content

    <input type="textbox" />
    some content

Any help is highly appreciated.

Body:
You can focus on elements that are ordinarily unfocusable by assigning a tabindex:

<td tabindex="1">focus on me</td>


问:
What does OWASP mean when they say you should not "send raw responses to clients"?

Do not send raw responses to clients

https://owasp.org/Top10/A10_2021-Server-Side_Request_Forgery_%28SSRF%29/

What does this refer to? I tried to google, but all I can find is 'raw' as in the full text or stringified. Aren't all HTTP(s) responses 'raw' in this sense, since it's text based?

Or does it mean editing the response to give fake values regarding the server, rather than genuine ones?

答:
I am fairly certain that it means you shouldn't send a response you received from a third party (e.g. an API) directly to the end user.

If you do so it could provide sensitive information to an attacker, or information that could further expose your app.


问:
Webpack external module gives an error on optimization
I'm new to Node and Angular but I have been tasked with updating an application using them.

When I run ng build --configuration production --base-href on the code I updated I get

```<code>Error: Optimization error [main.0a57bb482e1539bc.js]: Error: Transform failed with 1 error:
main.0a57bb482e1539bc.js:78551:5: error: Expected identifier but found "="
    at failureErrorWithLog (C:\Users\[redacted]\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:1493:15)
    at C:\Users\[redacted]\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:1282:29
    at C:\Users\[redacted]\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:629:9
    at handleIncomingPacket (C:\Users\[redacted]\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:726:9)
    at Socket.readFromStdout (C:\Users\[redacted]\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:596:7)
    at Socket.emit (events.js:315:20)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
    at Socket.Readable.push (internal/streams/readable.js:223:10)
    at Pipe.onStreamRead (internal/stream_base_commons.js:188:23)
</code>```

If I run ng build --configuration production --base-href --optimization false it builds and I can see the line causing the error (main.0a57bb482e1539bc.js:78551) is:

```<code>// EXTERNAL MODULE: buffer/
var  = __webpack_require__(7555);
</code>```

I can tell it's obviously syntactically incorrect.

buffer is being used as a dependency of // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/AuthenticationDetails.js

However if I create a new app and use the code import {AuthenticationDetails} from "amazon-cognito-identity-js"; in it I don't have this problem. What I see instead is this line:

```<code>/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! buffer */ 7555);
</code>```

What I would like to know is what is causing my updated code to use // EXTERNAL MODULE: buffer/ and how I can change it to not have the problem maybe by using /* harmony import */.

Angular CLI: 13.0.3
Node: 14.16.1

答:
Experienced the same build issue when upgrading from Angular 11 -> 12.

Original version - Optimization error

```<code>"amazon-cognito-identity-js": "^5.2.4",
</code>```

Downgraded version - No Optimization error

```<code>"amazon-cognito-identity-js": "^3.3.3",
</code>```

No degradation to the app found by reducing the version. "3.3.3" is the latest stable version of amazon-cognito-identity-js.

Body:
I'm new to Node and Angular but I have been tasked with updating an application using them.

When I run ng build --configuration production --base-href on the code I updated I get

Error: Optimization error [main.0a57bb482e1539bc.js]: Error: Transform failed with 1 error:
main.0a57bb482e1539bc.js:78551:5: error: Expected identifier but found "="
    at failureErrorWithLog (C:\Users\[redacted]\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:1493:15)
    at C:\Users\[redacted]\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:1282:29
    at C:\Users\[redacted]\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:629:9
    at handleIncomingPacket (C:\Users\[redacted]\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:726:9)
    at Socket.readFromStdout (C:\Users\[redacted]\node_modules\@angular-devkit\build-angular\node_modules\esbuild\lib\main.js:596:7)
    at Socket.emit (events.js:315:20)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
    at Socket.Readable.push (internal/streams/readable.js:223:10)
    at Pipe.onStreamRead (internal/stream_base_commons.js:188:23)

If I run ng build --configuration production --base-href --optimization false it builds and I can see the line causing the error (main.0a57bb482e1539bc.js:78551) is:

// EXTERNAL MODULE: buffer/
var  = __webpack_require__(7555);

I can tell it's obviously syntactically incorrect.

buffer is being used as a dependency of // CONCATENATED MODULE: ./node_modules/amazon-cognito-identity-js/es/AuthenticationDetails.js

However if I create a new app and use the code import {AuthenticationDetails} from "amazon-cognito-identity-js"; in it I don't have this problem. What I see instead is this line:

/* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! buffer */ 7555);

What I would like to know is what is causing my updated code to use // EXTERNAL MODULE: buffer/ and how I can change it to not have the problem maybe by using /* harmony import */.

Angular CLI: 13.0.3
Node: 14.16.1

Body:
Experienced the same build issue when upgrading from Angular 11 -> 12.

Original version - Optimization error

"amazon-cognito-identity-js": "^5.2.4",

Downgraded version - No Optimization error

"amazon-cognito-identity-js": "^3.3.3",

No degradation to the app found by reducing the version. "3.3.3" is the latest stable version of amazon-cognito-identity-js.


问:
How to make replication faster for mysql table with 8 million records
I take my Live server backup using mysqldump command via CRON job in my Ubuntu Server via Bash Shell Script and the same script uploads the backup to my backup server also. Earlier this was working fine but now I am facing slowness issue (it takes 1 hour to backup and upload on backup server) as one of the database Table size has grown to 5GB and consists of 10 Million Records. I saw on a thread that we can fasten the SQL insertion via bulk/group execution of SQL -  How can mysql insert millions records faster?

But in my case I am unsure how can I create a Shell Script to perform the same.

The requirement is I want to export all my SQL Database tables in groups of maximum 10k so that execution can be faster while it is getting imported on the server.

I have written this code on my server bash script:

```<code>#!/bin/bash
cd /tmp
file=$(date +%F-%T).sql
mysqldump \
  --host ${MYSQL_HOST} \
  --port ${MYSQL_PORT} \
  -u ${MYSQL_USER} \
  --password="${MYSQL_PASS}" \
  ${MYSQL_DB} > ${file}
if [ "${?}" -eq 0 ]; then
  mysql -umyuser -pmypassword -h 198.168.1.3  -e "show databases"
  mysql -umyuser -pmypassword -h 198.168.1.3 -D backup_db -e "drop database backup_db"
  mysql -umyuser -pmypassword -h 198.168.1.3  -e "create database backup_db"
  mysql -umyuser -pmypassword -h 198.168.1.3 backup_db < ${file}
  gzip ${file}
  aws s3 cp ${file}.gz s3://${S3_BUCKET}/live_db/
  rm ${file}.gz
else
  echo "Error backing up mysql"
  exit 255
fi
</code>```

The backup server and live server share the same AWS hardware configuration: 16GB RAM, 4 CPU, 100GB SSD.

These are the screenshots and data:

Screenshot and Queries for Debugging on the Live Server:
Information Schema Tables:

```<code>https://i.imgur.com/RnjQwbP.png
</code>```

SHOW GLOBAL STATUS:

```<code>https://pastebin.com/raw/MuJYwnsm
</code>```

SHOW GLOBAL VARIABLES:

```<code>https://pastebin.com/raw/wdvn97XP
</code>```

Screenshot and Queries for Debugging on the Backup Server:

```<code>https://i.imgur.com/rB7qcYU.png
https://pastebin.com/raw/K7vHXqWi
https://pastebin.com/raw/PR2gWpqe
</code>```

Server workload is almost negligible. There is no load all the times, I have also monitored via AWS Monitoring Panel, and that's the only reason to take more than required resource server so that it never gets exhausted. I have taken 16GB RAM and 4 CPU which are more than more than sufficient. AWS Monitoring Panel showed Max usage 6% rarely and maximum times it is around 1%.

答:
```<code>Analysis of GLOBAL STATUS and VARIABLES:

</code>```

Observations:

Version: 10.3.32-MariaDB-0ubuntu0.20.04.1-log

16 GB of RAM

Uptime = 3d 05:41:50

42.1 QPS

The More Important Issues:

Some setting suggestions for better memory utilization:

```<code>key_buffer_size = 20M
innodb_buffer_pool_size = 8G
table_open_cache = 300
innodb_open_files = 1000
query_cache_type = OFF
query_cache_size = 0
</code>```

Some setting suggestions for other reasons:

```<code>eq_range_index_dive_limit = 20
log_queries_not_using_indexes = OFF
</code>```

Recommend using the slowlog (with long_query_time = 1) to locate the naughty queries.  Then we can discuss how to improve them.
http://mysql.rjweb.org/doc.php/mysql_analysis#slow_queries_and_slowlog

Details and other observations:

( (key_buffer_size - 1.2 * Key_blocks_used * 1024) ) = ((512M - 1.2 * 8 * 1024)) / 16384M = 3.1% -- Percent of RAM wasted in key_buffer.
-- Decrease key_buffer_size (now 536870912).

( Key_blocks_used * 1024 / key_buffer_size ) = 8 * 1024 / 512M = 0.00% -- Percent of key_buffer used. High-water-mark.
-- Lower key_buffer_size (now 536870912) to avoid unnecessary memory usage.

( (key_buffer_size / 0.20 + innodb_buffer_pool_size / 0.70) ) = ((512M / 0.20 + 128M / 0.70)) / 16384M = 16.7% -- Most of available ram should be made available for caching.
-- http://mysql.rjweb.org/doc.php/memory

( table_open_cache ) = 16,293 -- Number of table descriptors to cache
-- Several hundred is usually good.

( innodb_buffer_pool_size ) = 128M -- InnoDB Data + Index cache
-- 128M (an old default) is woefully small.

( innodb_buffer_pool_size ) = 128 / 16384M = 0.78% -- % of RAM used for InnoDB buffer_pool
-- Set to about 70% of available RAM. (To low is less efficient; too high risks swapping.)

( innodb_lru_scan_depth ) = 1,024
-- "InnoDB: page_cleaner: 1000ms intended loop took ..." may be fixed by lowering lru_scan_depth

( innodb_io_capacity ) = 200 -- When flushing, use this many IOPs.
-- Reads could be slugghish or spiky.

( innodb_io_capacity_max / innodb_io_capacity ) = 2,000 / 200 = 10 -- Capacity: max/plain
-- Recommend 2. Max should be about equal to the IOPs your I/O subsystem can handle. (If the drive type is unknown 2000/200 may be a reasonable pair.)

( Innodb_buffer_pool_reads / Innodb_buffer_pool_read_requests ) = 3,565,561,783 / 162903322931 = 2.2% -- Read requests that had to hit disk
-- Increase innodb_buffer_pool_size (now 134217728) if you have enough RAM.

( Innodb_pages_read / Innodb_buffer_pool_read_requests ) = 3,602,479,499 / 162903322931 = 2.2% -- Read requests that had to hit disk
-- Increase innodb_buffer_pool_size (now 134217728) if you have enough RAM.

( Innodb_buffer_pool_reads ) = 3,565,561,783 / 279710 = 12747 /sec -- Cache misses in the buffer_pool.
-- Increase innodb_buffer_pool_size (now 134217728)? (~100 is limit for HDD, ~1000 is limit for SSDs.)

( (Innodb_buffer_pool_reads + Innodb_buffer_pool_pages_flushed) ) = ((3565561783 + 1105583) ) / 279710 = 12751 /sec -- InnoDB I/O
-- Increase innodb_buffer_pool_size (now 134217728)?

( Innodb_buffer_pool_read_ahead_evicted ) = 5,386,209 / 279710 = 19 /sec

( Innodb_os_log_written / (Uptime / 3600) / innodb_log_files_in_group / innodb_log_file_size ) = 1,564,913,152 / (279710 / 3600) / 2 / 48M = 0.2 -- Ratio
-- (see minutes)

( innodb_flush_method ) = innodb_flush_method = fsync -- How InnoDB should ask the OS to write blocks. Suggest O_DIRECT or O_ALL_DIRECT (Percona) to avoid double buffering. (At least for Unix.) See chrischandler for caveat about O_ALL_DIRECT

( default_tmp_storage_engine ) = default_tmp_storage_engine =

( innodb_flush_neighbors ) = 1 -- A minor optimization when writing blocks to disk.
-- Use 0 for SSD drives; 1 for HDD.

( ( Innodb_pages_read + Innodb_pages_written ) / Uptime / innodb_io_capacity ) = ( 3602479499 + 1115984 ) / 279710 / 200 = 6441.7% -- If > 100%, need more io_capacity.
-- Increase innodb_io_capacity (now 200) if the drives can handle it.

( innodb_io_capacity ) = 200 -- I/O ops per second capable on disk . 100 for slow drives; 200 for spinning drives; 1000-2000 for SSDs; multiply by RAID factor.

( innodb_adaptive_hash_index ) = innodb_adaptive_hash_index = ON -- Whether to use the adapative hash (AHI).
-- ON for mostly readonly; OFF for DDL-heavy

( innodb_adaptive_hash_index ) = innodb_adaptive_hash_index = ON -- Usually should be ON.
-- There are cases where OFF is better. See also innodb_adaptive_hash_index_parts (now 8) (after 5.7.9) and innodb_adaptive_hash_index_partitions (MariaDB and Percona). ON has been implicated in rare crashes (bug 73890). 10.5.0 decided to default OFF.

( innodb_print_all_deadlocks ) = innodb_print_all_deadlocks = OFF -- Whether to log all Deadlocks.
-- If you are plagued with Deadlocks, turn this on. Caution: If you have lots of deadlocks, this may write a lot to disk.

( innodb_ft_result_cache_limit ) = 2,000,000,000 / 16384M = 11.6% -- Byte limit on FULLTEXT resultset. (Possibly not preallocated, but grows?)
-- Lower the setting.

( local_infile ) = local_infile = ON
-- local_infile (now ON) = ON is a potential security issue

( Qcache_lowmem_prunes ) = 6,329,393 / 279710 = 23 /sec -- Running out of room in QC
-- increase query_cache_size (now 16777216)

( Qcache_lowmem_prunes/Qcache_inserts ) = 6,329,393/7792821 = 81.2% -- Removal Ratio (frequency of needing to prune due to not enough memory)

( Qcache_hits / Qcache_inserts ) = 1,619,341 / 7792821 = 0.208 -- Hit to insert ratio -- high is good
-- Consider turning off the query cache.

( Qcache_hits / (Qcache_hits + Com_select) ) = 1,619,341 / (1619341 + 9691638) = 14.3% -- Hit ratio -- SELECTs that used QC
-- Consider turning off the query cache.

( Qcache_hits / (Qcache_hits + Qcache_inserts + Qcache_not_cached) ) = 1,619,341 / (1619341 + 7792821 + 278272) = 16.7% -- Query cache hit rate
-- Probably best to turn off the QC.

( (query_cache_size - Qcache_free_memory) / Qcache_queries_in_cache / query_alloc_block_size ) = (16M - 1272984) / 3058 / 16384 = 0.309 -- query_alloc_block_size vs formula
-- Adjust query_alloc_block_size (now 16384)

( Created_tmp_disk_tables ) = 1,667,989 / 279710 = 6 /sec -- Frequency of creating disk "temp" tables as part of complex SELECTs
-- increase tmp_table_size (now 16777216) and max_heap_table_size (now 16777216).
Check the rules for temp tables on when MEMORY is used instead of MyISAM. Perhaps minor schema or query changes can avoid MyISAM.
Better indexes and reformulation of queries are more likely to help.

( Created_tmp_disk_tables / Questions ) = 1,667,989 / 11788712 = 14.1% -- Pct of queries that needed on-disk tmp table.
-- Better indexes / No blobs / etc.

( Created_tmp_disk_tables / Created_tmp_tables ) = 1,667,989 / 4165525 = 40.0% -- Percent of temp tables that spilled to disk
-- Maybe increase tmp_table_size (now 16777216) and max_heap_table_size (now 16777216); improve indexes; avoid blobs, etc.

( ( Com_stmt_prepare - Com_stmt_close ) / ( Com_stmt_prepare + Com_stmt_close ) ) = ( 473 - 0 ) / ( 473 + 0 ) = 100.0% -- Are you closing your prepared statements?
-- Add Closes.

( Com_stmt_close / Com_stmt_prepare ) = 0 / 473 = 0 -- Prepared statements should be Closed.
-- Check whether all Prepared statements are "Closed".

( binlog_format ) = binlog_format = MIXED -- STATEMENT/ROW/MIXED.
-- ROW is preferred by 5.7 (10.3)

( long_query_time ) = 5 -- Cutoff (Seconds) for defining a "slow" query.
-- Suggest 2

( Subquery_cache_hit / ( Subquery_cache_hit + Subquery_cache_miss ) ) = 0 / ( 0 + 1800 ) = 0 -- Subquery cache hit rate

( log_queries_not_using_indexes ) = log_queries_not_using_indexes = ON -- Whether to include such in slowlog.
-- This clutters the slowlog; turn it off so you can see the real slow queries. And decrease long_query_time (now 5) to catch most interesting queries.

( back_log ) = 80 -- (Autosized as of 5.6.6; based on max_connections)
-- Raising to min(150, max_connections (now 151)) may help when doing lots of connections.

Abnormally small:

```<code>Delete_scan = 0.039 /HR
Handler_read_rnd_next / Handler_read_rnd = 2.06
Handler_write = 0.059 /sec
Innodb_buffer_pool_read_requests / (Innodb_buffer_pool_read_requests + Innodb_buffer_pool_reads ) = 97.9%
Table_locks_immediate = 2.6 /HR
eq_range_index_dive_limit = 0
</code>```

Abnormally large:

```<code>( Innodb_pages_read + Innodb_pages_written ) / Uptime = 12,883
Com_release_savepoint = 5.5 /HR
Com_savepoint = 5.5 /HR
Handler_icp_attempts = 110666 /sec
Handler_icp_match = 110663 /sec
Handler_read_key = 62677 /sec
Handler_savepoint = 5.5 /HR
Handler_tmp_update = 1026 /sec
Handler_tmp_write = 40335 /sec
Innodb_buffer_pool_read_ahead = 131 /sec
Innodb_buffer_pool_reads * innodb_page_size / innodb_buffer_pool_size = 43524924.1%
Innodb_data_read = 211015030 /sec
Innodb_data_reads = 12879 /sec
Innodb_pages_read = 12879 /sec
Innodb_pages_read + Innodb_pages_written = 12883 /sec
Select_full_range_join = 1.1 /sec
Select_full_range_join / Com_select = 3.0%
Tc_log_page_size = 4,096
innodb_open_files = 16,293
log_slow_rate_limit = 1,000
query_cache_limit = 3.36e+7
table_open_cache / max_connections = 107
</code>```

Abnormal strings:

```<code>Innodb_have_snappy = ON
Slave_heartbeat_period = 0
Slave_received_heartbeats = 0
aria_recover_options = BACKUP,QUICK
innodb_fast_shutdown = 1
log_output = FILE,TABLE
log_slow_admin_statements = ON
myisam_stats_method = NULLS_UNEQUAL
old_alter_table = DEFAULT
sql_slave_skip_counter = 0
time_zone = +05:30
</code>```

Body:
I take my Live server backup using mysqldump command via CRON job in my Ubuntu Server via Bash Shell Script and the same script uploads the backup to my backup server also. Earlier this was working fine but now I am facing slowness issue (it takes 1 hour to backup and upload on backup server) as one of the database Table size has grown to 5GB and consists of 10 Million Records. I saw on a thread that we can fasten the SQL insertion via bulk/group execution of SQL -  How can mysql insert millions records faster?

But in my case I am unsure how can I create a Shell Script to perform the same.

The requirement is I want to export all my SQL Database tables in groups of maximum 10k so that execution can be faster while it is getting imported on the server.

I have written this code on my server bash script:

#!/bin/bash
cd /tmp
file=$(date +%F-%T).sql
mysqldump \
  --host ${MYSQL_HOST} \
  --port ${MYSQL_PORT} \
  -u ${MYSQL_USER} \
  --password="${MYSQL_PASS}" \
  ${MYSQL_DB} > ${file}
if [ "${?}" -eq 0 ]; then
  mysql -umyuser -pmypassword -h 198.168.1.3  -e "show databases"
  mysql -umyuser -pmypassword -h 198.168.1.3 -D backup_db -e "drop database backup_db"
  mysql -umyuser -pmypassword -h 198.168.1.3  -e "create database backup_db"
  mysql -umyuser -pmypassword -h 198.168.1.3 backup_db < ${file}
  gzip ${file}
  aws s3 cp ${file}.gz s3://${S3_BUCKET}/live_db/
  rm ${file}.gz
else
  echo "Error backing up mysql"
  exit 255
fi

The backup server and live server share the same AWS hardware configuration: 16GB RAM, 4 CPU, 100GB SSD.

These are the screenshots and data:

Screenshot and Queries for Debugging on the Live Server:
Information Schema Tables:

https://i.imgur.com/RnjQwbP.png

SHOW GLOBAL STATUS:

https://pastebin.com/raw/MuJYwnsm

SHOW GLOBAL VARIABLES:

https://pastebin.com/raw/wdvn97XP

Screenshot and Queries for Debugging on the Backup Server:

https://i.imgur.com/rB7qcYU.png
https://pastebin.com/raw/K7vHXqWi
https://pastebin.com/raw/PR2gWpqe

Server workload is almost negligible. There is no load all the times, I have also monitored via AWS Monitoring Panel, and that's the only reason to take more than required resource server so that it never gets exhausted. I have taken 16GB RAM and 4 CPU which are more than more than sufficient. AWS Monitoring Panel showed Max usage 6% rarely and maximum times it is around 1%.

Body:
Analysis of GLOBAL STATUS and VARIABLES:

Observations:

Version: 10.3.32-MariaDB-0ubuntu0.20.04.1-log

16 GB of RAM

Uptime = 3d 05:41:50

42.1 QPS

The More Important Issues:

Some setting suggestions for better memory utilization:

key_buffer_size = 20M
innodb_buffer_pool_size = 8G
table_open_cache = 300
innodb_open_files = 1000
query_cache_type = OFF
query_cache_size = 0

Some setting suggestions for other reasons:

eq_range_index_dive_limit = 20
log_queries_not_using_indexes = OFF

Recommend using the slowlog (with long_query_time = 1) to locate the naughty queries.  Then we can discuss how to improve them.
http://mysql.rjweb.org/doc.php/mysql_analysis#slow_queries_and_slowlog

Details and other observations:

( (key_buffer_size - 1.2 * Key_blocks_used * 1024) ) = ((512M - 1.2 * 8 * 1024)) / 16384M = 3.1% -- Percent of RAM wasted in key_buffer.
-- Decrease key_buffer_size (now 536870912).

( Key_blocks_used * 1024 / key_buffer_size ) = 8 * 1024 / 512M = 0.00% -- Percent of key_buffer used. High-water-mark.
-- Lower key_buffer_size (now 536870912) to avoid unnecessary memory usage.

( (key_buffer_size / 0.20 + innodb_buffer_pool_size / 0.70) ) = ((512M / 0.20 + 128M / 0.70)) / 16384M = 16.7% -- Most of available ram should be made available for caching.
-- http://mysql.rjweb.org/doc.php/memory

( table_open_cache ) = 16,293 -- Number of table descriptors to cache
-- Several hundred is usually good.

( innodb_buffer_pool_size ) = 128M -- InnoDB Data + Index cache
-- 128M (an old default) is woefully small.

( innodb_buffer_pool_size ) = 128 / 16384M = 0.78% -- % of RAM used for InnoDB buffer_pool
-- Set to about 70% of available RAM. (To low is less efficient; too high risks swapping.)

( innodb_lru_scan_depth ) = 1,024
-- "InnoDB: page_cleaner: 1000ms intended loop took ..." may be fixed by lowering lru_scan_depth

( innodb_io_capacity ) = 200 -- When flushing, use this many IOPs.
-- Reads could be slugghish or spiky.

( innodb_io_capacity_max / innodb_io_capacity ) = 2,000 / 200 = 10 -- Capacity: max/plain
-- Recommend 2. Max should be about equal to the IOPs your I/O subsystem can handle. (If the drive type is unknown 2000/200 may be a reasonable pair.)

( Innodb_buffer_pool_reads / Innodb_buffer_pool_read_requests ) = 3,565,561,783 / 162903322931 = 2.2% -- Read requests that had to hit disk
-- Increase innodb_buffer_pool_size (now 134217728) if you have enough RAM.

( Innodb_pages_read / Innodb_buffer_pool_read_requests ) = 3,602,479,499 / 162903322931 = 2.2% -- Read requests that had to hit disk
-- Increase innodb_buffer_pool_size (now 134217728) if you have enough RAM.

( Innodb_buffer_pool_reads ) = 3,565,561,783 / 279710 = 12747 /sec -- Cache misses in the buffer_pool.
-- Increase innodb_buffer_pool_size (now 134217728)? (~100 is limit for HDD, ~1000 is limit for SSDs.)

( (Innodb_buffer_pool_reads + Innodb_buffer_pool_pages_flushed) ) = ((3565561783 + 1105583) ) / 279710 = 12751 /sec -- InnoDB I/O
-- Increase innodb_buffer_pool_size (now 134217728)?

( Innodb_buffer_pool_read_ahead_evicted ) = 5,386,209 / 279710 = 19 /sec

( Innodb_os_log_written / (Uptime / 3600) / innodb_log_files_in_group / innodb_log_file_size ) = 1,564,913,152 / (279710 / 3600) / 2 / 48M = 0.2 -- Ratio
-- (see minutes)

( innodb_flush_method ) = innodb_flush_method = fsync -- How InnoDB should ask the OS to write blocks. Suggest O_DIRECT or O_ALL_DIRECT (Percona) to avoid double buffering. (At least for Unix.) See chrischandler for caveat about O_ALL_DIRECT

( default_tmp_storage_engine ) = default_tmp_storage_engine =

( innodb_flush_neighbors ) = 1 -- A minor optimization when writing blocks to disk.
-- Use 0 for SSD drives; 1 for HDD.

( ( Innodb_pages_read + Innodb_pages_written ) / Uptime / innodb_io_capacity ) = ( 3602479499 + 1115984 ) / 279710 / 200 = 6441.7% -- If > 100%, need more io_capacity.
-- Increase innodb_io_capacity (now 200) if the drives can handle it.

( innodb_io_capacity ) = 200 -- I/O ops per second capable on disk . 100 for slow drives; 200 for spinning drives; 1000-2000 for SSDs; multiply by RAID factor.

( innodb_adaptive_hash_index ) = innodb_adaptive_hash_index = ON -- Whether to use the adapative hash (AHI).
-- ON for mostly readonly; OFF for DDL-heavy

( innodb_adaptive_hash_index ) = innodb_adaptive_hash_index = ON -- Usually should be ON.
-- There are cases where OFF is better. See also innodb_adaptive_hash_index_parts (now 8) (after 5.7.9) and innodb_adaptive_hash_index_partitions (MariaDB and Percona). ON has been implicated in rare crashes (bug 73890). 10.5.0 decided to default OFF.

( innodb_print_all_deadlocks ) = innodb_print_all_deadlocks = OFF -- Whether to log all Deadlocks.
-- If you are plagued with Deadlocks, turn this on. Caution: If you have lots of deadlocks, this may write a lot to disk.

( innodb_ft_result_cache_limit ) = 2,000,000,000 / 16384M = 11.6% -- Byte limit on FULLTEXT resultset. (Possibly not preallocated, but grows?)
-- Lower the setting.

( local_infile ) = local_infile = ON
-- local_infile (now ON) = ON is a potential security issue

( Qcache_lowmem_prunes ) = 6,329,393 / 279710 = 23 /sec -- Running out of room in QC
-- increase query_cache_size (now 16777216)

( Qcache_lowmem_prunes/Qcache_inserts ) = 6,329,393/7792821 = 81.2% -- Removal Ratio (frequency of needing to prune due to not enough memory)

( Qcache_hits / Qcache_inserts ) = 1,619,341 / 7792821 = 0.208 -- Hit to insert ratio -- high is good
-- Consider turning off the query cache.

( Qcache_hits / (Qcache_hits + Com_select) ) = 1,619,341 / (1619341 + 9691638) = 14.3% -- Hit ratio -- SELECTs that used QC
-- Consider turning off the query cache.

( Qcache_hits / (Qcache_hits + Qcache_inserts + Qcache_not_cached) ) = 1,619,341 / (1619341 + 7792821 + 278272) = 16.7% -- Query cache hit rate
-- Probably best to turn off the QC.

( (query_cache_size - Qcache_free_memory) / Qcache_queries_in_cache / query_alloc_block_size ) = (16M - 1272984) / 3058 / 16384 = 0.309 -- query_alloc_block_size vs formula
-- Adjust query_alloc_block_size (now 16384)

( Created_tmp_disk_tables ) = 1,667,989 / 279710 = 6 /sec -- Frequency of creating disk "temp" tables as part of complex SELECTs
-- increase tmp_table_size (now 16777216) and max_heap_table_size (now 16777216).
Check the rules for temp tables on when MEMORY is used instead of MyISAM. Perhaps minor schema or query changes can avoid MyISAM.
Better indexes and reformulation of queries are more likely to help.

( Created_tmp_disk_tables / Questions ) = 1,667,989 / 11788712 = 14.1% -- Pct of queries that needed on-disk tmp table.
-- Better indexes / No blobs / etc.

( Created_tmp_disk_tables / Created_tmp_tables ) = 1,667,989 / 4165525 = 40.0% -- Percent of temp tables that spilled to disk
-- Maybe increase tmp_table_size (now 16777216) and max_heap_table_size (now 16777216); improve indexes; avoid blobs, etc.

( ( Com_stmt_prepare - Com_stmt_close ) / ( Com_stmt_prepare + Com_stmt_close ) ) = ( 473 - 0 ) / ( 473 + 0 ) = 100.0% -- Are you closing your prepared statements?
-- Add Closes.

( Com_stmt_close / Com_stmt_prepare ) = 0 / 473 = 0 -- Prepared statements should be Closed.
-- Check whether all Prepared statements are "Closed".

( binlog_format ) = binlog_format = MIXED -- STATEMENT/ROW/MIXED.
-- ROW is preferred by 5.7 (10.3)

( long_query_time ) = 5 -- Cutoff (Seconds) for defining a "slow" query.
-- Suggest 2

( Subquery_cache_hit / ( Subquery_cache_hit + Subquery_cache_miss ) ) = 0 / ( 0 + 1800 ) = 0 -- Subquery cache hit rate

( log_queries_not_using_indexes ) = log_queries_not_using_indexes = ON -- Whether to include such in slowlog.
-- This clutters the slowlog; turn it off so you can see the real slow queries. And decrease long_query_time (now 5) to catch most interesting queries.

( back_log ) = 80 -- (Autosized as of 5.6.6; based on max_connections)
-- Raising to min(150, max_connections (now 151)) may help when doing lots of connections.

Abnormally small:

Delete_scan = 0.039 /HR
Handler_read_rnd_next / Handler_read_rnd = 2.06
Handler_write = 0.059 /sec
Innodb_buffer_pool_read_requests / (Innodb_buffer_pool_read_requests + Innodb_buffer_pool_reads ) = 97.9%
Table_locks_immediate = 2.6 /HR
eq_range_index_dive_limit = 0

Abnormally large:

( Innodb_pages_read + Innodb_pages_written ) / Uptime = 12,883
Com_release_savepoint = 5.5 /HR
Com_savepoint = 5.5 /HR
Handler_icp_attempts = 110666 /sec
Handler_icp_match = 110663 /sec
Handler_read_key = 62677 /sec
Handler_savepoint = 5.5 /HR
Handler_tmp_update = 1026 /sec
Handler_tmp_write = 40335 /sec
Innodb_buffer_pool_read_ahead = 131 /sec
Innodb_buffer_pool_reads * innodb_page_size / innodb_buffer_pool_size = 43524924.1%
Innodb_data_read = 211015030 /sec
Innodb_data_reads = 12879 /sec
Innodb_pages_read = 12879 /sec
Innodb_pages_read + Innodb_pages_written = 12883 /sec
Select_full_range_join = 1.1 /sec
Select_full_range_join / Com_select = 3.0%
Tc_log_page_size = 4,096
innodb_open_files = 16,293
log_slow_rate_limit = 1,000
query_cache_limit = 3.36e+7
table_open_cache / max_connections = 107

Abnormal strings:

Innodb_have_snappy = ON
Slave_heartbeat_period = 0
Slave_received_heartbeats = 0
aria_recover_options = BACKUP,QUICK
innodb_fast_shutdown = 1
log_output = FILE,TABLE
log_slow_admin_statements = ON
myisam_stats_method = NULLS_UNEQUAL
old_alter_table = DEFAULT
sql_slave_skip_counter = 0
time_zone = +05:30


问:
Hiding empty inputs by parent row in jquery
I have the following HTML:

```<code><table>
   <tr class="row">
        <td class="field">
            <input type="text" />
        </td>
        <td class="field">
            <input type="text" />
        </td>
        <td class="field">
            <input type="text" />
        </td>
   </tr>
   <tr>
   ...
   ...
   </tr>
</table>
</code>```

I want to be able to hide the
 with the class="row" but only when the input within the  with the class="field" is empty when the page loads.

I've tried this, but it doesn't work:

$('td.field:text[value=""]').parents('tr.row').hide();

However, for some reason, this DOES work:

$('td.field).parents('tr.row').hide();

(ie: it hides all of the rows with class="row")

Also, the following DOES work:

$('td.field:text[value=""]').val('test');

(ie: all empty inputs are populated with 'test' on page load)

I'm new to JQuery so I'm suspecting that I may have just misunderstood the way chaining works. can anyone give me any pointers? It semms like the two parts of what I am trying to do are correct when attempted separately, but don't work together as one.

答:
I think it should be in this way:

```<code>$('td.field :text[value=""]').parents('tr.row').hide();
</code>```

The reason: :text (input) is child from td.field. If you put td.field:text it's wrong because they are diferente selectors.

Body:
I have the following HTML:

            <input type="text" />

            <input type="text" />

            <input type="text" />

   ...
   ...

I want to be able to hide the
 with the class="row" but only when the input within the  with the class="field" is empty when the page loads.

I've tried this, but it doesn't work:

$('td.field:text[value=""]').parents('tr.row').hide();

However, for some reason, this DOES work:

$('td.field).parents('tr.row').hide();

(ie: it hides all of the rows with class="row")

Also, the following DOES work:

$('td.field:text[value=""]').val('test');

(ie: all empty inputs are populated with 'test' on page load)

I'm new to JQuery so I'm suspecting that I may have just misunderstood the way chaining works. can anyone give me any pointers? It semms like the two parts of what I am trying to do are correct when attempted separately, but don't work together as one.

Body:
I think it should be in this way:

$('td.field :text[value=""]').parents('tr.row').hide();

The reason: :text (input) is child from td.field. If you put td.field:text it's wrong because they are diferente selectors.


问:
Chromedriver for linux32 does not exist - Python Selenium Chromedriver
I'm creating a cross platform python script that executes some commands with selenium.
I have two questions:

How come the following script works on windows but doesn't work on Raspberry pi OS 32bit? The only way this works is to remove the webdriver-manager, but this requires
manual installation of the webdriver.
I'm using a raspberry pi 3

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.utils import ChromeType

options = Options()
options.headless = True
options.add_experimental_option("excludeSwitches", ["enable-logging"])
driver = webdriver.Chrome(service=Service(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()), options=options)
driver.get("http://www.google.com")
print(driver.title)
</code>```

The output is:

```<code>pi@raspberrypi:~/Documents/Software $ /bin/python /home/pi/Documents/Software/test.py

====== WebDriver manager ======
Current chromium version is 95.0.4638
Get LATEST chromedriver version for 95.0.4638 chromium
There is no [linux32] chromedriver for browser  in cache
Trying to download new driver from https://chromedriver.storage.googleapis.com/95.0.4638.69/chromedriver_linux32.zip
Traceback (most recent call last):
  File "/home/pi/Documents/Software/test.py", line 10, in <module>
    driver = webdriver.Chrome(service=Service(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()), options=options)
  File "/home/pi/.local/lib/python3.9/site-packages/webdriver_manager/chrome.py", line 32, in install
    driver_path = self._get_driver_path(self.driver)
  File "/home/pi/.local/lib/python3.9/site-packages/webdriver_manager/manager.py", line 30, in _get_driver_path
    file = download_file(driver.get_url(), driver.ssl_verify)
  File "/home/pi/.local/lib/python3.9/site-packages/webdriver_manager/utils.py", line 98, in download_file
    validate_response(response)
  File "/home/pi/.local/lib/python3.9/site-packages/webdriver_manager/utils.py", line 80, in validate_response
    raise ValueError("There is no such driver by url {}".format(resp.url))
ValueError: There is no such driver by url https://chromedriver.storage.googleapis.com/95.0.4638.69/chromedriver_linux32.zip
</code>```

How can I create a python script that uses selenium webdriver in headless mode and works on every platform? I mean, if I use chromewebdriver in the script, the user who will use the script must have chrome installed, as well as if a firefox the user must have firefox installed. Is there any webdriver that works without external script installations?

Thanks

EDIT:

The problem is not with the webdriver manager but the fact that chromedrivers for chromium do not exist for linux32. In fact at the address: "https://chromedriver.storage.googleapis.com/95.0.4638.69/chromedriver_linux32.zip" there is no chromedriver, but replacing linux32 with linux64 a package is downloaded but not compatible with linux32.
The thing I don't understand is if the chromedrivers for linux32 don't exist then why installing them with: "sudo apt-get install chromium-chromedriver" and then removing the webdriver-manager calls from the code, does the python script work? Then there are chromedrivers for linux32, only they are not present in the main chromedriver site.
I am using a raspberry pi 3 with chromium 95.0.4638.69.

答:
As there is no linux32 chromedriver developped by the official team (e.g. https://chromedriver.storage.googleapis.com/index.html?path=99.0.4844.17/), you can't use webdriver_manager because it's looking at their repositories.

Yet a compatible chromedriver version is maintained by the Raspian team, so in order to make it works you need to :

Install chromedriver for raspberry. e.g. for Linux:

```<code>sudo apt-get install chromium-chromedriver
</code>```

When you instantiate your driver, you need to tell him where to find this chromedriver. Plus, you should also state that you use Chromium instead of Chrome (if so):

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

options = Options()
# browser is Chromium instead of Chrome
options.BinaryLocation = "/usr/bin/chromium-browser"
# we use custom chromedriver for raspberry
driver_path = "/usr/bin/chromedriver"
driver = webdriver.Chrome(options=options, service=Service(driver_path))
</code>```

Then you're good to go:

```<code>driver.get("https://stackoverflow.com/")
</code>```

If you need a code that works for every platform, the best option I found so far is to distinguished raspberry pi from the other system:

```<code>import platform
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

options = Options()
# a few usefull options
options.add_argument("--disable-infobars")
options.add_argument("start-maximized")
options.add_argument("--disable-extensions")
options.add_argument("--headless") # if you want it headless

if platform.system() == "Linux" and platform.machine() == "armv7l":
    # if raspi
    options.BinaryLocation = ("/usr/bin/chromium-browser")
    service = Service("/usr/bin/chromedriver")
else: # if not raspi and considering you're using Chrome
    service = Service(ChromeDriverManager().install())

driver = webdriver.Chrome(
    service=service,
    options=options
    )
</code>```

Considering your question about not having to install Chrome manually to make Selenium works, you could probably install Chrome through a script to be sure that the user has it.
It will also work for a Docker use, e.g. for a DockerFile with a Linux amd64 environment:

```<code>   RUN wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
   RUN dpkg -i google-chrome-stable_current_amd64.deb; apt-get -fy instal
</code>```

Body:
I'm creating a cross platform python script that executes some commands with selenium.
I have two questions:

How come the following script works on windows but doesn't work on Raspberry pi OS 32bit? The only way this works is to remove the webdriver-manager, but this requires
manual installation of the webdriver.
I'm using a raspberry pi 3

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.utils import ChromeType

options = Options()
options.headless = True
options.add_experimental_option("excludeSwitches", ["enable-logging"])
driver = webdriver.Chrome(service=Service(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()), options=options)
driver.get("http://www.google.com")
print(driver.title)

The output is:

pi@raspberrypi:~/Documents/Software $ /bin/python /home/pi/Documents/Software/test.py

====== WebDriver manager ======
Current chromium version is 95.0.4638
Get LATEST chromedriver version for 95.0.4638 chromium
There is no [linux32] chromedriver for browser  in cache
Trying to download new driver from https://chromedriver.storage.googleapis.com/95.0.4638.69/chromedriver_linux32.zip
Traceback (most recent call last):
  File "/home/pi/Documents/Software/test.py", line 10, in <module>
    driver = webdriver.Chrome(service=Service(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()), options=options)
  File "/home/pi/.local/lib/python3.9/site-packages/webdriver_manager/chrome.py", line 32, in install
    driver_path = self._get_driver_path(self.driver)
  File "/home/pi/.local/lib/python3.9/site-packages/webdriver_manager/manager.py", line 30, in _get_driver_path
    file = download_file(driver.get_url(), driver.ssl_verify)
  File "/home/pi/.local/lib/python3.9/site-packages/webdriver_manager/utils.py", line 98, in download_file
    validate_response(response)
  File "/home/pi/.local/lib/python3.9/site-packages/webdriver_manager/utils.py", line 80, in validate_response
    raise ValueError("There is no such driver by url {}".format(resp.url))
ValueError: There is no such driver by url https://chromedriver.storage.googleapis.com/95.0.4638.69/chromedriver_linux32.zip

How can I create a python script that uses selenium webdriver in headless mode and works on every platform? I mean, if I use chromewebdriver in the script, the user who will use the script must have chrome installed, as well as if a firefox the user must have firefox installed. Is there any webdriver that works without external script installations?

Thanks

EDIT:

The problem is not with the webdriver manager but the fact that chromedrivers for chromium do not exist for linux32. In fact at the address: "https://chromedriver.storage.googleapis.com/95.0.4638.69/chromedriver_linux32.zip" there is no chromedriver, but replacing linux32 with linux64 a package is downloaded but not compatible with linux32.
The thing I don't understand is if the chromedrivers for linux32 don't exist then why installing them with: "sudo apt-get install chromium-chromedriver" and then removing the webdriver-manager calls from the code, does the python script work? Then there are chromedrivers for linux32, only they are not present in the main chromedriver site.
I am using a raspberry pi 3 with chromium 95.0.4638.69.

Body:
As there is no linux32 chromedriver developped by the official team (e.g. https://chromedriver.storage.googleapis.com/index.html?path=99.0.4844.17/), you can't use webdriver_manager because it's looking at their repositories.

Yet a compatible chromedriver version is maintained by the Raspian team, so in order to make it works you need to :

Install chromedriver for raspberry. e.g. for Linux:

sudo apt-get install chromium-chromedriver

When you instantiate your driver, you need to tell him where to find this chromedriver. Plus, you should also state that you use Chromium instead of Chrome (if so):

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

options = Options()
# browser is Chromium instead of Chrome
options.BinaryLocation = "/usr/bin/chromium-browser"
# we use custom chromedriver for raspberry
driver_path = "/usr/bin/chromedriver"
driver = webdriver.Chrome(options=options, service=Service(driver_path))

Then you're good to go:

driver.get("https://stackoverflow.com/")

If you need a code that works for every platform, the best option I found so far is to distinguished raspberry pi from the other system:

import platform
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

options = Options()
# a few usefull options
options.add_argument("--disable-infobars")
options.add_argument("start-maximized")
options.add_argument("--disable-extensions")
options.add_argument("--headless") # if you want it headless

if platform.system() == "Linux" and platform.machine() == "armv7l":
    # if raspi
    options.BinaryLocation = ("/usr/bin/chromium-browser")
    service = Service("/usr/bin/chromedriver")
else: # if not raspi and considering you're using Chrome
    service = Service(ChromeDriverManager().install())

driver = webdriver.Chrome(
    service=service,
    options=options
    )

Considering your question about not having to install Chrome manually to make Selenium works, you could probably install Chrome through a script to be sure that the user has it.
It will also work for a Docker use, e.g. for a DockerFile with a Linux amd64 environment:

   RUN wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
   RUN dpkg -i google-chrome-stable_current_amd64.deb; apt-get -fy instal


问:
Multiline mode in Regex not performing according to documentation
According to the .Net Standard:

The RegexOptions.Multiline option, or the m inline option, enables the
regular expression engine to handle an input string that consists of
multiple lines. It changes the interpretation of the ^ and $ language
elements so that they match the beginning and end of a line, instead
of the beginning and end of the input string.

By default, $ matches only the end of the input string. If you specify
the RegexOptions.Multiline option, it matches either the newline
character (\n) or the end of the input string.

(emphasis mine)

Source: https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-options#multiline-mode

This seems to say that $ matches the newline character.  However this does not seem to be the case.  The code:

```<code>var m = Regex.Match("123\n456", @"123$", RegexOptions.Multiline);
Console.WriteLine(m.Length);
</code>```

prints 3, not 4 as would be expected if $ matched newline.

Is this a bug?  A documentation error?

答:
This is a documentation error as any anchor (^, $, \A, \Z, \z, \G) are zero-width assertions and do not consume any text. Non-consuming patterns only match positions inside a string, not the text itself.

If you specify the RegexOptions.Multiline option, the $ anchor matches either the position immediately before a newline character (\n, line feed (LF) char) or the end of the input string.

Body:
According to the .Net Standard:

The RegexOptions.Multiline option, or the m inline option, enables the
regular expression engine to handle an input string that consists of
multiple lines. It changes the interpretation of the ^ and $ language
elements so that they match the beginning and end of a line, instead
of the beginning and end of the input string.

By default, $ matches only the end of the input string. If you specify
the RegexOptions.Multiline option, it matches either the newline
character (\n) or the end of the input string.

(emphasis mine)

Source: https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-options#multiline-mode

This seems to say that $ matches the newline character.  However this does not seem to be the case.  The code:

var m = Regex.Match("123\n456", @"123$", RegexOptions.Multiline);
Console.WriteLine(m.Length);

prints 3, not 4 as would be expected if $ matched newline.

Is this a bug?  A documentation error?


问:
Flutter The method 'User' isn't defined for the type '_LeaveApplicationState'
I am building an app using Flutter and Firebase for the backend. I was Following a tutorial guide but when I have written the code am getting two types of errors, the first one being;
"The method 'User' isn't defined for the type '_LeaveApplicationState' "

```<code>class LeaveApplication extends StatefulWidget {
  const LeaveApplication({Key? key}) : super(key: key);

  @override
  _LeaveApplicationState createState() => _LeaveApplicationState();
}

class _LeaveApplicationState extends State<LeaveApplication> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final controllerFirstName = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Container(
          margin: EdgeInsets.all(24),
          child: Form(
            key: _formKey,
            child: Column(
              children: <Widget>[
                const Text(
                  'Apply For Work Leave',
                  style: TextStyle(
                    fontWeight: FontWeight.w700,
                    fontSize: 18,
                    color: Colors.black,
                  ),
                ),
                //rest of code....

                  child: MaterialButton(
                    color: Colors.lightBlue,
                    onPressed: () {
                      final user = **User**(
                        fname: controllerFirstName.text,
                        lname: controllerLastName.text,
                        email: controllerEmail.text,
                        phoneno: int.parse(controllerPhoneNo.text),
                        leave: controllerLeaveType,
                        duration: controllerDuration.text,
                      );

                      Navigator.pop(context);

                      createUser(user);

                      if (_formKey.currentState!.validate()) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('Request Sent')),
                        );
                      }
                    },

                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future createUser(**User** user) async {
    final docUser = FirebaseFirestore.instance.collection('employees').doc();
    user.id = docUser.id;

    final json = user.toJson();
    await docUser.set(json);
  }
}
</code>```

the second error is "Undefined class 'User'."
the errors arise in the areas which are in bold/asterisk.
I want the user who has logged in to be able to put in details and send them to firebase datebase. Can anyone help

答: If you are importing your user model class this should work fine i will sujjest you to change the name of your user class to something else because firebase also have a user class might you had imported that one please recheck again and let me know if this works</p>

Body:
I am building an app using Flutter and Firebase for the backend. I was Following a tutorial guide but when I have written the code am getting two types of errors, the first one being;
"The method 'User' isn't defined for the type '_LeaveApplicationState' "

class LeaveApplication extends StatefulWidget {
  const LeaveApplication({Key? key}) : super(key: key);

  @override
  _LeaveApplicationState createState() => _LeaveApplicationState();
}

class _LeaveApplicationState extends State<LeaveApplication> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final controllerFirstName = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Container(
          margin: EdgeInsets.all(24),
          child: Form(
            key: _formKey,
            child: Column(
              children: <Widget>[
                const Text(
                  'Apply For Work Leave',
                  style: TextStyle(
                    fontWeight: FontWeight.w700,
                    fontSize: 18,
                    color: Colors.black,
                  ),
                ),
                //rest of code....

                  child: MaterialButton(
                    color: Colors.lightBlue,
                    onPressed: () {
                      final user = **User**(
                        fname: controllerFirstName.text,
                        lname: controllerLastName.text,
                        email: controllerEmail.text,
                        phoneno: int.parse(controllerPhoneNo.text),
                        leave: controllerLeaveType,
                        duration: controllerDuration.text,
                      );

                      Navigator.pop(context);

                      createUser(user);

                      if (_formKey.currentState!.validate()) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('Request Sent')),
                        );
                      }
                    },

                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future createUser(**User** user) async {
    final docUser = FirebaseFirestore.instance.collection('employees').doc();
    user.id = docUser.id;

    final json = user.toJson();
    await docUser.set(json);
  }
}

the second error is "Undefined class 'User'."
the errors arise in the areas which are in bold/asterisk.
I want the user who has logged in to be able to put in details and send them to firebase datebase. Can anyone help


问:
window.location.href with React.js
I need help.

If I use JSON.stringify(window.location.href), is there any way to show that URL without "" (quotes / as a string)? So showing it like a link and not a string.

If not... Is there a way to use window.location.href in React without having to use JSON.stringify()?

Or maybe use something to replace window.location.href but same result?

Basically need to show / use that url as a link (html   tag) not as a string.

New images!

code

useStickyState function

--- Ignore the key: URL_HREF its MY_URL instead ---

with JSON.stringify

without JSON.stringify

Any help is appreciated!

答:
This seems to do what you're asking.

class SimpleExample extends React.Component {

    render() {
        return (

         Link

        );
    }
}

ReactDOM.render(<SimpleExample />, document.getElementById('example'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.2/umd/react-dom.production.min.js"></script>

<div id="example"></div></code>```

EDIT:
But I'm also curious why  Link  doesn't work.

Title: window.location.href with React.js

Body:
This seems to do what you're asking.

class SimpleExample extends React.Component {

    render() {
        return (
            <div>
        <a href={`${window.location.href}`}> Link </a>
      </div>
        );
    }
}

ReactDOM.render(<SimpleExample />, document.getElementById('example'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.2/umd/react-dom.production.min.js"></script>

<div id="example"></div>

EDIT:
But I'm also curious why <a href={window.location.href}> Link </a> doesn't work.


问:
while loop keeps executing
I don't understand why the while keeps executing even though I have written the name "gabriel" or the name "tommy"</p>
```<code>nombre = ""
while nombre != "gabriel" or nombre !="tommy":
nombre = input()
if nombre != "gabriel" or nombre != "tommy":
    print("ingrese su nombre nuevamente")
else:
    print("su nombre es ")
    break
</code>```

答:
```<code>nombre != "gabriel" or nombre !="tommy"
</code>```

No matter what the user enters, this condition will always be true.

If they enter "gabriel", then it is not equal to "tommy".

If they enter "tommy", then it is not equal to "gabriel".

Use and instead of or.

Title: while loop keeps executing

Body:
I don't understand why the while keeps executing even though I have written the name "gabriel" or the name "tommy"

nombre = ""
while nombre != "gabriel" or nombre !="tommy":
nombre = input()
if nombre != "gabriel" or nombre != "tommy":
    print("ingrese su nombre nuevamente")
else:
    print("su nombre es ")
    break

Body:
nombre != "gabriel" or nombre !="tommy"

No matter what the user enters, this condition will always be true.

If they enter "gabriel", then it is not equal to "tommy".

If they enter "tommy", then it is not equal to "gabriel".

Use and instead of or.


问:
Adding Array extension for multidimensional arrays in swift?
I have a matrix, ie array of arrays. I want to add some methods to better handle this as extension to Array. I was thinking of writting something like this:

```<code>extension Array where Element == Array {
    // my methods
}
</code>```

But alas, this won't compile, since I have added recursive definition. Obviosly I can omit part where Element == Array, but it seems like nice touch to have these methods show only when appropriate. Is there some other way this can be achieved?

EDIT:
as per @Leo Dabus suggestion, I will provide some use case:

I have app that has multiple table view controllers. In each of them I have sections and rows. In order to populate them, I use two arrays: one for section names, and the other one is array of arrays of objects(or structs) -> corresponding sections and rows in index paths. So I want to write methods for manipulation array of arrays based on index path. For example:

```<code>a[indexPath] = sender
</code>```

These objects vary, some are simple strings, some are more complex

答:
The solution is to use a Contextual Where Clause on a function, rather than a where on the extension. In a function context you can introduce generic parameters.

Here is an example which computes the trace of a 2D matrix:

```<code>public extension Array {
    func trace<T: BinaryFloatingPoint>() -> T where Element == Array<T> {
        var total: T = 0

        for i in 0...count {
            let row = self[i]
            total += row[i]
        }

        return total
    }
}
</code>```

However, if you plan to implement 2D arrays, I strongly suggest you consider using a single array of size cols * rows and then indexing it appropriately.

Body:
I have a matrix, ie array of arrays. I want to add some methods to better handle this as extension to Array. I was thinking of writting something like this:

extension Array where Element == Array {
    // my methods
}

But alas, this won't compile, since I have added recursive definition. Obviosly I can omit part where Element == Array, but it seems like nice touch to have these methods show only when appropriate. Is there some other way this can be achieved?

EDIT:
as per @Leo Dabus suggestion, I will provide some use case:

I have app that has multiple table view controllers. In each of them I have sections and rows. In order to populate them, I use two arrays: one for section names, and the other one is array of arrays of objects(or structs) -> corresponding sections and rows in index paths. So I want to write methods for manipulation array of arrays based on index path. For example:

a[indexPath] = sender

These objects vary, some are simple strings, some are more complex

Body:
The solution is to use a Contextual Where Clause on a function, rather than a where on the extension. In a function context you can introduce generic parameters.

Here is an example which computes the trace of a 2D matrix:

public extension Array {
    func trace<T: BinaryFloatingPoint>() -> T where Element == Array<T> {
        var total: T = 0

        for i in 0...count {
            let row = self[i]
            total += row[i]
        }

        return total
    }
}

However, if you plan to implement 2D arrays, I strongly suggest you consider using a single array of size cols * rows and then indexing it appropriately.


问:
Is there a way to connect via SFTP without using pem key?
I have an EC2 instance running and the only method I can access the server to upload something is through a pem key. Now, we need to create users for them to upload their own files into the server. I have successfully allowed FTP connection using vsftpd but my senior devs wants me to make the server allow other users with username and password only without pem key. What should I configure inside my EC2 instance?

edit : On our team. We mainly use filezilla and winscp

答:
Generally speaking you'll find that many of the Linux AMIs you can use to launch an instance have ssh password authentication disabled.  For your case, the procedure is:

Edit /etc/ssh/sshd_config to allow password authentication

Reload or restart the sshd daemon to pick up the change

Create users

Set a password

The change to make in /etc/ssh/sshd_config is to set PasswordAuthentication yes.  It could either exist and be commented out or it could exist and be set to no.  Just make sure it is set only once in the file.

With that set, you can reload or restart sshd, and depending on your distribution/version combination, it could be one of the following:

sudo systemctl reload sshd

sudo service sshd reload

sudo restart sshd
Also depending on distribution and version, the service may be called ssh instead of sshd, so you may need to try that too.

Creating a user is done with the useradd command, like sudo useradd <username>.  There are different switches that you can use to specify things like home directory, shell, group membership, etc.  Some Linux distributions set defaults on these, and others do not, which could leave you say with a user that has no home directory or a login shell that does allow logins.  A longer form would look something like sudo useradd -m -k /etc/skel -d /home/<username> -s /bin/bash <username>.  If you need more info about adding a user, check the useradd man page or look for examples online.

With the user created, you can set the password with the command sudo passwd <username>


问:
Getting error when i try to import bluetooth on python2.7
I got python2.7 installed on a raspeberry pi 4 with a script which use the bluethooth library(pybluez) but the script was crashing when importing the library.
Si i simply try to import the bluetooth library on a python2.7 shell and i have the same error "AttributeEror: attribute 'doc' of 'instancemethod' objects is not writable"

I can't switch to python3 and i don't understand why it's not working so if someone got an issue to this i would be grateful :)

code:

```<code>Import bluetooth

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/bluetooth/__init__.py", line 282,
in <module>
"""
AtributeError: attribute '__doc__' of 'instancemethod' objects is not writable
</code>```

Thanks

答:
Another means to fix...
Installed bluez with the following:
sudo apt-get install bluetooth
sudo apt-get install bluez libbluetooth-dev
sudo python -m pip install pybluez

and got this error.
fixed it by using python3 and installing pybluez with
sudo python3 -m pip install pybluez

btw the install is based on:https://blog.adafruit.com/2020/04/17/starting-with-raspberry-pi-bluetooth-python-python-bluetooth-raspberrypi-piday-raspberry_pi/

Body:
I got python2.7 installed on a raspeberry pi 4 with a script which use the bluethooth library(pybluez) but the script was crashing when importing the library.
Si i simply try to import the bluetooth library on a python2.7 shell and i have the same error "AttributeEror: attribute 'doc' of 'instancemethod' objects is not writable"

I can't switch to python3 and i don't understand why it's not working so if someone got an issue to this i would be grateful :)

code:

Import bluetooth

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/bluetooth/__init__.py", line 282,
in <module>
"""
AtributeError: attribute '__doc__' of 'instancemethod' objects is not writable

Thanks


问:
Extending a class that has injected services without duplicating injectors in child class?
Ok, so I'm getting deep into TypeScript inheritance (specifically in Angular 11), and I've set up a BasePageComponent to provide all the necessary functions and services that exist across pages.
The issue I've run into, is that now my base is getting bloated, because there are services that are used only on one or two pages, but in order to extend the base, we have included those in the base.

export class BasePageComponent {

  constructor(
    public uiPopupService: UiPopUpService,
    public loaderService: LoaderService,
    public questionService: QuestionService,
    public aBunchOfOthers: OTHERS,
    public exampleOneOffService: ExampleOneOffService
  ) {}
}
```
<p>I realize that it would be more performant to repeat all the injected services, and then pass them all up to <code>BasePageComponent</code> as so:</p>
<pre class="lang-js prettyprint-override"><code>export class ChildPageComponent extends BasePageComponent {

  constructor(
    public uiPopupService: UiPopUpService,
    public loaderService: LoaderService,
    public questionService: QuestionService,
    public aBunchOfOthers: OTHERS,
    private exampleOneOffService: ExampleOneOffService
  ) {
    super(uiPopupService, loaderService, questionService, aBunchOfOthers);
  }
}
</code>```

I will do the above, if there's no other way, but I have as hinted at in the sample code, I have a bunch of other micro services that are included in the base (like 15-20), so I want to be able to do something like this, where I just declare the one additional service, and still inherit all the others from the parent class, but I am not seeing a way to do this.

export class ChildPageComponent extends BasePageComponent {

  constructor(private otherExampleService: OtherExampleService){
    super()
  };
}
```

Does this pattern exist and I'm just not googling the right keyword?

答:
This is kind of ironic, you're using inheritance to avoid dependency injection, when in reality you should be using dependency injection to avoid inheritance. If components have shared services, all you need to do is put the ones you need in the constructor and you're done.

If they have shared functions, you can put the functions in a service. If they have shared variables, you can use services to pass data around. The point is to have components as their own separate entities, so if you change one, it doesn't affect any others.

Services follow this same philosophy, because you can change the implementation of the service, without having to touch any files that use the service. Think about your design, what happens if you need to remove or add a service to the base component? You now need to go and edit every other component in your entire project. And when you inject a service into a component it creates an instance of that service too. By injecting all of your services into every component, you're creating countless instances of wasted memory and processing power. And do you actually gain anything in return?

What I'm trying to say is you should try to avoid extending components. Angular provides much better design philosophies.

To answer your question, yes, you could create a global service that imports all of your other services, then inject that one massive service. You could then extend that service and import even more. But for the love of all that's holy please don't.

Body:
Ok, so I'm getting deep into TypeScript inheritance (specifically in Angular 11), and I've set up a BasePageComponent to provide all the necessary functions and services that exist across pages.
The issue I've run into, is that now my base is getting bloated, because there are services that are used only on one or two pages, but in order to extend the base, we have included those in the base.

export class BasePageComponent {

  constructor(
    public uiPopupService: UiPopUpService,
    public loaderService: LoaderService,
    public questionService: QuestionService,
    public aBunchOfOthers: OTHERS,
    public exampleOneOffService: ExampleOneOffService
  ) {}
}

I realize that it would be more performant to repeat all the injected services, and then pass them all up to BasePageComponent as so:

export class ChildPageComponent extends BasePageComponent {

  constructor(
    public uiPopupService: UiPopUpService,
    public loaderService: LoaderService,
    public questionService: QuestionService,
    public aBunchOfOthers: OTHERS,
    private exampleOneOffService: ExampleOneOffService
  ) {
    super(uiPopupService, loaderService, questionService, aBunchOfOthers);
  }
}

I will do the above, if there's no other way, but I have as hinted at in the sample code, I have a bunch of other micro services that are included in the base (like 15-20), so I want to be able to do something like this, where I just declare the one additional service, and still inherit all the others from the parent class, but I am not seeing a way to do this.

export class ChildPageComponent extends BasePageComponent {

  constructor(private otherExampleService: OtherExampleService){
    super()
  };
}

Does this pattern exist and I'm just not googling the right keyword?


问:
Bicep: Creating random string
I'm coming from a Terraform background and AWS. Now I'm using Bicep with Azure, so please bear with me :)

In Terraform, we create random passwords with the random_password resource. We then stored this as a value in the AWS Systems Manager Parameter Store. This allowed us to have secure (enough...) passwords, which got created and stored in some secure database without us having to enter or even know the password. If somebody would need to know the password, it would get logged. Lovely ;)

Now...

How do I do something like this with Bicep? I'm only finding the uniqueString() function. But this only creates 13 character long random strings and also doesn't have any "special" characters like !@#$%&*()-_=+[]{}<>:? and such.

For quite obvious reasons, I don't want to have some sort of statement in my code, which sets the secret to some clearly readable value. Which is why we used random_password in Terraform.

What's the right approach to solve this in Bicep?

I found the blog post "Automatically generate a password for an Azure SQL database with ARM template" by Vivien Chevallier, but that isn't good, IMO. To circumvent the short comings of the uniqueString() function and make it comply to the password complexity rules, the person adds a constand prefix of "P" and suffix of "x!". This reduces the quality of the password, as there now 3 known characters. Out of 16.

答:
The intent in Bicep is that one creates fully idempotent templates so that you should receive the same output every time you attempt to deploy anything in Bicep. As such, randomString and newGuid both accept parameters you can use to seed the result, but you'll always get the same result for the new values you put in.

For the reasons above, you're encouraged to provide your own generated password to kick off template deployment externally so there's nothing about the Bicep template that's changing from one deployment to another. On top of that, you're not really encouraged to expose the password in an output value since those are all logged indefinitely, so I highly recommend writing out the value to a Key Vault secret as in the following

```<code>@secure() //Prevents it from being logged, but also removes it from output
param password string = newGuid() //Can only be used as the default value for a param

@description('The name of the Key Vault to save the secret to')
param KeyVaultName string

@description('The name of the secret in Key Vault')
param KeyVaultSecretName string

//Save as Key Vault secret
resource KeyVault 'Microsoft.KeyVault/vaults@2021-06-01-preview' existing = {
  name: KeyVaultName
}

resource KVSecret 'Microsoft.KeyVault/vaults/secrets@2021-06-01-preview' = {
  name: replace(replace(SecretName, '.', '-'), ' ', '-')
  parent: KeyVault
  properties: {
    contentType: 'text/plain'
    attributes: {
      enabled: true
    }
    value: password
  }
}

output PasswordSecretUri string = KVSecret.properties.secretUri
</code>```

And then you can use the GUID output as your password for your use-case knowing that it will be different every time you run the Bicep deployment.

Title: Bicep: Creating random string

Body:
The intent in Bicep is that one creates fully idempotent templates so that you should receive the same output every time you attempt to deploy anything in Bicep. As such, randomString and newGuid both accept parameters you can use to seed the result, but you'll always get the same result for the new values you put in.

For the reasons above, you're encouraged to provide your own generated password to kick off template deployment externally so there's nothing about the Bicep template that's changing from one deployment to another. On top of that, you're not really encouraged to expose the password in an output value since those are all logged indefinitely, so I highly recommend writing out the value to a Key Vault secret as in the following

@secure() //Prevents it from being logged, but also removes it from output
param password string = newGuid() //Can only be used as the default value for a param

@description('The name of the Key Vault to save the secret to')
param KeyVaultName string

@description('The name of the secret in Key Vault')
param KeyVaultSecretName string

//Save as Key Vault secret
resource KeyVault 'Microsoft.KeyVault/vaults@2021-06-01-preview' existing = {
  name: KeyVaultName
}

resource KVSecret 'Microsoft.KeyVault/vaults/secrets@2021-06-01-preview' = {
  name: replace(replace(SecretName, '.', '-'), ' ', '-')
  parent: KeyVault
  properties: {
    contentType: 'text/plain'
    attributes: {
      enabled: true
    }
    value: password
  }
}

output PasswordSecretUri string = KVSecret.properties.secretUri

And then you can use the GUID output as your password for your use-case knowing that it will be different every time you run the Bicep deployment.


答:
Below statement always return true and the loop won't stop. I guess u want to use "and" instead or in below statement.

nombre != "gabriel" or nombre != "tommy"

Title: while loop keeps executing


问:
android facebook: Not showing my Message in dialog
I am working on facebook android application but there is one problem i am facing

i am using the following example

Android/Java -- Post simple text to Facebook wall?

so the problem is that everything works here fine, the dialogs etc etc but When it open the screen to upload Walla Message that i have setted up here

```<code>        try
        {
            System.out.println("*** IN TRY ** ");
            Bundle parameters = new Bundle();
            parameters.putString("message", "this is a test");// the message to post to the wall
            facebookClient.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API call
        }
        catch (Exception e)
        {
            // TODO: handle exception
            System.out.println(e.getMessage());
        }
</code>```

It does not show me my Message written in the dialog. Whats the problem with that

can anybody Guide me please..

Thanks alot.

答:
Use this code , it working for me :

```<code>                    Bundle parameters = new Bundle();
                    parameters.putString("message",sharetext.getText().toString());// the message to post to the wall
                    //facebookClient.dialog(Jams.this, "stream.publish", parameters, this);// "stream.publish" is an API call
                    facebookClient.request("me/feed", parameters, "POST");
</code>```

Hope it helps..

```<code>Edited:

 public class FacebookActivity implements DialogListener
    {

        private Facebook facebookClient;
        private LinearLayout facebookButton;

       public FacebookActivity(Context context) {

           facebookClient = new Facebook();
           // replace APP_API_ID with your own
           facebookClient.authorize(Jams.this, APP_API_ID,
               new String[] {"publish_stream", "read_stream", "offline_access"}, this);

       }

        @Override
        public void onComplete(Bundle values)
        {

            if (values.isEmpty())
            {
                //"skip" clicked ?

            }

            // if facebookClient.authorize(...) was successful, this runs
            // this also runs after successful post
            // after posting, "post_id" is added to the values bundle
            // I use that to differentiate between a call from
            // faceBook.authorize(...) and a call from a successful post
            // is there a better way of doing this?
            if (!values.containsKey("post_id"))
            {
                try
                {
                    Bundle parameters = new Bundle();
                    parameters.putString("message",sharetext.getText().toString());// the

message to post to the wall
                    //facebookClient.dialog(Jams.this, "stream.publish", parameters,

this);// "stream.publish" is an API call
                    facebookClient.request("me/feed", parameters, "POST");
                    sharetext.setText("");
                    Toast.makeText(Jams.this,"Message posted

successfully.",Toast.LENGTH_SHORT).show();

                }
                catch (Exception e)
                {
                    // TODO: handle exception
                   // System.out.println(e.getMessage());
                }

            }

        }

        @Override
        public void onError(DialogError e)
        {
            return;
        }

        @Override
        public void onFacebookError(FacebookError e)
        {
            return;
        }

        @Override
        public void onCancel()
        {
            return;
        }

    }
</code>```

Body:
I am working on facebook android application but there is one problem i am facing

i am using the following example

Android/Java -- Post simple text to Facebook wall?

so the problem is that everything works here fine, the dialogs etc etc but When it open the screen to upload Walla Message that i have setted up here

        try
        {
            System.out.println("*** IN TRY ** ");
            Bundle parameters = new Bundle();
            parameters.putString("message", "this is a test");// the message to post to the wall
            facebookClient.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API call
        }
        catch (Exception e)
        {
            // TODO: handle exception
            System.out.println(e.getMessage());
        }

It does not show me my Message written in the dialog. Whats the problem with that

can anybody Guide me please..

Thanks alot.

Body:
Use this code , it working for me :

                    Bundle parameters = new Bundle();
                    parameters.putString("message",sharetext.getText().toString());// the message to post to the wall
                    //facebookClient.dialog(Jams.this, "stream.publish", parameters, this);// "stream.publish" is an API call
                    facebookClient.request("me/feed", parameters, "POST");

Hope it helps..

Edited:

 public class FacebookActivity implements DialogListener
    {

        private Facebook facebookClient;
        private LinearLayout facebookButton;

       public FacebookActivity(Context context) {

           facebookClient = new Facebook();
           // replace APP_API_ID with your own
           facebookClient.authorize(Jams.this, APP_API_ID,
               new String[] {"publish_stream", "read_stream", "offline_access"}, this);

       }

        @Override
        public void onComplete(Bundle values)
        {

            if (values.isEmpty())
            {
                //"skip" clicked ?

            }

            // if facebookClient.authorize(...) was successful, this runs
            // this also runs after successful post
            // after posting, "post_id" is added to the values bundle
            // I use that to differentiate between a call from
            // faceBook.authorize(...) and a call from a successful post
            // is there a better way of doing this?
            if (!values.containsKey("post_id"))
            {
                try
                {
                    Bundle parameters = new Bundle();
                    parameters.putString("message",sharetext.getText().toString());// the

message to post to the wall
                    //facebookClient.dialog(Jams.this, "stream.publish", parameters,

this);// "stream.publish" is an API call
                    facebookClient.request("me/feed", parameters, "POST");
                    sharetext.setText("");
                    Toast.makeText(Jams.this,"Message posted

successfully.",Toast.LENGTH_SHORT).show();

                }
                catch (Exception e)
                {
                    // TODO: handle exception
                   // System.out.println(e.getMessage());
                }

            }

        }

        @Override
        public void onError(DialogError e)
        {
            return;
        }

        @Override
        public void onFacebookError(FacebookError e)
        {
            return;
        }

        @Override
        public void onCancel()
        {
            return;
        }

    }