问:
Error when utilizing column aliases in where conditions for Sequelize find methods
For brief context: I am trying to migrate our app to utilize Sequelize, and was hoping to rely on the usage of column aliases given the actual column names we are dealing with are rather long and convoluted. Unfortunately I seem to be unable to make use of the aliased attributes when constructing where conditions in Sequelize findAll(), findOne(), etc. methods.
My (simplified) setup is as follows:

```<code>// package.json
{
  ...
  "dependencies": {
    "pg": "^7.18.1",
    "pg-hstore": "^2.3.3",
    "sequelize": "^5.21.4"
  }
}
</code>```

// sequelize.js

const Sequelize = require('sequelize')

const options = {
    ...
    databaseVersion: '8.0.2', // RedShift Postgres version
    dialect: 'postgres',
    dialectOptions: {
        ssl: {
            require: true,
            rejectUnauthorized: true
        }
    }
    define: {
        timestamps: false,
        freezeTableName: true
    }
}

const sequelize = new Sequelize(<database>, <user>, <pass>, options)

module.exports = sequelize

```

<pre class="lang-js prettyprint-override"><code>// MyTable.model.js

const { DataTypes } = require('sequelize')
const sequelize = require('./sequelize')

const schema = 'my_schema'
const tableName = 'my_table'
const modelName = 'MyTable'

const attributes = {
    my_table_key: {
        type: DataTypes.CHAR(32)
    },
    key: {
        field: 'my_table_key',
        type: DataTypes.CHAR(32)
    },
    value: {
        field: 'my_table_value',
        type: DataTypes.STRING
    }
}

const options = {
    schema
    tableName
}

const model = sequelize.define(modelName, attributes, options)

module.exports = model
</code>```

Executing queries such as the following work just fine:

```<code>MyTable.findOne({ attributes: ['key'] })
>> Executing (default): SELECT "my_table_key" AS "key" FROM "my_schema"."my_table" AS "my_table" LIMIT 1;

MyTable.findOne({ attributes: ['key'], where: { key_column: '123' } })
>> Executing (default): SELECT "my_table_key" AS "key" FROM "my_schema"."my_table" AS "my_table" WHERE ("my_table"."my_table_key" = '123') LIMIT 1;
</code>```

However, as soon as I try to make use of the renamed/aliased attributes I encounter an error:

```<code>MyTable.findOne({ attributes: ['key'], where: { key: '123' } })

Unhandled rejection SequelizeDatabaseError: column mytable.key does not exist
at Query.formatError (~/node_modules/sequelize/lib/dialects/postgres/query.js:366:16)
    at query.catch.err (~/node_modules/sequelize/lib/dialects/postgres/query.js:72:18)
    at bound (domain.js:301:14)
    at runBound (domain.js:314:12)
    at tryCatcher (~/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (~/node_modules/bluebird/js/release/promise.js:547:31)
    at Promise._settlePromise (~/node_modules/bluebird/js/release/promise.js:604:18)
    at Promise._settlePromise0 (~/node_modules/bluebird/js/release/promise.js:649:10)
    at Promise._settlePromises (~/node_modules/bluebird/js/release/promise.js:725:18)
    at _drainQueueStep (~/node_modules/bluebird/js/release/async.js:93:12)
    at _drainQueue (~/node_modules/bluebird/js/release/async.js:86:9)
    at Async._drainQueues (~/node_modules/bluebird/js/release/async.js:102:5)
    at Immediate.Async.drainQueues (~/node_modules/bluebird/js/release/async.js:15:14)
    at runCallback (timers.js:810:20)
    at tryOnImmediate (timers.js:768:5)
    at processImmediate [as _immediateCallback] (timers.js:745:5)
</code>```

I've experimented with the modelName and tableName variables (e.g. just keeping the original table name and no custom model name) when defining the model, but encounter the same error. Does anyone know the correct approach (if any) to make use of aliased columns for the where argument?

Thanks!

答:
I've never seen aliases done in this way (during model definition) and I don't recommend you do this.

I recommend you keep the same keys/columns and only when you're fetching, should you use the attributes key to change the column name for usage later:

```<code>MyTable.findOne({ attributes: [['LONG_COLUMN_NAME1', 'key1'], ['LONG_COLUMN_NAME2', 'key2']] }) // This will select LONG_COLUMN_NAME1 as key1 and LONG_COLUMN_NAME2 as key2.
</code>```

Body:
For brief context: I am trying to migrate our app to utilize Sequelize, and was hoping to rely on the usage of column aliases given the actual column names we are dealing with are rather long and convoluted. Unfortunately I seem to be unable to make use of the aliased attributes when constructing where conditions in Sequelize findAll(), findOne(), etc. methods.
My (simplified) setup is as follows:

// package.json
{
  ...
  "dependencies": {
    "pg": "^7.18.1",
    "pg-hstore": "^2.3.3",
    "sequelize": "^5.21.4"
  }
}

// sequelize.js

const Sequelize = require('sequelize')

const options = {
    ...
    databaseVersion: '8.0.2', // RedShift Postgres version
    dialect: 'postgres',
    dialectOptions: {
        ssl: {
            require: true,
            rejectUnauthorized: true
        }
    }
    define: {
        timestamps: false,
        freezeTableName: true
    }
}

const sequelize = new Sequelize(<database>, <user>, <pass>, options)

module.exports = sequelize

// MyTable.model.js

const { DataTypes } = require('sequelize')
const sequelize = require('./sequelize')

const schema = 'my_schema'
const tableName = 'my_table'
const modelName = 'MyTable'

const attributes = {
    my_table_key: {
        type: DataTypes.CHAR(32)
    },
    key: {
        field: 'my_table_key',
        type: DataTypes.CHAR(32)
    },
    value: {
        field: 'my_table_value',
        type: DataTypes.STRING
    }
}

const options = {
    schema
    tableName
}

const model = sequelize.define(modelName, attributes, options)

module.exports = model

Executing queries such as the following work just fine:

MyTable.findOne({ attributes: ['key'] })
>> Executing (default): SELECT "my_table_key" AS "key" FROM "my_schema"."my_table" AS "my_table" LIMIT 1;

MyTable.findOne({ attributes: ['key'], where: { key_column: '123' } })
>> Executing (default): SELECT "my_table_key" AS "key" FROM "my_schema"."my_table" AS "my_table" WHERE ("my_table"."my_table_key" = '123') LIMIT 1;

However, as soon as I try to make use of the renamed/aliased attributes I encounter an error:

MyTable.findOne({ attributes: ['key'], where: { key: '123' } })

Unhandled rejection SequelizeDatabaseError: column mytable.key does not exist
at Query.formatError (~/node_modules/sequelize/lib/dialects/postgres/query.js:366:16)
    at query.catch.err (~/node_modules/sequelize/lib/dialects/postgres/query.js:72:18)
    at bound (domain.js:301:14)
    at runBound (domain.js:314:12)
    at tryCatcher (~/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (~/node_modules/bluebird/js/release/promise.js:547:31)
    at Promise._settlePromise (~/node_modules/bluebird/js/release/promise.js:604:18)
    at Promise._settlePromise0 (~/node_modules/bluebird/js/release/promise.js:649:10)
    at Promise._settlePromises (~/node_modules/bluebird/js/release/promise.js:725:18)
    at _drainQueueStep (~/node_modules/bluebird/js/release/async.js:93:12)
    at _drainQueue (~/node_modules/bluebird/js/release/async.js:86:9)
    at Async._drainQueues (~/node_modules/bluebird/js/release/async.js:102:5)
    at Immediate.Async.drainQueues (~/node_modules/bluebird/js/release/async.js:15:14)
    at runCallback (timers.js:810:20)
    at tryOnImmediate (timers.js:768:5)
    at processImmediate [as _immediateCallback] (timers.js:745:5)

I've experimented with the modelName and tableName variables (e.g. just keeping the original table name and no custom model name) when defining the model, but encounter the same error. Does anyone know the correct approach (if any) to make use of aliased columns for the where argument?

Thanks!

Body:
I've never seen aliases done in this way (during model definition) and I don't recommend you do this.

I recommend you keep the same keys/columns and only when you're fetching, should you use the attributes key to change the column name for usage later:

MyTable.findOne({ attributes: [['LONG_COLUMN_NAME1', 'key1'], ['LONG_COLUMN_NAME2', 'key2']] }) // This will select LONG_COLUMN_NAME1 as key1 and LONG_COLUMN_NAME2 as key2.


来源: stackexchange

问:
Problems while using multiple databases
Background: I am developing a web application with Symfony5 for a customer. The application should be available for several customers. Each customer should get his own file directory (for pdf etc.) and database. The file-directory is not the problem, but I can't get anywhere with the databases.
According to the Symfony docu you can work with different DBs. I configured this in the config/packages/doctrine.yaml.

```<code>doctrine:
dbal:
    connections:
        Client1:
            dbname:     client1
            host:       localhost
            port:       3306
            user:       admin
            password:   secret_pw
            driver:     pdo_mysql
            server-version: 5.7
        Client2:
            dbname:     client2
            host:       localhost
            port:       3306
            user:       admin
            password:   secret_pw
            driver:     pdo_mysql
            server-version: 5.7
orm:
    auto_generate_proxy_classes: true
    entity_managers:
        Client1:
            connection: Client1
            naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
            mappings:
                Client1:
                    is_bundle: false
                    type: annotation
                    dir: '%kernel.project_dir%/src/Entity'
                    prefix: 'App\Entity'
                    alias: Client1
        Client2:
            connection: Client2
            naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
            mappings:
                Client2:
                    is_bundle: false
                    type: annotation
                    dir: '%kernel.project_dir%/src/Entity'
                    prefix: 'App\Entity'
                    alias: Client2
</code>```

So far it also works, if I create the database from the CLI and execute the migrations.

But if I want to read e.g. a user from the DB for Client2 (is set in $dbClient) with

```<code>$userRepo = $this->getDoctrine()
        ->getRepository(User::class, $dbClient);
$user = $userRepo->findOneByeEmail($this->userEmail);
</code>```

the DB for Client1 is ALWAYS set in the repo :((.

Did I do something wrong in the config?
Or is there something else that needs to be configured elsewhere?

Thank you very much for your help

Frank

答:
Both entity managers have the same prefix in your mappings. You should try something like

```<code>prefix: 'App\Entity\Client1'
//...
prefix: 'App\Entity\Client2'
</code>```

That's what they do in the doc.

ContentLicense: CC BY-SA 4.0

Title: Problems while using multiple databases

Body:
Background: I am developing a web application with Symfony5 for a customer. The application should be available for several customers. Each customer should get his own file directory (for pdf etc.) and database. The file-directory is not the problem, but I can't get anywhere with the databases.
According to the Symfony docu you can work with different DBs. I configured this in the config/packages/doctrine.yaml.

doctrine:
dbal:
    connections:
        Client1:
            dbname:     client1
            host:       localhost
            port:       3306
            user:       admin
            password:   secret_pw
            driver:     pdo_mysql
            server-version: 5.7
        Client2:
            dbname:     client2
            host:       localhost
            port:       3306
            user:       admin
            password:   secret_pw
            driver:     pdo_mysql
            server-version: 5.7
orm:
    auto_generate_proxy_classes: true
    entity_managers:
        Client1:
            connection: Client1
            naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
            mappings:
                Client1:
                    is_bundle: false
                    type: annotation
                    dir: '%kernel.project_dir%/src/Entity'
                    prefix: 'App\Entity'
                    alias: Client1
        Client2:
            connection: Client2
            naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
            mappings:
                Client2:
                    is_bundle: false
                    type: annotation
                    dir: '%kernel.project_dir%/src/Entity'
                    prefix: 'App\Entity'
                    alias: Client2

So far it also works, if I create the database from the CLI and execute the migrations.

But if I want to read e.g. a user from the DB for Client2 (is set in $dbClient) with

$userRepo = $this->getDoctrine()
        ->getRepository(User::class, $dbClient);
$user = $userRepo->findOneByeEmail($this->userEmail);

the DB for Client1 is ALWAYS set in the repo :((.

Did I do something wrong in the config?
Or is there something else that needs to be configured elsewhere?

Thank you very much for your help

Frank

Body:
Both entity managers have the same prefix in your mappings. You should try something like

prefix: 'App\Entity\Client1'
//...
prefix: 'App\Entity\Client2'

That's what they do in the doc.


问:
Measure user activity time on webpage
For newrelic custom monitoring, Measuring time(in sec) user spends on a page to record time in and time out. I have the timestamp when user session is created or visits the page, however need to identify time of session end solely using javascript.

Code Tried

```<code>window.onbeforeunload = function(event) {
    doSomething();
    //event.returnValue = "Is this working";
    };

    function doSomething(){
            //const t = new Date();
            //const ctime = t.getTime();
            //Test
            newrelic.setCustomAttribute('ctime', "sal");
            }
</code>```

答:
You can use the "onunload" or "onbeforeunload" event:

```<code><body onbeforeunload="return onBeforeUnload()">
</code>```

where onBeforeUnload() is:

```<code><script>

    function onBeforeUnload() {
      // log the out time
    }

</script>
</code>```

Title: Measure user activity time on webpage

Body:
For newrelic custom monitoring, Measuring time(in sec) user spends on a page to record time in and time out. I have the timestamp when user session is created or visits the page, however need to identify time of session end solely using javascript.

Code Tried

window.onbeforeunload = function(event) {
    doSomething();
    //event.returnValue = "Is this working";
    };

    function doSomething(){
            //const t = new Date();
            //const ctime = t.getTime();
            //Test
            newrelic.setCustomAttribute('ctime', "sal");
            }

Body:
You can use the "onunload" or "onbeforeunload" event:

<body onbeforeunload="return onBeforeUnload()">

where onBeforeUnload() is:

<script>

    function onBeforeUnload() {
      // log the out time
    }

</script>


问:
How to view the full exception/error stack trace in Cloudera
I am trying to run a query from Cloudera Hue editor for Hive. However the query fails with an exception (which I am trying to explore). How do I see the full stack trace?

答: Found the log file location in /var/log/hive.


问:
Does using channel encryption (https) make hashing the secret key redundant?
I'm designing a web service that clients connect to in order to retrieve some private data. Each client has a unique ID and a secret key (generated by the server) that are sent as parameters to the web service in order to authenticate itself. In addition, all communications are done over HTTPS.

I'm also planning to use HMAC-SHA256, in order to avoid sending the secret key over the wire.

However, I'm wondering whether this is strictly necessary. Since HTTPS gives me a secure channel between client and server, why would I really mind sending the secret key over that channel?

The only reason I managed to come up with is that an unknowledgeable developer might add a service in the future and not reject non-HTTPS connections, so hashing the secret key is a sort of insurance against the realities of corporate software development, an extra line of defense if you will.

Am I missing something more significant? Is this a real vulnerability that some attack vector could take advantage of?

答:
The channel may be secure, but that doesn't tell you anything about endpoints: depending on the browser in question (and its plugins/extensions/...), your key could very well end up in a disk-based cache somewhere on the user's computer, and it could sit there until the end of forever.

That is not a very interesting vulnerability ... until you realize that various malware already goes trawling through the disks, looking for anything valuable - and with the current rates, some of your users will be infected (unless your website only has twenty users ;)).

So: don't throw away a pretty powerful crypto mechanism to save a few CPU cycles; that's a potentially dangerous microoptimization IMNSHO.

ContentLicense: CC BY-SA 3.0


问:
Mongo Atlas - Low connection limit?
I am currently testing a free tier of mongo atlas, however I am repeatedly running into issues with the connection limit (100 on the free tier).

I am using the database in an Azure Service Fabric application that has many services and will run on multiple nodes (although currently I am mostly just running locally using a single node local cluster).

To me, 100 connections seems extremely low, I understand it is a free tier, but even the lower tier paid clusters have a low limit (https://docs.atlas.mongodb.com/connection-limits/). My production cluster would likely be M20 to start with which has a limit of 700.

I currently have no confidence at all using Mongo Atlas for my production cluster as I am worried I will run out of connections.

I previously had a cluster with mLab (at a previous job) which had a limit of around 16000 connections on all clusters (and ours was usually sat at around ~800).

I am using the C# driver which I have read I do not need to do anything specific to close the connections. However I have found sometimes that I am not running anything locally (not the service or even a GUI) and yet the connections are sat at almost 100, as if open connections are not being closed.

Am I right in thinking these limits are very restrictive? Am I doing something wrong to keep using up my connections?

Update 16/09/2019:
I have spoken to Mongo about this and got the following reply:
Our connection limits are set conservatively to ensure that memory exhaustion does not lead to stability problems for your MongoDB Atlas cluster. However, we are in fact currently doing some deep testing within our performance team around whether we can safely lift these limits. Please stay tuned for a likely increase of these limits soon.

So it seems this may be changed Soon™

答:
Just to mark this solved: they have twice increased the limits since I posted this.

Now the M20 tier that previously had 700 has 3000 connections, and lower tiers have also been increased. They are now what I would consider "safe" (i.e you would have to be doing something wrong or unusual to hit the limits).

Title: Mongo Atlas - Low connection limit?


问:
Remove comma only from number separators (regular expression grouping)
I have a column of alpha-numeric string in pandas dataframe.
The goal is to only remove comma from number separators. For example:

```<code>Hello, world! -> Hello, world!
</code>```

but

```<code>Warhammer 40,000 -> Warhammer 40000
Codename 1,337 -> Codename 1337
</code>```

I can deduce that only when both sides are numerics '[0-9]+,[0-9]+' do I want to remove the comma. However, I can't seem to figure out a way to keep the same digits. Could someone help? If related, the size of the dataframe is a few hundred thousand rows and an average string is about 100 words.

p.s. this is my first post. I tried searching for related issue but found none. English is not my mother-tougue, chances are, I might have missed the keyword for this issue. Please do link me to the right place should this happens. Many thanks and much appreciated :)

Update: added the keyword 'grouping' as reminder for myself.

Body:
I have a column of alpha-numeric string in pandas dataframe.
The goal is to only remove comma from number separators. For example:

Hello, world! -> Hello, world!

but

Warhammer 40,000 -> Warhammer 40000
Codename 1,337 -> Codename 1337

I can deduce that only when both sides are numerics '[0-9]+,[0-9]+' do I want to remove the comma. However, I can't seem to figure out a way to keep the same digits. Could someone help? If related, the size of the dataframe is a few hundred thousand rows and an average string is about 100 words.

p.s. this is my first post. I tried searching for related issue but found none. English is not my mother-tougue, chances are, I might have missed the keyword for this issue. Please do link me to the right place should this happens. Many thanks and much appreciated :)

Update: added the keyword 'grouping' as reminder for myself.

Body:
import re
str = 'hello, world! 40,000 and 50,000!'
str = re.sub(r'(\d+),(\d+)', r'\1\2', str)


问:
Artifactory cURL download returns 404 File Not Found error when artefact file exists in repository
I'm using Artifactory  for build artifact storage in my CICD pipeline.

I've scripted the artifact push to repository using a cURL API call in PowerSHell script:

```<code>curl.exe -H "X-JFrog-Art-Api: $apiKey" -X PUT $repoUrl -T $artifactFilePath
</code>```

This executed successfully and the artifact file is deposited in the specified Artifactory repository as expected.

Later, I've attempted to download the same artifact file using the following cURL API call:

```<code>curl.exe -H "X-JFrog-Art-Api: $apiKey" -X GET $artifactUrl
</code>```

Even though I can browse the Artifactory GUI and clearly see the artifact file in the subrepository, execution of the GET request returns:

```<code>{
  "errors" : [ {
    "status" : 404,
    "message" : "File not found."
  } ]
}
</code>```

I've checked and double-checked that he repository path is correct (it is consistent with the path in the initial upload request).
I've used the same API key for each request and have confirmed that the associated functional ID has read, write, annotate and delete permissions in the repository.

I've been working with this for some hours now and have so far been unable to identify or solve the problem. Insights or advice on this issue would be most welcome.

UPDATE:

Execution of cURL request with '-v- switch for verbose output returns:

Connected to www.[Artifactory URL].net (169.177.244.86) port 443 (#0)

schannel: SSL/TLS connection with www.[Artifactory URL].net port 443 (step 1/3)

schannel: checking server certificate revocation

schannel: sending initial handshake data: sending 201 bytes...

schannel: sent initial handshake data: sent 201 bytes

schannel: SSL/TLS connection with www.[Artifactory URL].net port 443 (step 2/3)

schannel: failed to receive handshake, need more data

schannel: SSL/TLS connection with www.[Artifactory URL].net port 443 (step 2/3)

schannel: encrypted data got 2415

schannel: encrypted data buffer: offset 2415 length 4096

schannel: sending next handshake data: sending 126 bytes...

schannel: SSL/TLS connection with www.[Artifactory URL].net port 443 (step 2/3)

schannel: encrypted data got 290

schannel: encrypted data buffer: offset 290 length 4096

schannel: SSL/TLS handshake complete

schannel: SSL/TLS connection with www.[Artifactory URL].net port 443 (step 3/3)

schannel: stored credential handle in session cache

GET /[Artifactory repo]/[Artifactory repo path]/[artifact file name].txt HTTP/1.1
    Host: www.[Artifactory URL].net
    User-Agent: curl/7.55.1
    Accept: /
    X-JFrog-Art-Api: [API key]
        0     0    0     0    0     0      0      0 --:--:--  0:00:01 --:--:--     0   0
     0    0     0    0     0      0      0 --:--:--  0:00:02 --:--:--     0   0     0    0
     0    0     0      0      0 --:--:--  0:00:03 --:--:--     0   0      0    0     0    0     0      0      0 --:--:--  0:00:04 --:--:--     0
    0     0    0     0    0     0      0      0 --:--:--  0:00:05 --:--:--
    0   0     0    0     0    0     0      0      0 --:--:--  0:00:06
    --:--:--     0   0     0    0     0    0     0      0      0 --:--:--  0:00:07 --:--:--     0

dud

schannel: client wants to read 102400 bytes

schannel: encdata_buffer resized 103424

schannel: encrypted data buffer: offset 0 length 103424

schannel: encrypted data got 1144

schannel: encrypted data buffer: offset 1144 length 103424

schannel: decrypted data length: 1115

schannel: decrypted data added: 1115

schannel: decrypted data cached: offset 1115 length 102400

schannel: encrypted data buffer: offset 0 length 103424

schannel: decrypted data buffer: offset 1115 length 102400

schannel: schannel_recv cleanup

schannel: decrypted data returned 1115

schannel: decrypted data buffer: offset 0 length 102400 < HTTP/1.1 200 OK < Date: Wed, 19 Feb 2020 17:04:58 GMT < Content-Type:
  text/plain < Content-Length: 3 < Connection: keep-alive < Server:
  Artifactory/6.16.0 < X-Artifactory-Id:
  d9260ad7ca1d26ab34fdd4717e47fdd9abc8e83f < X-Artifactory-Node-Id:
  prodnode3 < Last-Modified: Thu, 23 Jan 2020 15:30:10 GMT < ETag:
  7744ffc8156c74a9ce68f9cc621ac37624549928 < X-Checksum-Sha1:
  7744ffc8156c74a9ce68f9cc621ac37624549928 < X-Checksum-Sha256:
  b4fae8fae2070cbb6c52c22baf32eb1995be678f93e760dfddb60b166bd1a90f <
  X-Checksum-Md5: 807dfcc396f827846e9631b735c7e808 < Accept-Ranges:
  bytes < X-Artifactory-Filename: [artifact file name].txt <
  Content-Disposition: attachment; filename="[artifact file name].txt";
  filename*=UTF-8''[artifact file name].txt < X-Frame-Options: DENY <
  X-Content-Type-Options: nosniff < X-XSS-Protection: 1; mode=block <
  Strict-Transport-Security: max-age=31536000; includeSubdomains;
  preload < Content-Security-Policy: default-src 'self'; script-src
  'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: ; style-src
  'self' 'unsafe-inline'; font-src 'self' data:
  https://themes.googleusercontent.com;  object-src 'none' <  { [3 bytes
  data] 100     3    0     3    0     0      0      0 --:--:--  0:00:08
  --:--:--     0100     3    0     3    0     0      0      0 --:--:--  0:00:08 --:--:--     0

Connection #0 to host www.[Artifactory URL].net left intact
  Blockquote

答:
The original 404 issue was apparently due to an error in my artifact URL in the original cURL API call.

The logs above show the call return after the URL had been rectified. Even with the correct artifact path, the file did not appear to be downloading as expected.
Note, the 'dud' in the above verbose call log is the content of the text file, implying that the file is found and successfully read.

In the end, addition of the '--output' switch, with filename specified, resulted in successful artifact file download.

Body:
I'm using Artifactory  for build artifact storage in my CICD pipeline.

I've scripted the artifact push to repository using a cURL API call in PowerSHell script:

curl.exe -H "X-JFrog-Art-Api: $apiKey" -X PUT $repoUrl -T $artifactFilePath

This executed successfully and the artifact file is deposited in the specified Artifactory repository as expected.

Later, I've attempted to download the same artifact file using the following cURL API call:

curl.exe -H "X-JFrog-Art-Api: $apiKey" -X GET $artifactUrl

Even though I can browse the Artifactory GUI and clearly see the artifact file in the subrepository, execution of the GET request returns:

{
  "errors" : [ {
    "status" : 404,
    "message" : "File not found."
  } ]
}

I've checked and double-checked that he repository path is correct (it is consistent with the path in the initial upload request).
I've used the same API key for each request and have confirmed that the associated functional ID has read, write, annotate and delete permissions in the repository.

I've been working with this for some hours now and have so far been unable to identify or solve the problem. Insights or advice on this issue would be most welcome.

UPDATE:

Execution of cURL request with '-v- switch for verbose output returns:

Connected to www.[Artifactory URL].net (169.177.244.86) port 443 (#0)

schannel: SSL/TLS connection with www.[Artifactory URL].net port 443 (step 1/3)

schannel: checking server certificate revocation

schannel: sending initial handshake data: sending 201 bytes...

schannel: sent initial handshake data: sent 201 bytes

schannel: SSL/TLS connection with www.[Artifactory URL].net port 443 (step 2/3)

schannel: failed to receive handshake, need more data

schannel: SSL/TLS connection with www.[Artifactory URL].net port 443 (step 2/3)

schannel: encrypted data got 2415

schannel: encrypted data buffer: offset 2415 length 4096

schannel: sending next handshake data: sending 126 bytes...

schannel: SSL/TLS connection with www.[Artifactory URL].net port 443 (step 2/3)

schannel: encrypted data got 290

schannel: encrypted data buffer: offset 290 length 4096

schannel: SSL/TLS handshake complete

schannel: SSL/TLS connection with www.[Artifactory URL].net port 443 (step 3/3)

schannel: stored credential handle in session cache

GET /[Artifactory repo]/[Artifactory repo path]/[artifact file name].txt HTTP/1.1
    Host: www.[Artifactory URL].net
    User-Agent: curl/7.55.1
    Accept: /
    X-JFrog-Art-Api: [API key]
        0     0    0     0    0     0      0      0 --:--:--  0:00:01 --:--:--     0   0
     0    0     0    0     0      0      0 --:--:--  0:00:02 --:--:--     0   0     0    0
     0    0     0      0      0 --:--:--  0:00:03 --:--:--     0   0      0    0     0    0     0      0      0 --:--:--  0:00:04 --:--:--     0
    0     0    0     0    0     0      0      0 --:--:--  0:00:05 --:--:--
    0   0     0    0     0    0     0      0      0 --:--:--  0:00:06
    --:--:--     0   0     0    0     0    0     0      0      0 --:--:--  0:00:07 --:--:--     0

dud

schannel: client wants to read 102400 bytes

schannel: encdata_buffer resized 103424

schannel: encrypted data buffer: offset 0 length 103424

schannel: encrypted data got 1144

schannel: encrypted data buffer: offset 1144 length 103424

schannel: decrypted data length: 1115

schannel: decrypted data added: 1115

schannel: decrypted data cached: offset 1115 length 102400

schannel: encrypted data buffer: offset 0 length 103424

schannel: decrypted data buffer: offset 1115 length 102400

schannel: schannel_recv cleanup

schannel: decrypted data returned 1115

schannel: decrypted data buffer: offset 0 length 102400 < HTTP/1.1 200 OK < Date: Wed, 19 Feb 2020 17:04:58 GMT < Content-Type:
  text/plain < Content-Length: 3 < Connection: keep-alive < Server:
  Artifactory/6.16.0 < X-Artifactory-Id:
  d9260ad7ca1d26ab34fdd4717e47fdd9abc8e83f < X-Artifactory-Node-Id:
  prodnode3 < Last-Modified: Thu, 23 Jan 2020 15:30:10 GMT < ETag:
  7744ffc8156c74a9ce68f9cc621ac37624549928 < X-Checksum-Sha1:
  7744ffc8156c74a9ce68f9cc621ac37624549928 < X-Checksum-Sha256:
  b4fae8fae2070cbb6c52c22baf32eb1995be678f93e760dfddb60b166bd1a90f <
  X-Checksum-Md5: 807dfcc396f827846e9631b735c7e808 < Accept-Ranges:
  bytes < X-Artifactory-Filename: [artifact file name].txt <
  Content-Disposition: attachment; filename="[artifact file name].txt";
  filename*=UTF-8''[artifact file name].txt < X-Frame-Options: DENY <
  X-Content-Type-Options: nosniff < X-XSS-Protection: 1; mode=block <
  Strict-Transport-Security: max-age=31536000; includeSubdomains;
  preload < Content-Security-Policy: default-src 'self'; script-src
  'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: ; style-src
  'self' 'unsafe-inline'; font-src 'self' data:
  https://themes.googleusercontent.com;  object-src 'none' <  { [3 bytes
  data] 100     3    0     3    0     0      0      0 --:--:--  0:00:08
  --:--:--     0100     3    0     3    0     0      0      0 --:--:--  0:00:08 --:--:--     0

Connection #0 to host www.[Artifactory URL].net left intact
  Blockquote


Title: Delete list from the list matrix - Python

Body:
I created sorted matrix with ID/ Odometers/ Date. I really need to delete all list where 0 value is on the second position.
I prepared a function and loop but unfortunately I have still below error. I doubt that del [] method is used correctly ?

in zero_clear, if tablica[i][1] == 0: ****

tablica = [
            [
            [21091705,  0,'30.06.2019'],
            [21091705,  0,'29.06.2019'],
            [21091705,  653842,'29.06.2019'],
            [21091705,  641701,'28.06.2019'],
            [21091705,  642000,'27.06.2019'],
            [21091705,  0,'25.06.2019'],
            [21091705,  642030,'25.06.2019'],
            [21091705,  642030,'25.06.2019'],
            [21091705,  637030,'25.06.2019'],
            [21091705,  0,'25.06.2019'],
            [21091705,  0,'17.05.2019'],
            [21091705,  641256,'25.06.2019']
            ],
            [
            [21091703,  487000,'30.06.2019'],
            [21091703,  461524,'29.06.2019'],
            [21091703,  0,'29.06.2019'],
            [21091703,  0,'28.06.2019'],
            [21091703,  427701,'28.06.2019'],
            [21091703,  429000,'27.06.2019']
            ],
            [
            [21091701,  421077,'30.06.2019'],
            [21091701,  453777,'29.06.2019'],
            [21091701,  0,'29.06.2019'],
            [21091701,  427701,'28.06.2019'],
            [21091701,  433123,'27.06.2019']
            ],
            [
            [21091704,  491000,'30.06.2019'],
            [21091704,  0,'29.06.2019'],
            [21091704,  474542,'29.06.2019'],
            [21091704,  427701,'28.06.2019'],
            [21091704,  427701,'28.06.2019'],
            [21091704,  0,'27.06.2019']
            ]
            ]

def zero_clear(tablica):

    for i in range(len(tablica)):

        if tablica[i][1] == 0:
            del tablica[i]

    return tablica

for item in tablica:
    zero_clear(item)

Body:
if you remove elements from your tablica list elements while you are iterating (using for loop) you are ending to jump the next element for every element deleted, to fix the issue you can use a while loop or create a new list:

1) using while loop

def zero_clear(tablica):
    i = 0
    while i < len(tablica):
        if tablica[i][1] == 0:
            del tablica[i]
        else:
            i += 1

for item in tablica:
    zero_clear(item)

2) creating a new list

def zero_clear(tablica):

    new_list = []

    for l in tablica:
        if l[1] != 0:
            new_list.append(l)

    return new_list

for item in tablica:
    item[:] = zero_clear(item)

or  creating a new elemen by using list comprehension:

for item in tablica:
    item[:] = [l for l in item if l[1] != 0]

or creating a completely new list using list comprehension:

tablica = [[l for l in item if l[1] != 0] for item in tablica]

output:

[[[21091705, 653842, '29.06.2019'],
  [21091705, 641701, '28.06.2019'],
  [21091705, 642000, '27.06.2019'],
  [21091705, 642030, '25.06.2019'],
  [21091705, 642030, '25.06.2019'],
  [21091705, 637030, '25.06.2019'],
  [21091705, 641256, '25.06.2019']],
 [[21091703, 487000, '30.06.2019'],
  [21091703, 461524, '29.06.2019'],
  [21091703, 427701, '28.06.2019'],
  [21091703, 429000, '27.06.2019']],
 [[21091701, 421077, '30.06.2019'],
  [21091701, 453777, '29.06.2019'],
  [21091701, 427701, '28.06.2019'],
  [21091701, 433123, '27.06.2019']],
 [[21091704, 491000, '30.06.2019'],
  [21091704, 474542, '29.06.2019'],
  [21091704, 427701, '28.06.2019'],
  [21091704, 427701, '28.06.2019']]]


问:
Change Option val into (SpecialType of val | DefaultType)
I got this bit of code to manage my connection state. I'm trying to learn F#. Now in the connect function I wan't to return my connected state, which needs a TcpClient. The try_connect_tcp function returns an Option TcpClient though. I tried the line try_connect_tcp hostname port |> Option.fold Connected Disconnected to return Disconnected if try_connect_tcp returns None. But it doesn't seem to work. What am I doing wrong?

My code:

type ConnectionState =
    | Disconnected
    | Connected of TcpClient
    | LoggedIn of TcpClient * string

let try_connect_tcp hostname port =
    try
        Some(new TcpClient(hostname, port))
    with
        | :? ArgumentNullException -> printf "Empty Hostname"; None
        | :? ArgumentOutOfRangeException -> printf "Invalid portnumber"; None
        | :? SocketException -> printf "IDK MAN"; None

let connect connectionstate hostname port =
    match connectionstate with
    | Disconnected -> try_connect_tcp hostname port |> Option.fold Connected Disconnected //HERE'S THE PROBLEM
    | _ -> connectionstate
```

答:
Why not change the try_connect_tcp function to work directly with the ConnectionState type?

```<code>let try_connect_tcp hostname port =
    try
        Connected (TcpClient (hostname, port))
    with
        | :? ArgumentNullException -> printf "Empty Hostname"; Disconnected
        | :? ArgumentOutOfRangeException -> printf "Invalid portnumber"; Disconnected
        | :? SocketException -> printf "IDK MAN"; Disconnected
</code>```

Edit: If you really want to use Option.fold, the function passed to it requires two parameters. In your case, using your original try_connect_tcp function, you could write it like this:

```<code>let connect connectionstate hostname port =
    match connectionstate with
    | Disconnected ->
        try_connect_tcp hostname port
        |> Option.fold (fun _ x -> Connected x) Disconnected
    | _ -> connectionstate
</code>```

Body:
Why not change the try_connect_tcp function to work directly with the ConnectionState type?

let try_connect_tcp hostname port =
    try
        Connected (TcpClient (hostname, port))
    with
        | :? ArgumentNullException -> printf "Empty Hostname"; Disconnected
        | :? ArgumentOutOfRangeException -> printf "Invalid portnumber"; Disconnected
        | :? SocketException -> printf "IDK MAN"; Disconnected

Edit: If you really want to use Option.fold, the function passed to it requires two parameters. In your case, using your original try_connect_tcp function, you could write it like this:

let connect connectionstate hostname port =
    match connectionstate with
    | Disconnected ->
        try_connect_tcp hostname port
        |> Option.fold (fun _ x -> Connected x) Disconnected
    | _ -> connectionstate


问:
How to query database column names?
I have a table with multiple columns starting with one keyword link_. I.E. link_0_10, link_10_20, link_20_30 and so on.

I want to select only columns starting with these link_ keywords. How to do that? I can query by RegEx on the value, but on the columns? I have not been able to.

P.S.: I have no prior idea of how many columns may be present.

答:
just change database name and table name with yours and run this query </p>

```<code>SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='database_name'
AND `TABLE_NAME`='table_name' and  COLUMN_NAME like 'link_%'
</code>```

Title: How to query database column names?

Body:
just change database name and table name with yours and run this query

SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='database_name'
AND `TABLE_NAME`='table_name' and  COLUMN_NAME like 'link_%'


问:
C#: Label Designing for Color Printers
I'm developing a Label Printing application for our company that will include support for Black & White and Color Printers.

To simplify development on my part, I'm creating a WinForm with various labels on it that I can position, size, and color as needed. If the End User's printer is Non-Color, all Pens and Brushes will be black. Otherwise, I will be setting my drawing colors based on the Label control's color.

I'd like to develop my labels using basic colors that are found in the standard color printer cartridge, so that I don't wind up causing our company to throw away a cartridge simply because Color Tank #2 has run out (trying to reduce waste and help the environment where I can).

What are the Colors in the tanks? Black, Magenta, Yellow, and Cyan?

If I designed my Labels using these four (4) colors, would I be making good use of the color cartridges or should I stick to combination colors like Red, Blue & Green?

I'd be interested in looking at a simple algorithm that calculates how much color is used, too, if someone knows how to do that.

答:
So...

There is no way to calculate how much of a color is used on a form that I make.

And...

There is no way to balance the amount of colors I select for a printout to load balance the ink in the cartridges.

For now, this is the answer.

If someone can show this to be wrong one day, I'm subscribed for answers, and I'll be happy to mark a solution ...if it works.

Title: C#: Label Designing for Color Printers


问:
django how to dynamically create nested and or queries
I have two types of filter list looking like below

```<code>a_filter = ['a', 'b', 'c']
b_filter = ['x', 'y', 'z']
</code>```

I have to combine the in query for a_filter and boolean field query for b_filter something like below

```<code>Item.objects.filter(a__in=a_filter, x=True, y=True, z=True)
</code>```

How do I dynamically create this query? I got as far as below

```<code>filters = {
  a_filter__in:a_filter,
}

and_condition = Q(**filters)

if len(b_filter) > 0:
  or_cond = Q()
  for filter in b_filter:
    or_cond.add(Q(**{filter:True}), Q.AND)

and_condition.add(or_filter)

Item.objects.filter(and_condition)
</code>```

This create additional (OR: (AND: ) in between the two filter queries like below

```<code>(AND: 'a_filter__in': ['a', 'b', 'c'), (OR: (AND: ), (AND:('x':True, 'y':True, 'z':True))
</code>```

How do I write a correctly working query?

答:
You don't need Q objects to get the specific query you cited.

This would be enough:

```<code>bool_kwargs = {k: True for k in b_filter}
Item.objects.filter(a__in=a_filter, **bool_kwargs)
</code>```

Also, the example you gave would not work. Assuming you had in mind something like:

```<code>filters = {
    "a__in": a_filter,
}

and_condition = Q(**filters)

if len(b_filter) > 0:
    or_cond = Q()
    for filter in b_filter:
        or_cond.add(Q(**{filter: True}), Q.AND)

    and_condition.add(or_cond)

Item.objects.filter(and_condition)
</code>```

If you want to use Q objects anyway or that Q.AND is supposed to be Q.OR (as hinted by the or_cond variable name), you can do:

```<code>from functools import reduce
from operator import or_ # replace or_ with and_ for Q.AND

bool_q_list = [Q(k=True) for k in b_filter]
bool_q = reduce(or_, bool_q_list) # replace or_ with and_ for Q.AND
Item.objects.filter(bool_q, a__in=a_filter)
</code>```

Body:
I have two types of filter list looking like below

a_filter = ['a', 'b', 'c']
b_filter = ['x', 'y', 'z']

I have to combine the in query for a_filter and boolean field query for b_filter something like below

Item.objects.filter(a__in=a_filter, x=True, y=True, z=True)

How do I dynamically create this query? I got as far as below

filters = {
  a_filter__in:a_filter,
}

and_condition = Q(**filters)

if len(b_filter) > 0:
  or_cond = Q()
  for filter in b_filter:
    or_cond.add(Q(**{filter:True}), Q.AND)

and_condition.add(or_filter)

Item.objects.filter(and_condition)

This create additional (OR: (AND: ) in between the two filter queries like below

(AND: 'a_filter__in': ['a', 'b', 'c'), (OR: (AND: ), (AND:('x':True, 'y':True, 'z':True))

How do I write a correctly working query?

Body:
You don't need Q objects to get the specific query you cited.

This would be enough:

bool_kwargs = {k: True for k in b_filter}
Item.objects.filter(a__in=a_filter, **bool_kwargs)

Also, the example you gave would not work. Assuming you had in mind something like:

filters = {
    "a__in": a_filter,
}

and_condition = Q(**filters)

if len(b_filter) > 0:
    or_cond = Q()
    for filter in b_filter:
        or_cond.add(Q(**{filter: True}), Q.AND)

    and_condition.add(or_cond)

Item.objects.filter(and_condition)

If you want to use Q objects anyway or that Q.AND is supposed to be Q.OR (as hinted by the or_cond variable name), you can do:

from functools import reduce
from operator import or_ # replace or_ with and_ for Q.AND

bool_q_list = [Q(k=True) for k in b_filter]
bool_q = reduce(or_, bool_q_list) # replace or_ with and_ for Q.AND
Item.objects.filter(bool_q, a__in=a_filter)


问:
Unable to open site url in browser
I have created simple basic automation script in Python using Selenium..
Getting unwanted exception.

File:-

```<code>import pandas as pd
from pandas import ExcelWriter
from selenium import webdriver

import selenium as sel

# Data = pd.read_excel(r"C:\Users\Admin\PycharmProjects\Web_Automation_Form_Filling\challenge.xlsx",sheet_name="Sheet1")

# browser = webdriver.Chrome(executable_path=r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe");
browser.sleep(1000);
browser.get("http://www.python.org")
</code>```

Error log:-

```<code>C:\Users\Admin\PycharmProjects\Web_Automation_Form_Filling\venv\Scripts\python.exe C:/Users/Admin/PycharmProjects/Web_Automation_Form_Filling/venv/Web_Auto_Filling.py
Traceback (most recent call last):
  File "C:/Users/Admin/PycharmProjects/Web_Automation_Form_Filling/venv/Web_Auto_Filling.py", line 10, in <module>
    browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe");
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\common\service.py", line 98, in start
    self.assert_process_still_running()
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\common\service.py", line 109, in assert_process_still_running
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: Service C:\Program Files (x86)\Google\Chrome\Application\chrome.exe unexpectedly exited. Status code was: 0

Process finished with exit code 1
</code>```

Any suggestion will be appreciated..
Thanks...

答:
This code should work (better to use firefox for selenium):</p>

```<code>from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup

# noinspection PyUnresolvedReferences
import wget

DesiredCapabilities.PHANTOMJS[
    "phantomjs.page.settings.userAgent"
] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:16.0) Gecko/20121026 Firefox/16.0"

if browser == "firefox":
    driver = webdriver.Firefox()
else:
    driver = webdriver.PhantomJS(
        CFG_phantomjs
    )  # r"D:/_devs/webserver/phantomjs-1.9.8/phantomjs.exe"

driver.get("https://tourwebsite")
username = driver.find_element_by_id("login_field")
password = driver.find_element_by_id("password")
username.clear()
</code>```

Title: Unable to open site url in browser

Body:
I have created simple basic automation script in Python using Selenium..
Getting unwanted exception.

File:-

import pandas as pd
from pandas import ExcelWriter
from selenium import webdriver

import selenium as sel

# Data = pd.read_excel(r"C:\Users\Admin\PycharmProjects\Web_Automation_Form_Filling\challenge.xlsx",sheet_name="Sheet1")

# browser = webdriver.Chrome(executable_path=r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe");
browser.sleep(1000);
browser.get("http://www.python.org")

Error log:-

C:\Users\Admin\PycharmProjects\Web_Automation_Form_Filling\venv\Scripts\python.exe C:/Users/Admin/PycharmProjects/Web_Automation_Form_Filling/venv/Web_Auto_Filling.py
Traceback (most recent call last):
  File "C:/Users/Admin/PycharmProjects/Web_Automation_Form_Filling/venv/Web_Auto_Filling.py", line 10, in <module>
    browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe");
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\common\service.py", line 98, in start
    self.assert_process_still_running()
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\common\service.py", line 109, in assert_process_still_running
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: Service C:\Program Files (x86)\Google\Chrome\Application\chrome.exe unexpectedly exited. Status code was: 0

Process finished with exit code 1

Any suggestion will be appreciated..
Thanks...

Body:
This code should work (better to use firefox for selenium):

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup

# noinspection PyUnresolvedReferences
import wget

DesiredCapabilities.PHANTOMJS[
    "phantomjs.page.settings.userAgent"
] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:16.0) Gecko/20121026 Firefox/16.0"

if browser == "firefox":
    driver = webdriver.Firefox()
else:
    driver = webdriver.PhantomJS(
        CFG_phantomjs
    )  # r"D:/_devs/webserver/phantomjs-1.9.8/phantomjs.exe"

driver.get("https://tourwebsite")
username = driver.find_element_by_id("login_field")
password = driver.find_element_by_id("password")
username.clear()


问:
Response is not showing while fetching data from an api
I am trying to fetch data from an api but I am getting an following error I am unable to find out where the problem is I am using separate UI thread to fetech data then too app crashes.

```<code>2020-02-20 17:20:01.088 22802-22802/com.example.flypped E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.flypped, PID: 22802
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:560)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.request(RealBufferedSource.kt:62)
    at okio.RealBufferedSource.require(RealBufferedSource.kt:55)
    at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:299)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:450)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:429)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.read(Exchange.kt:279)
    at okio.RealBufferedSource.select(RealBufferedSource.kt:93)
    at okhttp3.internal.Util.readBomAsCharset(Util.kt:256)
    at okhttp3.ResponseBody.string(ResponseBody.kt:187)
    at com.example.flypped.MainActivity$2$1.run(MainActivity.java:110)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7156)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
    Suppressed: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:560)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.request(RealBufferedSource.kt:62)
    at okio.RealBufferedSource.require(RealBufferedSource.kt:55)
    at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:299)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:450)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:429)
    at okhttp3.internal.Util.skipAll(Util.kt:337)
    at okhttp3.internal.Util.discard(Util.kt:358)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.close(Http1ExchangeCodec.kt:471)
    at okio.ForwardingSource.close(ForwardingSource.kt:34)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.close(Exchange.kt:306)
    at okio.RealBufferedSource.close(RealBufferedSource.kt:461)
    at kotlin.io.CloseableKt.closeFinally(Closeable.kt:56)
    at okhttp3.ResponseBody.string(ResponseBody.kt:186)
</code>```

Below is my code:

XML code:

```<code> <?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">

<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</com.google.android.material.appbar.AppBarLayout>

<include layout="@layout/content_main" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/bottomBar"
    android:layout_gravity="bottom"
    app:menu="@menu/bottom_menu"
    android:background="#fff"
    app:itemIconTint="@drawable/nav_check"
    app:itemTextColor="@drawable/nav_check"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

<com.google.android.material.navigation.NavigationView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:id="@+id/nav_view">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include
            layout="@layout/nav_header"
            android:id="@+id/header"/>

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/header"
            android:id="@+id/menuRecycler"
            android:layout_marginTop="20dp"/>

    </RelativeLayout>

</com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>
</code>```

Java code:

```<code> private void getMenuData(){

    OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();

    Request request = new Request.Builder().url(URL).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    try {

                        JSONArray jsonArray = new JSONArray(response.body().string());

                      //  Log.d("array", String.valueOf(jsonArray));

                       if(jsonArray.length() > 0){

                            for(int i=0;i<jsonArray.length();i++){

                                JSONObject jsonObject = jsonArray.getJSONObject(i);

                                String str1 = jsonObject.getString("name");
                                String str2 = jsonObject.getString("term_id");

                                MenuModel model = new MenuModel(str1,str2);
                                list.add(model);
                            }

                            adapter = new MenuAdapter(list,getApplicationContext());
                            menuRecycler.setAdapter(adapter);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }

    });

}
</code>```

Log cat showing error in below line

```<code>JSONArray jsonArray = new JSONArray(response.body().string());
</code>```

Someone please let me know what I am doing wrong.Any help would be appreciated.

THANKS

答:
Put your api call inside run block.</p>

```<code>Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {

       //Your code goes here

    }
});
thread.start();
</code>```

Body:
I am trying to fetch data from an api but I am getting an following error I am unable to find out where the problem is I am using separate UI thread to fetech data then too app crashes.

2020-02-20 17:20:01.088 22802-22802/com.example.flypped E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.flypped, PID: 22802
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:560)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.request(RealBufferedSource.kt:62)
    at okio.RealBufferedSource.require(RealBufferedSource.kt:55)
    at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:299)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:450)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:429)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.read(Exchange.kt:279)
    at okio.RealBufferedSource.select(RealBufferedSource.kt:93)
    at okhttp3.internal.Util.readBomAsCharset(Util.kt:256)
    at okhttp3.ResponseBody.string(ResponseBody.kt:187)
    at com.example.flypped.MainActivity$2$1.run(MainActivity.java:110)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7156)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
    Suppressed: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:560)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.request(RealBufferedSource.kt:62)
    at okio.RealBufferedSource.require(RealBufferedSource.kt:55)
    at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:299)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:450)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:429)
    at okhttp3.internal.Util.skipAll(Util.kt:337)
    at okhttp3.internal.Util.discard(Util.kt:358)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.close(Http1ExchangeCodec.kt:471)
    at okio.ForwardingSource.close(ForwardingSource.kt:34)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.close(Exchange.kt:306)
    at okio.RealBufferedSource.close(RealBufferedSource.kt:461)
    at kotlin.io.CloseableKt.closeFinally(Closeable.kt:56)
    at okhttp3.ResponseBody.string(ResponseBody.kt:186)

Below is my code:

XML code:

 <?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">

<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</com.google.android.material.appbar.AppBarLayout>

<include layout="@layout/content_main" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/bottomBar"
    android:layout_gravity="bottom"
    app:menu="@menu/bottom_menu"
    android:background="#fff"
    app:itemIconTint="@drawable/nav_check"
    app:itemTextColor="@drawable/nav_check"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

<com.google.android.material.navigation.NavigationView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:id="@+id/nav_view">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include
            layout="@layout/nav_header"
            android:id="@+id/header"/>

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/header"
            android:id="@+id/menuRecycler"
            android:layout_marginTop="20dp"/>

    </RelativeLayout>

</com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

Java code:

 private void getMenuData(){

    OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();

    Request request = new Request.Builder().url(URL).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    try {

                        JSONArray jsonArray = new JSONArray(response.body().string());

                      //  Log.d("array", String.valueOf(jsonArray));

                       if(jsonArray.length() > 0){

                            for(int i=0;i<jsonArray.length();i++){

                                JSONObject jsonObject = jsonArray.getJSONObject(i);

                                String str1 = jsonObject.getString("name");
                                String str2 = jsonObject.getString("term_id");

                                MenuModel model = new MenuModel(str1,str2);
                                list.add(model);
                            }

                            adapter = new MenuAdapter(list,getApplicationContext());
                            menuRecycler.setAdapter(adapter);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }

    });

}

Log cat showing error in below line

JSONArray jsonArray = new JSONArray(response.body().string());

Someone please let me know what I am doing wrong.Any help would be appreciated.

THANKS

Body:
Put your api call inside run block.

Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {

       //Your code goes here

    }
});
thread.start();


问:
Conditional row subtraction in table
I have an m x 4 table consisting of the YTD sales per product per month across divisions A to D. I would like to add a column, which calculates the monthly sales per product per month across the divisions.

There cannot be two rows where month, division and product is the same, hence each row is unique.

I have tried to use SUMIFS to index the value, but the part that causes me trouble is that a product can appear mid-year, and a product can also have sales for 3 months and then no sales for 2 months before reappearing again.

Adding multiple “assisting” columns is okay. I cannot use VBA for this particular task.

Thank you in advance!

答:
You can use following array formula:

```<code>{=D2-SUMPRODUCT(IFERROR((B2=$B$1:B1)*(C2=$C$1:C1)*($E$1:E1);0))}
</code>```

Array formula after editing is confirmed by pressing ctrl + shift + enter

Replace semicolon with comma in formula if needed.

Title: Conditional row subtraction in table

Body:
You can use following array formula:

{=D2-SUMPRODUCT(IFERROR((B2=$B$1:B1)*(C2=$C$1:C1)*($E$1:E1);0))}

Array formula after editing is confirmed by pressing ctrl + shift + enter

Replace semicolon with comma in formula if needed.


问:
How to get component instance in data section in vuejs template?
I have a component that has complex rendering logic.
I try to carry out this logic to helper classes, for simplifying.
To do this, in the data section (for reactivity), I create class references as follows:

```<code>export default {
  data: () => ({
    state: new InitialState(this),
    query: new QueryController(this)
  })
}
</code>```

As I understand it, at this point the context of this is not yet defined.
So, I have two questions.

1) Is there a way to pass the this component context in the data section (without lifecycle hooks)?

2) Is the approach with references to external classes of vuejs philosophy contrary?

答:
As I understand it, at this point the context of this is not yet defined.

Only because of the way you've written the code. The component instance does exist and is available. It is sometimes used to access the values of props for determining the initial values of data properties.

For example, here is an example from the documentation:

https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow

export default {
  props: ['initialCounter'],
  data: function () {
    return {
      counter: this.initialCounter
    }
  }
}
```
<p>The reason why your code doesn't work is because you are using an arrow function. If you change it to the following then <code>this</code> will be available:</p>
<pre class="lang-js prettyprint-override"><code>export default {
  data () {
    return {
      state: new InitialState(this),
      query: new QueryController(this)
    }
  }
}
</code>```

See also the note here:

https://v2.vuejs.org/v2/api/#data

Note that if you use an arrow function with the data property, this won’t be the component’s instance, but you can still access the instance as the function’s first argument

As to your other question about whether using classes like this is contrary to Vue...

I don't think the use of classes like this is encouraged but they can be made to work so long as you understand the limitations. If you have a clear understanding of how Vue reactivity works, especially the rewriting of properties, then it is possible to write classes like this and for them to work fine. The key is to ensure that any properties you want to be reactive are exposed as properties of the object so Vue can rewrite them.

If you don't need reactivity on these objects then don't put them in data. You'd be better off just creating properties within the created hook instead so the reactivity system doesn't waste time trying to add reactivity to them. So long as they are properties of the instance they will still be accessible in your templates, there's nothing special about using data from that perspective.

Body:
I have a component that has complex rendering logic.
I try to carry out this logic to helper classes, for simplifying.
To do this, in the data section (for reactivity), I create class references as follows:

export default {
  data: () => ({
    state: new InitialState(this),
    query: new QueryController(this)
  })
}

As I understand it, at this point the context of this is not yet defined.
So, I have two questions.

1) Is there a way to pass the this component context in the data section (without lifecycle hooks)?

2) Is the approach with references to external classes of vuejs philosophy contrary?

Body:
As I understand it, at this point the context of this is not yet defined.

Only because of the way you've written the code. The component instance does exist and is available. It is sometimes used to access the values of props for determining the initial values of data properties.

For example, here is an example from the documentation:

https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow

export default {
  props: ['initialCounter'],
  data: function () {
    return {
      counter: this.initialCounter
    }
  }
}

The reason why your code doesn't work is because you are using an arrow function. If you change it to the following then this will be available:

export default {
  data () {
    return {
      state: new InitialState(this),
      query: new QueryController(this)
    }
  }
}

See also the note here:

https://v2.vuejs.org/v2/api/#data

Note that if you use an arrow function with the data property, this won’t be the component’s instance, but you can still access the instance as the function’s first argument

As to your other question about whether using classes like this is contrary to Vue...

I don't think the use of classes like this is encouraged but they can be made to work so long as you understand the limitations. If you have a clear understanding of how Vue reactivity works, especially the rewriting of properties, then it is possible to write classes like this and for them to work fine. The key is to ensure that any properties you want to be reactive are exposed as properties of the object so Vue can rewrite them.

If you don't need reactivity on these objects then don't put them in data. You'd be better off just creating properties within the created hook instead so the reactivity system doesn't waste time trying to add reactivity to them. So long as they are properties of the instance they will still be accessible in your templates, there's nothing special about using data from that perspective.


问:
Angular 8: unable to set headers
I want to call a service from my component:

```<code>getToken() {
  const httpOptions = {headers: new HttpHeaders({ 'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' })};
  return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password", httpOptions);
}
</code>```

The call not showing the Authorization, check the image below:

答:
You're sending the header as the request body.

You need to pass it as a third param to the call:

```<code>this.http.post(url, null, httpOptions)
</code>```

Title: Angular 8: unable to set headers

Body:
I want to call a service from my component:

getToken() {
  const httpOptions = {headers: new HttpHeaders({ 'Authorization': 'Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' })};
  return this.http.post(this.rootUrl + "oauth/token?client_id=spring-security-oauth2-read-write-client&password=root1234&username=tarak@bambootv.com&grant_type=password", httpOptions);
}

The call not showing the Authorization, check the image below:

Body:
You're sending the header as the request body.

You need to pass it as a third param to the call:

this.http.post(url, null, httpOptions)


问:
How to fetch hierarchy data with dynamic changes
I have emp table like as follows:

```<code>Empname              Mgr_hierarchy
-------    ---------------------------------
arjun      Giri    | Raj    | Suresh
arun       arjun   | Giri   | Raj    | Suresh
alex       Pandey  | Ravi   | Suresh
adam       alex    | Pandey | Ravi   | Suresh
bux        alex    | Pandey | Ravi   | Suresh
bony       Agarwal | Ram    | Nitesh | Suresh
</code>```

A manager table as like follows:

```<code>Mgr_names
----------
Raj
Ram
Ravi
</code>```

I want to fetch the all the employee details who are have the listed managers in their hierarchy,

I have use the following code for that

```<code>    select empname from `project.dataset.emp`
 where
(mgr_hierarchy like '%Raj%' or mgr_hierarchy like '%Ravi%' or mgr_hierarchy like '%Ram%')
</code>```

But the problem is the manager table is dynamically changing; as of now it contains 3 values after one month these managers are replaced with another 3 or 4 values. So every time I am changing the condition. Are there any solutions for this?

答:
Like Nikesh answered, using the IN clause with a subquery would do the work:

```<code>SELECT empname FROM `project.dataset.emp`
WHERE (mgr_hierarchy IN
  (SELECT names FROM Mgr_names))
</code>```

I made a new answer, since the LIKE clause was not needed.

Body:
I have emp table like as follows:

Empname              Mgr_hierarchy
-------    ---------------------------------
arjun      Giri    | Raj    | Suresh
arun       arjun   | Giri   | Raj    | Suresh
alex       Pandey  | Ravi   | Suresh
adam       alex    | Pandey | Ravi   | Suresh
bux        alex    | Pandey | Ravi   | Suresh
bony       Agarwal | Ram    | Nitesh | Suresh

A manager table as like follows:

Mgr_names
----------
Raj
Ram
Ravi

I want to fetch the all the employee details who are have the listed managers in their hierarchy,

I have use the following code for that

    select empname from `project.dataset.emp`
 where
(mgr_hierarchy like '%Raj%' or mgr_hierarchy like '%Ravi%' or mgr_hierarchy like '%Ram%')

But the problem is the manager table is dynamically changing; as of now it contains 3 values after one month these managers are replaced with another 3 or 4 values. So every time I am changing the condition. Are there any solutions for this?

Body:
Like Nikesh answered, using the IN clause with a subquery would do the work:

SELECT empname FROM `project.dataset.emp`
WHERE (mgr_hierarchy IN
  (SELECT names FROM Mgr_names))

I made a new answer, since the LIKE clause was not needed.


问:
auto select radio button not triggering routes
I am writing code in angular. I tried auto select in radio button but it is not triggering click event. Need to click radio button again to generate event.
Here is what i did

```<code>     <mat-radio-group aria-label="Select an option">

                    <mat-radio-button value="2" routerLink='/products/tshirt/shirt' [checked]='true'><span>Shirt</span></mat-radio-button><br>
                    <mat-radio-button value="3"><span>Cap</span></mat-radio-button>
                  </mat-radio-group>
</code>```

i am getting checked radio button but routes doesnot works.

答:
You can not set the routerLink attribute for the mat-radio-button. But you could navigate on the change event of the radio button:

```<code><mat-radio-group aria-label="Select an option">
   <mat-radio-button value="2" (change)="changeRoute($event)"><span>Shirt</span></mat-radio-button>
   <mat-radio-button value="3" (change)="changeRoute($event)"><span>Cap</span></mat-radio-button>
</mat-radio-group>
</code>```

And in ts file you can change the route according to the selected value:

```<code> private changeRoute(event:MatRadioChange){
    if(event.value === "2"){
      this.router.navigate(['/products/tshirts/shirt']);
    }
  }

</code>```

And in your ts file don't forget to inject the router:

```<code>constructor(private router: Router){}
</code>```

Body:
I am writing code in angular. I tried auto select in radio button but it is not triggering click event. Need to click radio button again to generate event.
Here is what i did

     <mat-radio-group aria-label="Select an option">

                    <mat-radio-button value="2" routerLink='/products/tshirt/shirt' [checked]='true'>Shirt</mat-radio-button>

                    <mat-radio-button value="3">Cap</mat-radio-button>
                  </mat-radio-group>

i am getting checked radio button but routes doesnot works.

Body:
You can not set the routerLink attribute for the mat-radio-button. But you could navigate on the change event of the radio button:

<mat-radio-group aria-label="Select an option">
   <mat-radio-button value="2" (change)="changeRoute($event)"><span>Shirt</span></mat-radio-button>
   <mat-radio-button value="3" (change)="changeRoute($event)"><span>Cap</span></mat-radio-button>
</mat-radio-group>

And in ts file you can change the route according to the selected value:

 private changeRoute(event:MatRadioChange){
    if(event.value === "2"){
      this.router.navigate(['/products/tshirts/shirt']);
    }
  }

And in your ts file don't forget to inject the router:

constructor(private router: Router){}


问:
Remove all HTML tags except
 from a text?
hi all
I have a java string which I want to
1- remove all html tags except the new line tags
 and
 from it and keep the text inside the tags if there's a text.
2- after parsing the text result is concatenated to each other like: text1andtext2 , there's no space separation between the texts, I want to do that too.

here's what I am doing:

```<code>String html = "<div dir=\"ltr\">hello my friend<span>ECHO</span><br>how are you ?<br><br><div class=\"gmail_quote\">On Mon, Feb 14, 2011 at 10:45 AM, My Friend <span dir=\"ltr\"><<a href=\"mailto:notifications@mydomain.com\">notifications@mydomain.com</a>></span> wrote:<br> "
            + "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;\"> ";
    String parsedText = html.replaceAll("\\<.*?\\>", "");
    System.out.println(parsedText);
</code>```

current output:

```<code>hello my friendECHOhow are you ?On Mon, Feb 14, 2011 at 10:45 AM, My Friend <notifications@mydomain.com> wrote:
</code>```

desired output:

```<code>hello my friend ECHO <br> how are you ? <br> <br> On Mon, Feb 14, 2011 at 10:45 AM, My Friend &`lt;notifications@mydomain.com> wrote:`
</code>```

答:
Look at this Question

How do I preserve line breaks when using jsoup to convert html to plain text?

ContentLicense: CC BY-SA 2.5

Title: Remove all HTML tags except <br> from a text?

Body:
hi all
I have a java string which I want to
1- remove all html tags except the new line tags
 and
 from it and keep the text inside the tags if there's a text.
2- after parsing the text result is concatenated to each other like: text1andtext2 , there's no space separation between the texts, I want to do that too.

here's what I am doing:

String html = "
hello my friendECHO
how are you ?

On Mon, Feb 14, 2011 at 10:45 AM, My Friend <notifications@mydomain.com> wrote:
 "
            + "
 ";
    String parsedText = html.replaceAll("\\<.*?\\>", "");
    System.out.println(parsedText);

current output:

hello my friendECHOhow are you ?On Mon, Feb 14, 2011 at 10:45 AM, My Friend <notifications@mydomain.com> wrote:

desired output:

hello my friend ECHO
 how are you ?

 On Mon, Feb 14, 2011 at 10:45 AM, My Friend &`lt;notifications@mydomain.com> wrote:`


问:
@Recover (fallback method) is not getting invoked when used with @CircuitBreaker, once all the retry gets exhaused
Though with other return type Spring retry fallback mechanism seems to be working fine, but when it comes to calling an API with return type void. Recover method is not getting called at all, I have tried with all possible type of method parameters and changing the return type of the fallback method.... Is thr any way to do it? I don't understand why the @CircuitBReaker annotation doesn't have a parameter to take the fallback method name passed as a value to it?</p>

```<code>    @CircuitBreaker(maxAttempts = 3, openTimeout = 8000, resetTimeout = 15000)
    public Void callingXYZ(final Abc abc, final Cdf cdf) {
        return retryTemplate.execute(context -> {
            log.info("Retry count={} when calling ******", context.getRetryCount());
            AbcServiceImpl.this.update*****Settings(OrgId.fromString(abc.getUUID(), cdf.getData());
            return null;
        });
    }

   //Recover method that should get invoked
    @Recover
    public Void fallbackUpdate*****(Throwable e, Abc abc) throws Throwable{
        log.info("Inside fallback");
        if (e instanceof ClientException) {
            log.warn("Fallback method is called when trying to call ******** from ****** because of {}", e.getCause());

   //Rollback in the db based on the method attributes
            throw SpecificException.forTask(HttpStatus.SERVICE_UNAVAILABLE.value(),
                    Enum.NAME.getErrorCode(),
                    Enum.NAME.getMEssage(), true);
        }
        throw e;
    }

</code>```

答: I resolved the issue in my code, it had nothing to do with spring-retry project. I was unable to find the solution of my issue because of my lack of understanding in Spring implementation of AOP. As Spring's aspect is applied to a proxy surrounding the bean not the actual class, calling a method with @circuitbreaker won't work if it is called from a same class/Service.</p>

Body:
Though with other return type Spring retry fallback mechanism seems to be working fine, but when it comes to calling an API with return type void. Recover method is not getting called at all, I have tried with all possible type of method parameters and changing the return type of the fallback method.... Is thr any way to do it? I don't understand why the @CircuitBReaker annotation doesn't have a parameter to take the fallback method name passed as a value to it?

    @CircuitBreaker(maxAttempts = 3, openTimeout = 8000, resetTimeout = 15000)
    public Void callingXYZ(final Abc abc, final Cdf cdf) {
        return retryTemplate.execute(context -> {
            log.info("Retry count={} when calling ******", context.getRetryCount());
            AbcServiceImpl.this.update*****Settings(OrgId.fromString(abc.getUUID(), cdf.getData());
            return null;
        });
    }

   //Recover method that should get invoked
    @Recover
    public Void fallbackUpdate*****(Throwable e, Abc abc) throws Throwable{
        log.info("Inside fallback");
        if (e instanceof ClientException) {
            log.warn("Fallback method is called when trying to call ******** from ****** because of {}", e.getCause());

   //Rollback in the db based on the method attributes
            throw SpecificException.forTask(HttpStatus.SERVICE_UNAVAILABLE.value(),
                    Enum.NAME.getErrorCode(),
                    Enum.NAME.getMEssage(), true);
        }
        throw e;
    }


问:
Cross origin error between angular cli and flask
first i post the user id and password from the UI(angular) to flask

```<code>  public send_login(user){
           console.log(user)
           return
     this.http.post(this.apiURL+'/login',JSON.stringify(user),this.httpOptions)
    .pipe(retry(1),catchError(this.
     handleError))
     }
</code>```

next i received it from backend

backend error

all the operations are working properly but at console the cross origin error is raising

Error at UI console

the http option in Ui side is mentioned below

```<code>constructor(private http: HttpClient) { }
  // Http Options
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': 'http://localhost:9000',
      'Access-Control-Allow-Methods': "GET,POST,OPTIONS,DELETE,PUT",
      'X-Requested-With': 'XMLHttpRequest',
      'MyClientCert': '',        // This is empty
      'MyToken': ''
    })
  }
</code>```

the cors declared at backend is metioned below

```<code>cors = CORS(app, resources={r"/login": {"origins": "*"}})
 @app.route('/login', methods=['GET','POST'])
 def loginForm():
 json_data = ast.literal_eval(request.data.decode('utf-8'))
  print('\n\n\n',json_data,'\n\n\n')
</code>```

im not able to find were is the problem is raising

Note: cross origin arising in the time of login process other wise in the consecutive steps

答:
add below code in your app.py

```<code>CORS(app, supports_credentials=True)
</code>```

and from frontend use

```<code>{with-credentials :true}
</code>```

it will enable the communication between the frontend and backend

Body:
first i post the user id and password from the UI(angular) to flask

  public send_login(user){
           console.log(user)
           return
     this.http.post(this.apiURL+'/login',JSON.stringify(user),this.httpOptions)
    .pipe(retry(1),catchError(this.
     handleError))
     }

next i received it from backend

backend error

all the operations are working properly but at console the cross origin error is raising

Error at UI console

the http option in Ui side is mentioned below

constructor(private http: HttpClient) { }
  // Http Options
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': 'http://localhost:9000',
      'Access-Control-Allow-Methods': "GET,POST,OPTIONS,DELETE,PUT",
      'X-Requested-With': 'XMLHttpRequest',
      'MyClientCert': '',        // This is empty
      'MyToken': ''
    })
  }

the cors declared at backend is metioned below

cors = CORS(app, resources={r"/login": {"origins": "*"}})
 @app.route('/login', methods=['GET','POST'])
 def loginForm():
 json_data = ast.literal_eval(request.data.decode('utf-8'))
  print('\n\n\n',json_data,'\n\n\n')

im not able to find were is the problem is raising

Note: cross origin arising in the time of login process other wise in the consecutive steps

Body:
add below code in your app.py

CORS(app, supports_credentials=True)

and from frontend use

{with-credentials :true}

it will enable the communication between the frontend and backend


问:
Is Perl a good option for heavy text-processing?
I have this web application which needs to do several heavy text processing tasks: removing certain characters, parsing XML files, among others. Some of them involve regular expressions.

The web application has some implementations in Java and others in PHP. Is it worth using Perl or other specific text processing language for such tasks, or is there really no difference with using PHP?

I even thought of using Sed, Awk maybe even some compiled C scripts for processing texts. There's a lot of text to be processed...

答:
Yes, Perl was designed with processing text in mind.

It has tons of useful text processing features, and it was the first language I used (long ago) that had regular expressions.

http://en.wikipedia.org/wiki/Perl

OwnerDisplayName: Fernando

LastEditorDisplayName: brian d foy

OwnerDisplayName: TwistedAphid


问:
ASIHTTPRequest only works when i hardcode the strings
I have a problem that really makes me scratch my head. There seems to be no logical reason why this is happening. If i hardcode the string into the NSURL it works. But if I pass a NSString instead it doesnt work. I have confirmed that the NSString is identical to hardcoded string by NSLog both of them.

Code that works. Server returns a 200 responce code.

```<code>        //NSString * urlStr = [NSString stringWithFormat:@"http://www.server.com/%@",monograph.uri];
    NSURL *url = [NSURL URLWithString:@"http://www.server.com/api/monograph/com/3894.json"];

    ASIHTTPRequest *request;
    request = [ASIHTTPRequest requestWithURL:url];
    [request setUsername:appDelegate.key];
    [request setPassword:appDelegate.secret];
    [request setDelegate:self];
    [request startAsynchronous];
</code>```

Code that fails. Server returns 204 response code for this:

```<code>NSString * urlStr = [NSString stringWithFormat:@"http://www.server.com/%@",monograph.uri];
    NSURL *url = [NSURL URLWithString:urlStr];

    ASIHTTPRequest *request;
    request = [ASIHTTPRequest requestWithURL:url];
    [request setUsername:appDelegate.key];
    [request setPassword:appDelegate.secret];
    [request setDelegate:self];
    [request startAsynchronous];
</code>```

When i NSLog urlStr it contains:

```<code>http://www.server.com/api/monograph/com/3894.json
</code>```

What am i missing? There must be something to explain it -.-

Regards,
Code

EDIT

checked the length of both strings and they are both same length so seems not white spaces or anything hidden in there.

答:
Cut all the new lines/spaces from the string, this is one possible reason. And sometimes the log doesn't show you the new lines.

try

NSString * s = [monograph.uri stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

NSString * urlStr = [NSString stringWithFormat:@"http://www.server.com/%@",s];

Body:
I have a problem that really makes me scratch my head. There seems to be no logical reason why this is happening. If i hardcode the string into the NSURL it works. But if I pass a NSString instead it doesnt work. I have confirmed that the NSString is identical to hardcoded string by NSLog both of them.

Code that works. Server returns a 200 responce code.

        //NSString * urlStr = [NSString stringWithFormat:@"http://www.server.com/%@",monograph.uri];
    NSURL *url = [NSURL URLWithString:@"http://www.server.com/api/monograph/com/3894.json"];

    ASIHTTPRequest *request;
    request = [ASIHTTPRequest requestWithURL:url];
    [request setUsername:appDelegate.key];
    [request setPassword:appDelegate.secret];
    [request setDelegate:self];
    [request startAsynchronous];

Code that fails. Server returns 204 response code for this:

NSString * urlStr = [NSString stringWithFormat:@"http://www.server.com/%@",monograph.uri];
    NSURL *url = [NSURL URLWithString:urlStr];

    ASIHTTPRequest *request;
    request = [ASIHTTPRequest requestWithURL:url];
    [request setUsername:appDelegate.key];
    [request setPassword:appDelegate.secret];
    [request setDelegate:self];
    [request startAsynchronous];

When i NSLog urlStr it contains:

http://www.server.com/api/monograph/com/3894.json

What am i missing? There must be something to explain it -.-

Regards,
Code

EDIT

checked the length of both strings and they are both same length so seems not white spaces or anything hidden in there.


问:
How to I call post api in requests python?
I have an API which takes three parameter, Two are strings, while third is a file named "content".

```<code>from datetime import date

AuthToken = "xxxxxxxxxxx"
fileName = "a.txt"
FolderID = "xxxxxxxxxxx"
myfiles = {'file': ('report.xls', open('C:\\Users\\Nawaf Momin\\Desktop\\a.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
URL = "https://apidocs.zoho.com/files/v1/upload?authtoken=" + AuthToken + "&scope=docsapi"
mydata = {
    'filename': fileName,
    'fid': FolderID,
    'content': myfiles
}
r = requests.post(url=URL, data=mydata)
print(r.status_code)
print(r.text)
</code>```

for api documentation visit :https://www.zoho.com/docs/zoho-docs-api.html
its upload post api..

答:
You did not indicate the error you are getting so I assume the file content is not showing up. You probably should put the file content separately and add headers to it, also you need to install and import the requests library as it is not built in.

```<code>from datetime import date
import requests

headers = {
"User-Agent":"Mozilla/5.0" #you will need to complete this user agent yourself
}

AuthToken = "xxxxxxxxxxx"
fileName = "a.txt"
FolderID = "xxxxxxxxxxx"
myfiles = {'file': ('report.xls', open('C:\\Users\\Nawaf Momin\\Desktop\\a.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
URL = "https://apidocs.zoho.com/files/v1/upload

params = {
authtoken":AuthToken,
"scope":"docsapi"
}

r = requests.post(url=URL,  params=params, files=myfile, headers=headers)
print(r.status_code)
print(r.text)
</code>```

Hope this helped

Body:
I have an API which takes three parameter, Two are strings, while third is a file named "content".

from datetime import date

AuthToken = "xxxxxxxxxxx"
fileName = "a.txt"
FolderID = "xxxxxxxxxxx"
myfiles = {'file': ('report.xls', open('C:\\Users\\Nawaf Momin\\Desktop\\a.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
URL = "https://apidocs.zoho.com/files/v1/upload?authtoken=" + AuthToken + "&scope=docsapi"
mydata = {
    'filename': fileName,
    'fid': FolderID,
    'content': myfiles
}
r = requests.post(url=URL, data=mydata)
print(r.status_code)
print(r.text)

for api documentation visit :https://www.zoho.com/docs/zoho-docs-api.html
its upload post api..

Body:
You did not indicate the error you are getting so I assume the file content is not showing up. You probably should put the file content separately and add headers to it, also you need to install and import the requests library as it is not built in.

from datetime import date
import requests

headers = {
"User-Agent":"Mozilla/5.0" #you will need to complete this user agent yourself
}

AuthToken = "xxxxxxxxxxx"
fileName = "a.txt"
FolderID = "xxxxxxxxxxx"
myfiles = {'file': ('report.xls', open('C:\\Users\\Nawaf Momin\\Desktop\\a.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
URL = "https://apidocs.zoho.com/files/v1/upload

params = {
authtoken":AuthToken,
"scope":"docsapi"
}

r = requests.post(url=URL,  params=params, files=myfile, headers=headers)
print(r.status_code)
print(r.text)

Hope this helped