text:
Q: Why does MySQL's performance decrease when queries are executed in parallel? The Question: Why MySQL performance goes down for queries joining nearly empty tables when executed in parallel?
Below is more detailed explanation of the issue I'm facing. I have two tables in MySQL
CREATE TABLE first (
    num int(10) NOT NULL,
    UNIQUE KEY key_num (num)
) ENGINE=InnoDB

CREATE TABLE second (
    num int(10) NOT NULL,
    num2 int(10) NOT NULL,
    UNIQUE KEY key_num (num, num2)
) ENGINE=InnoDB

The first one contains about a thousand records. The second one is empty or contains a very few records. It also contains double index which somehow relates to the issue: the problem goes away for single index. Now I'm trying to make a lot of identical queries to those tables in parallel. Each query looks like this:
SELECT first.num
FROM first
LEFT JOIN second AS second_1 ON second_1.num = -1 # non-existent key
LEFT JOIN second AS second_2 ON second_2.num = -2 # non-existent key
LEFT JOIN second AS second_3 ON second_3.num = -3 # non-existent key
LEFT JOIN second AS second_4 ON second_4.num = -4 # non-existent key
LEFT JOIN second AS second_5 ON second_5.num = -5 # non-existent key
LEFT JOIN second AS second_6 ON second_6.num = -6 # non-existent key
WHERE second_1.num IS NULL
  AND second_2.num IS NULL
  AND second_3.num IS NULL
  AND second_4.num IS NULL
  AND second_5.num IS NULL
  AND second_6.num IS NULL

The issue I'm getting is that instead of having a nearly linear raise in performance on 8 core machine I actually have a drop. Namely having one process, the typical number of requests per second I have is about 200. Having two processes instead of expected increase up to 300 - 400 queries per second I actually have a drop down to 150. For 10 processes I have only 70 queries per seconds. The Perl code I'm using for testing is shown below:
#!/usr/bin/perl

use strict;
use warnings;

use DBI;
use Parallel::Benchmark;
use SQL::Abstract;
use SQL::Abstract::Plugin::InsertMulti;

my $children_dbh;

foreach my $second_table_row_count (0, 1, 1000) {
    print '#' x 80, "\nsecond_table_row_count = $second_table_row_count\n";
    create_and_fill_tables(1000, $second_table_row_count);
    foreach my $concurrency (1, 2, 3, 4, 6, 8, 10, 20) {
        my $bm = Parallel::Benchmark->new(
            'benchmark' => sub {
                _run_sql();
                return 1;
            },
            'concurrency' => $concurrency,
            'time' => 3,
        );
        my $result = $bm->run();
    }
}

sub create_and_fill_tables {
    my ($first_table_row_count, $second_table_row_count) = @_;
    my $dbh = dbi_connect();
    {
        $dbh->do(q{DROP TABLE IF EXISTS first});
        $dbh->do(q{
            CREATE TABLE first (
                num int(10) NOT NULL,
                UNIQUE KEY key_num (num)
            ) ENGINE=InnoDB
        });
        if ($first_table_row_count) {
            my ($stmt, @bind) = SQL::Abstract->new()->insert_multi(
                'first',
                ['num'],
                [map {[$_]} 1 .. $first_table_row_count],
            );
            $dbh->do($stmt, undef, @bind);
        }
    }
    {
        $dbh->do(q{DROP TABLE IF EXISTS second});
        $dbh->do(q{
            CREATE TABLE second (
                num int(10) NOT NULL,
                num2 int(10) NOT NULL,
                UNIQUE KEY key_num (num, num2)
            ) ENGINE=InnoDB
        });
        if ($second_table_row_count) {
            my ($stmt, @bind) = SQL::Abstract->new()->insert_multi(
                'second',
                ['num'],
                [map {[$_]} 1 .. $second_table_row_count],
            );
            $dbh->do($stmt, undef, @bind);
        }
    }
}

sub _run_sql {
    $children_dbh ||= dbi_connect();
    $children_dbh->selectall_arrayref(q{
        SELECT first.num
        FROM first
        LEFT JOIN second AS second_1 ON second_1.num = -1
        LEFT JOIN second AS second_2 ON second_2.num = -2
        LEFT JOIN second AS second_3 ON second_3.num = -3
        LEFT JOIN second AS second_4 ON second_4.num = -4
        LEFT JOIN second AS second_5 ON second_5.num = -5
        LEFT JOIN second AS second_6 ON second_6.num = -6
        WHERE second_1.num IS NULL
          AND second_2.num IS NULL
          AND second_3.num IS NULL
          AND second_4.num IS NULL
          AND second_5.num IS NULL
          AND second_6.num IS NULL
    });
}

sub dbi_connect {
    return DBI->connect(
        'dbi:mysql:'
            . 'database=tmp'
            . ';host=localhost'
            . ';port=3306',
        'root',
        '',
    );
}

And for compare queries like this executed in concurrent with increasing performance:
SELECT first.num
FROM first
LEFT JOIN second AS second_1 ON second_1.num = 1 # existent key
LEFT JOIN second AS second_2 ON second_2.num = 2 # existent key
LEFT JOIN second AS second_3 ON second_3.num = 3 # existent key
LEFT JOIN second AS second_4 ON second_4.num = 4 # existent key
LEFT JOIN second AS second_5 ON second_5.num = 5 # existent key
LEFT JOIN second AS second_6 ON second_6.num = 6 # existent key
WHERE second_1.num IS NOT NULL
  AND second_2.num IS NOT NULL
  AND second_3.num IS NOT NULL
  AND second_4.num IS NOT NULL
  AND second_5.num IS NOT NULL
  AND second_6.num IS NOT NULL

Testing results, cpu and disk usage measurements are here:

* table `first` have 1000 rows
* table `second` have 6 rows: `[1,1],[2,2],..[6,6]`

For query:
    SELECT first.num
    FROM first
    LEFT JOIN second AS second_1 ON second_1.num = -1 # non-existent key
    LEFT JOIN second AS second_2 ON second_2.num = -2 # non-existent key
    LEFT JOIN second AS second_3 ON second_3.num = -3 # non-existent key
    LEFT JOIN second AS second_4 ON second_4.num = -4 # non-existent key
    LEFT JOIN second AS second_5 ON second_5.num = -5 # non-existent key
    LEFT JOIN second AS second_6 ON second_6.num = -6 # non-existent key
    WHERE second_1.num IS NULL
      AND second_2.num IS NULL
      AND second_3.num IS NULL
      AND second_4.num IS NULL
      AND second_5.num IS NULL
      AND second_6.num IS NULL

Results:
    concurrency: 1,     speed: 162.910 / sec
    concurrency: 2,     speed: 137.818 / sec
    concurrency: 3,     speed: 130.728 / sec
    concurrency: 4,     speed: 107.387 / sec
    concurrency: 6,     speed: 90.513 / sec
    concurrency: 8,     speed: 80.445 / sec
    concurrency: 10,    speed: 80.381 / sec
    concurrency: 20,    speed: 84.069 / sec

System usage after for last 60 minutes of running query in 6 processes:
    $ iostat -cdkx 60

    avg-cpu:  %user   %nice %system %iowait  %steal   %idle
              74.82    0.00    0.08    0.00    0.08   25.02

    Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await  svctm  %util
    sda1              0.00     0.00    0.00    0.12     0.00     0.80    13.71     0.00    1.43   1.43   0.02
    sdf10             0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   10.00   5.00   0.02
    sdf4              0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   30.00  15.00   0.05
    sdm               0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdf8              0.00     0.00    0.00    0.37     0.00     1.24     6.77     0.00    5.00   3.18   0.12
    sdf6              0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   10.00   5.00   0.02
    sdf9              0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00    0.00   0.00   0.00
    sdf               0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdf3              0.00     0.00    0.00    0.08     0.00     1.33    32.00     0.00    4.00   4.00   0.03
    sdf2              0.00     0.00    0.00    0.17     0.00     1.37    16.50     0.00    3.00   3.00   0.05
    sdf15             0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdf14             0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdf1              0.00     0.00    0.00    0.05     0.00     0.40    16.00     0.00    0.00   0.00   0.00
    sdf13             0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   10.00   5.00   0.02
    sdf5              0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   50.00  25.00   0.08
    sdm2              0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdm1              0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdf12             0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   10.00   5.00   0.02
    sdf11             0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   10.00   5.00   0.02
    sdf7              0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   10.00   5.00   0.02
    md0               0.00     0.00    0.00    0.97     0.00    13.95    28.86     0.00    0.00   0.00   0.00

################################################################################

For query:
    SELECT first.num
    FROM first
    LEFT JOIN second AS second_1 ON second_1.num = 1 # existent key
    LEFT JOIN second AS second_2 ON second_2.num = 2 # existent key
    LEFT JOIN second AS second_3 ON second_3.num = 3 # existent key
    LEFT JOIN second AS second_4 ON second_4.num = 4 # existent key
    LEFT JOIN second AS second_5 ON second_5.num = 5 # existent key
    LEFT JOIN second AS second_6 ON second_6.num = 6 # existent key
    WHERE second_1.num IS NOT NULL
      AND second_2.num IS NOT NULL
      AND second_3.num IS NOT NULL
      AND second_4.num IS NOT NULL
      AND second_5.num IS NOT NULL
      AND second_6.num IS NOT NULL

Results:
    concurrency: 1,     speed: 875.973 / sec
    concurrency: 2,     speed: 944.986 / sec
    concurrency: 3,     speed: 1256.072 / sec
    concurrency: 4,     speed: 1401.657 / sec
    concurrency: 6,     speed: 1354.351 / sec
    concurrency: 8,     speed: 1110.100 / sec
    concurrency: 10,    speed: 1145.251 / sec
    concurrency: 20,    speed: 1142.514 / sec

System usage after for last 60 minutes of running query in 6 processes:
    $ iostat -cdkx 60

    avg-cpu:  %user   %nice %system %iowait  %steal   %idle
              74.40    0.00    0.53    0.00    0.06   25.01

    Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await  svctm  %util
    sda1              0.00     0.00    0.00    0.02     0.00     0.13    16.00     0.00    0.00   0.00   0.00
    sdf10             0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   10.00   5.00   0.02
    sdf4              0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   10.00   5.00   0.02
    sdm               0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdf8              0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   10.00   5.00   0.02
    sdf6              0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00    0.00   0.00   0.00
    sdf9              0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   10.00   5.00   0.02
    sdf               0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdf3              0.00     0.00    0.00    0.13     0.00     2.67    40.00     0.00    3.75   2.50   0.03
    sdf2              0.00     0.00    0.00    0.23     0.00     2.72    23.29     0.00    2.14   1.43   0.03
    sdf15             0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdf14             0.00     0.00    0.00    0.98     0.00     0.54     1.10     0.00    2.71   2.71   0.27
    sdf1              0.00     0.00    0.00    0.08     0.00     1.47    35.20     0.00    8.00   6.00   0.05
    sdf13             0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdf5              0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   10.00   5.00   0.02
    sdm2              0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdm1              0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdf12             0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00   0.00   0.00
    sdf11             0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00    0.00   0.00   0.00
    sdf7              0.00     0.00    0.00    0.03     0.00     1.07    64.00     0.00   10.00   5.00   0.02
    md0               0.00     0.00    0.00    1.70     0.00    15.92    18.74     0.00    0.00   0.00   0.00

################################################################################

And this server has lots of free memory. Example of top:
    top - 19:02:59 up  4:23,  4 users,  load average: 4.43, 3.03, 2.01
    Tasks: 218 total,   1 running, 217 sleeping,   0 stopped,   0 zombie
    Cpu(s): 72.8%us,  0.7%sy,  0.0%ni, 26.3%id,  0.0%wa,  0.0%hi,  0.0%si,  0.1%st
    Mem:  71701416k total, 22183980k used, 49517436k free,      284k buffers
    Swap:        0k total,        0k used,        0k free,  1282768k cached

      PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
     2506 mysql     20   0 51.7g  17g 5920 S  590 25.8 213:15.12 mysqld
     9348 topadver  20   0 72256  11m 1428 S    2  0.0   0:01.45 perl
     9349 topadver  20   0 72256  11m 1428 S    2  0.0   0:01.44 perl
     9350 topadver  20   0 72256  11m 1428 S    2  0.0   0:01.45 perl
     9351 topadver  20   0 72256  11m 1428 S    1  0.0   0:01.44 perl
     9352 topadver  20   0 72256  11m 1428 S    1  0.0   0:01.44 perl
     9353 topadver  20   0 72256  11m 1428 S    1  0.0   0:01.44 perl
     9346 topadver  20   0 19340 1504 1064 R    0  0.0   0:01.89 top

Does anyone have an idea why performance decreased for query with non-existent keys?

A: Well written question, that shows some research.
Out of curiosity, I tried MySQL 5.6 to see what the tooling there has to say about these queries.
First, note that the queries are different:

*

*changing the value from "1" to "-1" for the existent / non existent
key case is one thing

*changing "second_1.num IS NOT NULL" to
"second_1.num IS NULL" in the WHERE clause is another.

Using EXPLAIN  gives different plans:
EXPLAIN SELECT `first`.num
FROM `first`
LEFT JOIN `second` AS second_1 ON second_1.num = -1 # non-existent key
LEFT JOIN `second` AS second_2 ON second_2.num = -2 # non-existent key
LEFT JOIN `second` AS second_3 ON second_3.num = -3 # non-existent key
LEFT JOIN `second` AS second_4 ON second_4.num = -4 # non-existent key
LEFT JOIN `second` AS second_5 ON second_5.num = -5 # non-existent key
LEFT JOIN `second` AS second_6 ON second_6.num = -6 # non-existent key
WHERE second_1.num IS NULL
AND second_2.num IS NULL
AND second_3.num IS NULL
AND second_4.num IS NULL
AND second_5.num IS NULL
AND second_6.num IS NULL
;
id      select_type     table   type    possible_keys   key     key_len ref     rows    Extra
1       SIMPLE  first   index   NULL    key_num 4       NULL    1000    Using index
1       SIMPLE  second_1        ref     key_num key_num 4       const   1       Using where; Not exists; Using index
1       SIMPLE  second_2        ref     key_num key_num 4       const   1       Using where; Not exists; Using index
1       SIMPLE  second_3        ref     key_num key_num 4       const   1       Using where; Not exists; Using index
1       SIMPLE  second_4        ref     key_num key_num 4       const   1       Using where; Not exists; Using index
1       SIMPLE  second_5        ref     key_num key_num 4       const   1       Using where; Not exists; Using index
1       SIMPLE  second_6        ref     key_num key_num 4       const   1       Using where; Not exists; Using index

as opposed to
EXPLAIN SELECT `first`.num
FROM `first`
LEFT JOIN `second` AS second_1 ON second_1.num = 1 # existent key
LEFT JOIN `second` AS second_2 ON second_2.num = 2 # existent key
LEFT JOIN `second` AS second_3 ON second_3.num = 3 # existent key
LEFT JOIN `second` AS second_4 ON second_4.num = 4 # existent key
LEFT JOIN `second` AS second_5 ON second_5.num = 5 # existent key
LEFT JOIN `second` AS second_6 ON second_6.num = 6 # existent key
WHERE second_1.num IS NOT NULL
AND second_2.num IS NOT NULL
AND second_3.num IS NOT NULL
AND second_4.num IS NOT NULL
AND second_5.num IS NOT NULL
AND second_6.num IS NOT NULL
;
id      select_type     table   type    possible_keys   key     key_len ref     rows    Extra
1       SIMPLE  second_1        ref     key_num key_num 4       const   1       Using index
1       SIMPLE  second_2        ref     key_num key_num 4       const   1       Using index
1       SIMPLE  second_3        ref     key_num key_num 4       const   1       Using index
1       SIMPLE  second_4        ref     key_num key_num 4       const   1       Using index
1       SIMPLE  second_5        ref     key_num key_num 4       const   1       Using index
1       SIMPLE  second_6        ref     key_num key_num 4       const   1       Using index
1       SIMPLE  first   index   NULL    key_num 4       NULL    1000    Using index; Using join buffer (Block Nested Loop)

Using the JSON format, we have:
EXPLAIN FORMAT=JSON SELECT `first`.num
FROM `first`
LEFT JOIN `second` AS second_1 ON second_1.num = -1 # non-existent key
LEFT JOIN `second` AS second_2 ON second_2.num = -2 # non-existent key
LEFT JOIN `second` AS second_3 ON second_3.num = -3 # non-existent key
LEFT JOIN `second` AS second_4 ON second_4.num = -4 # non-existent key
LEFT JOIN `second` AS second_5 ON second_5.num = -5 # non-existent key
LEFT JOIN `second` AS second_6 ON second_6.num = -6 # non-existent key
WHERE second_1.num IS NULL
AND second_2.num IS NULL
AND second_3.num IS NULL
AND second_4.num IS NULL
AND second_5.num IS NULL
AND second_6.num IS NULL
;
EXPLAIN
{
  "query_block": {
    "select_id": 1,
    "nested_loop": [
      {
        "table": {
          "table_name": "first",
          "access_type": "index",
          "key": "key_num",
          "key_length": "4",
          "rows": 1000,
          "filtered": 100,
          "using_index": true
        }
      },
      {
        "table": {
          "table_name": "second_1",
          "access_type": "ref",
          "possible_keys": [
            "key_num"
          ],
          "key": "key_num",
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows": 1,
          "filtered": 100,
          "not_exists": true,
          "using_index": true,
          "attached_condition": "<if>(found_match(second_1), isnull(`test`.`second_1`.`num`), true)"
        }
      },
      {
        "table": {
          "table_name": "second_2",
          "access_type": "ref",
          "possible_keys": [
            "key_num"
          ],
          "key": "key_num",
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows": 1,
          "filtered": 100,
          "not_exists": true,
          "using_index": true,
          "attached_condition": "<if>(found_match(second_2), isnull(`test`.`second_2`.`num`), true)"
        }
      },
      {
        "table": {
          "table_name": "second_3",
          "access_type": "ref",
          "possible_keys": [
            "key_num"
          ],
          "key": "key_num",
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows": 1,
          "filtered": 100,
          "not_exists": true,
          "using_index": true,
          "attached_condition": "<if>(found_match(second_3), isnull(`test`.`second_3`.`num`), true)"
        }
      },
      {
        "table": {
          "table_name": "second_4",
          "access_type": "ref",
          "possible_keys": [
            "key_num"
          ],
          "key": "key_num",
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows": 1,
          "filtered": 100,
          "not_exists": true,
          "using_index": true,
          "attached_condition": "<if>(found_match(second_4), isnull(`test`.`second_4`.`num`), true)"
        }
      },
      {
        "table": {
          "table_name": "second_5",
          "access_type": "ref",
          "possible_keys": [
            "key_num"
          ],
          "key": "key_num",
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows": 1,
          "filtered": 100,
          "not_exists": true,
          "using_index": true,
          "attached_condition": "<if>(found_match(second_5), isnull(`test`.`second_5`.`num`), true)"
        }
      },
      {
        "table": {
          "table_name": "second_6",
          "access_type": "ref",
          "possible_keys": [
            "key_num"
          ],
          "key": "key_num",
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows": 1,
          "filtered": 100,
          "not_exists": true,
          "using_index": true,
          "attached_condition": "<if>(found_match(second_6), isnull(`test`.`second_6`.`num`), true)"
        }
      }
    ]
  }
}

as opposed to
EXPLAIN FORMAT=JSON SELECT `first`.num
FROM `first`
LEFT JOIN `second` AS second_1 ON second_1.num = 1 # existent key
LEFT JOIN `second` AS second_2 ON second_2.num = 2 # existent key
LEFT JOIN `second` AS second_3 ON second_3.num = 3 # existent key
LEFT JOIN `second` AS second_4 ON second_4.num = 4 # existent key
LEFT JOIN `second` AS second_5 ON second_5.num = 5 # existent key
LEFT JOIN `second` AS second_6 ON second_6.num = 6 # existent key
WHERE second_1.num IS NOT NULL
AND second_2.num IS NOT NULL
AND second_3.num IS NOT NULL
AND second_4.num IS NOT NULL
AND second_5.num IS NOT NULL
AND second_6.num IS NOT NULL
;
EXPLAIN
{
  "query_block": {
    "select_id": 1,
    "nested_loop": [
      {
        "table": {
          "table_name": "second_1",
          "access_type": "ref",
          "possible_keys": [
            "key_num"
          ],
          "key": "key_num",
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows": 1,
          "filtered": 100,
          "using_index": true
        }
      },
      {
        "table": {
          "table_name": "second_2",
          "access_type": "ref",
          "possible_keys": [
            "key_num"
          ],
          "key": "key_num",
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows": 1,
          "filtered": 100,
          "using_index": true
        }
      },
      {
        "table": {
          "table_name": "second_3",
          "access_type": "ref",
          "possible_keys": [
            "key_num"
          ],
          "key": "key_num",
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows": 1,
          "filtered": 100,
          "using_index": true
        }
      },
      {
        "table": {
          "table_name": "second_4",
          "access_type": "ref",
          "possible_keys": [
            "key_num"
          ],
          "key": "key_num",
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows": 1,
          "filtered": 100,
          "using_index": true
        }
      },
      {
        "table": {
          "table_name": "second_5",
          "access_type": "ref",
          "possible_keys": [
            "key_num"
          ],
          "key": "key_num",
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows": 1,
          "filtered": 100,
          "using_index": true
        }
      },
      {
        "table": {
          "table_name": "second_6",
          "access_type": "ref",
          "possible_keys": [
            "key_num"
          ],
          "key": "key_num",
          "key_length": "4",
          "ref": [
            "const"
          ],
          "rows": 1,
          "filtered": 100,
          "using_index": true
        }
      },
      {
        "table": {
          "table_name": "first",
          "access_type": "index",
          "key": "key_num",
          "key_length": "4",
          "rows": 1000,
          "filtered": 100,
          "using_index": true,
          "using_join_buffer": "Block Nested Loop"
        }
      }
    ]
  }
}

Looking at the table io instrumented by the performance schema at runtime, we have:
truncate table performance_schema.objects_summary_global_by_type;
select * from performance_schema.objects_summary_global_by_type
where OBJECT_NAME in ("first", "second");
OBJECT_TYPE OBJECT_SCHEMA   OBJECT_NAME COUNT_STAR  SUM_TIMER_WAIT  MIN_TIMER_WAIT  AVG_TIMER_WAIT  MAX_TIMER_WAIT
TABLE   test    first   0   0   0   0   0
TABLE   test    second  0   0   0   0   0
SELECT `first`.num
FROM `first`
LEFT JOIN `second` AS second_1 ON second_1.num = -1 # non-existent key
LEFT JOIN `second` AS second_2 ON second_2.num = -2 # non-existent key
LEFT JOIN `second` AS second_3 ON second_3.num = -3 # non-existent key
LEFT JOIN `second` AS second_4 ON second_4.num = -4 # non-existent key
LEFT JOIN `second` AS second_5 ON second_5.num = -5 # non-existent key
LEFT JOIN `second` AS second_6 ON second_6.num = -6 # non-existent key
WHERE second_1.num IS NULL
AND second_2.num IS NULL
AND second_3.num IS NULL
AND second_4.num IS NULL
AND second_5.num IS NULL
AND second_6.num IS NULL
;
(...)
select * from performance_schema.objects_summary_global_by_type
where OBJECT_NAME in ("first", "second");
OBJECT_TYPE OBJECT_SCHEMA   OBJECT_NAME COUNT_STAR  SUM_TIMER_WAIT  MIN_TIMER_WAIT  AVG_TIMER_WAIT  MAX_TIMER_WAIT
TABLE   test    first   1003    5705014442  1026171 5687889 87356557
TABLE   test    second  6012    271786533972    537266  45207298    1123939292

as opposed to:
select * from performance_schema.objects_summary_global_by_type
where OBJECT_NAME in ("first", "second");
OBJECT_TYPE OBJECT_SCHEMA   OBJECT_NAME COUNT_STAR  SUM_TIMER_WAIT  MIN_TIMER_WAIT  AVG_TIMER_WAIT  MAX_TIMER_WAIT
TABLE   test    first   1003    5211074603  969338  5195454 61066176
TABLE   test    second  24  458656783   510085  19110361    66229860

The query that scales does almost no table IO in table second.
The query that does not scale does 6K table IO in table second, or 6 times the size of table first.
This is because the query plans are different, in turn because the queries are different (IS NOT NULL versus IS NULL).
I think that answers the performance related question.
Note that both queries returned 1000 rows in my tests, which may not be what you want.
Before tuning a query to make it faster, make sure it works as expected.

A: I'll suggest trying an approach where each fork uses its own connection (it looks to me that right now $children_dbh, which holds a DB connection, is a shared variable). Or, even better, implement so-called connection pool, from which each client process will take a connection at a time when it's required, and will 'give it back' when it's no longer needed.
Check this answer for further details: the thread where it was given is about Java, but it's actually about some universal principles of MySQL organization. And this answer might be useful as well.
P.S. Somewhat similar situation (I think) is described here, and there's a detailed explanation of how to organize a connection pool.


text:
Q: Prevent adding users via gnome-control-center We require users to be added using a special script and therefore adding users via GUI (i.e. gnome-control-center user-accounts) should be blocked to prevent someone accidentally not using the script.
Is that possible? Removing gnome-control-center entirely is not an option. Ubuntu version is currently 20.04.

A: A Basic idea is to change polkit policy
edit the file /usr/share/polkit-1/actions/org.freedesktop.accounts.policy
sudo -H gedit /usr/share/polkit-1/actions/org.freedesktop.accounts.policy

Edited Content:
<action id="org.freedesktop.accounts.user-administration">
.........
.........
.........
    <defaults>
      <allow_any>none</allow_any>
      <allow_inactive>none</allow_inactive>
      <allow_active>none</allow_active>
    </defaults>
 </action>

I have edited 3 lines with none
Tested in gnome-shell 3.38.0

the above is just an idea.. you may dig further to have a localized location of the same file to prevent overwrite in updates..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android: what is the best way to load images from web without using AsyncTask? The common task in Android development is loading images from web and binding with ImageView in Activity. In code that I had been saw programmers often use AsyncTask to run loading in background and post result in context.
This approach lead us to craching aplication in some cases sucn as orientation changes. The cause is context. Because activity could be destroyed and created again our context also would be lost, but in running AsyncTask context is not update. So when postExectute will be invoked AsyncTask try to post result to Activity that no more exist.
I want to know what approaches you are using to load data as images and then posting into Activity?

A: You should try using what's called and AsyncTaskLoader. It's like an AsycnTask, except that the whole "need to delete the AsyncTask when the activity dies" bit is take care of for you. Loaders in general were designed almost specifically to improve the task of asynchronously loading data for listviews. In fact, they have quickly become one of my favorite new android classes to use. For more information on loaders, checkout this documentation.
As a final note, loaders weren't introduced until API level 10. That said, you can still access them from lesser api levels using the android Support Package.

A: Here is the complete code that load the images in background and stores it to sdcard.if the image is already there then it wont make request to server.
package com.packsmooch.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class Albumartloader
{
    private HashMap<String, Bitmap> cache = new HashMap<String, Bitmap>();

    private File cacheDir;
    private Bitmap  useThisBitmap;

    public Albumartloader(Context context)
    {
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir = new File(android.os.Environment.getExternalStorageDirectory(),"Streaming_Service/AlbumArt/");
        else
            cacheDir = context.getCacheDir();

        if (!cacheDir.exists())
            cacheDir.mkdirs();
    }

    public void DisplayImage(String url, Activity activity, ImageView imageView)
    {
         if(!url.equals(""))
         {
             if (cache.containsKey(url))
             {
                 imageView.setImageBitmap(cache.get(url));
             }
             else
             {
                queuePhoto(url, activity, imageView);
            }
         }
    }

    private void queuePhoto(String url, Activity activity, ImageView imageView)
    {
        photosQueue.Clean(imageView);
        PhotoToLoad p = new PhotoToLoad(url, imageView);

        synchronized (photosQueue.photosToLoad)
        {
            photosQueue.photosToLoad.push(p);
            photosQueue.photosToLoad.notifyAll();
        }

        // start thread if it's not started yet
        if (photoLoaderThread.getState() == Thread.State.NEW)
            photoLoaderThread.start();
    }

    public Bitmap getBitmap(String url)
    {
        try
        {
            // I identify images by hashcode. Not a perfect solution, good for the
            // demo.
            String filename = String.valueOf(url.hashCode());
            File f = new File(cacheDir, filename);

            // from SD cache
            Bitmap b = decodeFile(f);
            if (b != null)
                return b;

            // from web
            try {
                Bitmap bitmap = null;
                if(!url.equals("")){
                InputStream is = new URL(url).openStream();
                OutputStream os = new FileOutputStream(f);
                Utils.CopyStream(is, os);
                os.close();
                bitmap = decodeFile(f);
                }
                return bitmap;
            } catch (Exception ex) {
                ex.printStackTrace();
                return null;
            }
        }
        catch(Exception e)
        {
            return null;
        }
    }

    /*decodes image and scales it to reduce memory consumption
     * @param file path
     * @throws FileNotFoundException
     * @return bitmap
     * */
    private Bitmap decodeFile(File f){
        Bitmap b = null;
        try {

            useThisBitmap = null;
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            final int IMAGE_MAX_SIZE =50;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);
            int scale = 2;
            if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
                scale = 2 ^ (int) Math.ceil(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5));
            }

            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();

            o2.inSampleSize = scale;
            b = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
            useThisBitmap = b;

        } catch (FileNotFoundException e) {

        }
        catch(Exception e)
        {

        }
        finally{
            System.gc();
        }
        return useThisBitmap;
    }

    // Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    PhotosQueue photosQueue = new PhotosQueue();

    public void stopThread()
    {
        photoLoaderThread.interrupt();
    }

    // stores list of photos to download
    class PhotosQueue {
        private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();

        // removes all instances of this ImageView
        public void Clean(ImageView image) {
            for (int j = 0; j < photosToLoad.size();) {
                if (photosToLoad.get(j).imageView == image)
                    photosToLoad.remove(j);
                else
                    ++j;
            }
        }
    }

    class PhotosLoader extends Thread {
        public void run() {
            try {
                while (true) {
                    // thread waits until there are any images to load in the
                    // queue
                    if (photosQueue.photosToLoad.size() == 0)
                        synchronized (photosQueue.photosToLoad) {
                            photosQueue.photosToLoad.wait();
                        }
                    if (photosQueue.photosToLoad.size() != 0) {
                        PhotoToLoad photoToLoad;
                        synchronized (photosQueue.photosToLoad) {
                            photoToLoad = photosQueue.photosToLoad.pop();
                        }
                        Bitmap bmp = getBitmap(photoToLoad.url);
                        cache.put(photoToLoad.url, bmp);
                        if (((String) photoToLoad.imageView.getTag())
                                .equals(photoToLoad.url)) {
                            BitmapDisplayer bd = new BitmapDisplayer(bmp,
                                    photoToLoad.imageView);
                            Activity a = (Activity) photoToLoad.imageView
                                    .getContext();
                            a.runOnUiThread(bd);
                        }
                    }
                    if (Thread.interrupted())
                        break;
                }
            } catch (InterruptedException e) {
                // allow thread to exit
            }
        }
    }

    PhotosLoader photoLoaderThread = new PhotosLoader();

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        ImageView imageView;

        public BitmapDisplayer(Bitmap b, ImageView i) {
            bitmap = b;
            imageView = i;
        }

        public void run()
        {
            if (bitmap != null)
                imageView.setImageBitmap(bitmap);
        }
    }

    public void clearCache()
    {
        // clear memory cache
        cache.clear();
        // clear SD cache
        File[] files = cacheDir.listFiles();
        for (File f : files)
            f.delete();
    }
}

Here is the usage:
Albumartloader  albumartloader=new Albumartloader(this);
imageview.settag(urlofimage);
albumartloader.DisplayImage(url of image,activity context,imageview);

Best usage:-you can use it for listview when you need to display number of images from server and dont want to wait for all images to download.


text:
Q: Show that two intersecting curves on a regular surface with the same osculating plane that is not the tangent plane have the same curvature Let $\bf{p}$ be a point on a regular surface $S$.
Let $\boldsymbol{\alpha}(s)$ and $\boldsymbol{\beta}(s)$ be two curves parametrized by arc length on the surface $S$ such that $\boldsymbol{\alpha}(0) = \boldsymbol{\beta}(0) = \bf{p}$.
Denote the Frenet trihedron of $\boldsymbol{\alpha}(s)$ at $\bf{p}$ by $\bf{t}_{\alpha}$, $\bf{n}_{\alpha}$, $\bf{b}_{\alpha}$; the Frenet trihedron of $\boldsymbol{\beta}(s)$ at $\bf{p}$ by $\bf{t}_{\beta}$, $\bf{n}_{\beta}$, $\bf{b}_{\beta}$.
Suppose both curves have the same osculating plane at $\bf{p}$ and the osculating plane is not equal to the tangent plane at $\bf{p}$.
i) Show that $\bf{t}_{\alpha}$ and $\bf{t}_{\beta}$ are parallel, i.e. $\bf{t}_{\alpha} = \pm\bf{t}_{\beta}$.
ii) Show that $\bf{n}_{\alpha}$ and $\bf{n}_{\beta}$ are parallel, i.e. $\bf{n}_{\alpha} = \pm\bf{n}_{\beta}$.
iii) Show that both curves have the same curvature at $\bf{p}$.
I have only succeeded in showing i), where the strategy was to first assume they are not parallel. Taking the cross product of the two tangent vectors would then produce the normal of the osculating plane, a non-zero vector parallel to the Gauss map at $\bf{p}$. Since the tangent plane at $\bf{p}$ is defined by the normal vector at $\bf{p}$, i.e. the Gauss map, this implies that the osculating plane is the same as the tangent plane, which contradicts the setup.
This question was from an exam I took recently. Thank you.

A: You've done the hard part. Since the osculating planes of $\alpha$ and $\beta$ at $\mathbf p$ are the same and the tangent vectors are ($\pm$) the same, ii) follows. Here's a major hint for iii): Apply Meusnier's formula, which relates the normal curvature of $S$ in the direction of $\mathbf t_\alpha = \pm\mathbf t_\beta$ and the curvature of $\alpha$ (or $\beta$). What's the missing ingredient?
EDIT: Meusnier tells us that $\kappa_n = \kappa \mathbf n\cdot \nu = \kappa\cos\phi$, where $\nu$ is the surface normal and $\phi$ is the angle between the curve's principal normal and the surface normal. So if $\kappa_n$ is the same for both curves (as it depends only on the tangent direction of the curve), now what do you have?


text:
Q: injecting enum(Spring) I have an enum  and I need to inject it with spring bean.
my enum is:
public enum Status {

IN_PROCESS(1,"In process"),
DONE(0,"Successful"),
CANNOT_DONE(2,"Unsuccessful");

private final int code;
private final String description;

private Status(int code, String description){
    this.code = code;
    this.description = description;
}

public int getCode() {
    return code;
}

public String getDescription() {
    return description;
}

}

what my bean.xml should look like for this enum..
thanks.

A: You can not create an Enum via its constructor from outside of this Enum (not in java and not in Spring) because Enum values are constants!
An Enum constructor can only be invoked from the Enum declarion itselve.
Of course you can use an instance of this Enum, even in Spring, but you can not create it:
public Class Entity {
    public Entity(Status status) {...}
}

<bean name="entity" class="package.Entity">
   <property name="status" value="IN_PROCESS" />
</bean>

A: Technically you may try to register enum as a bean like this:
@Configuration
class EnumProducer {
   @Bean
   Status inProgress() {
        return Status.IN_PROGRESS;
   }
}

and then inject it like:
@Autowired("inProgress") Status status.

But there is no any sense for doing it.

A: Check <util:constant/> here:
http://static.springsource.org/spring/docs/3.0.x/reference/xsd-config.html


text:
Q: Android multicast - Sometimes receive is blocking thread I believe the MulticastSocket.receive method is blocking my thread. It won't work again unless the app goes to onResume(), which restarts the thread. How can I fix this?
Receiver Code
private class ReceiverThread extends Thread
{

    private static final String TAG = ComMessageReceiver.TAG + "Thread";

    private WifiManager wifiManager;
    private MulticastSocket multicastSocket;
    private InetSocketAddress groupInetSocketAddress;
    private boolean joinedGroup = false;

    public ReceiverThread(String group, int port, int timeout) throws IOException {

        super();

        wifiManager = (WifiManager) App.context.getSystemService(Context.WIFI_SERVICE);
        groupInetSocketAddress = new InetSocketAddress(InetAddress.getByName(group), port);
        multicastSocket = new MulticastSocket(port);
        multicastSocket.setSoTimeout(timeout);
    }

    public ReceiverThread() throws IOException {

        this(Config.multicastAddress, Config.multicastPort, DEFAULT_TIMEOUT);
    }

    @Override
    public void run() {

        Log.d(TAG, "started");

        while (!this.isInterrupted()) {

            if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {

                if (!joinedGroup) {

                    try {
                        multicastSocket.joinGroup(groupInetSocketAddress,
                                NetworkInterface.getByInetAddress(getWifiInetAddress()));

                        wifiManager.createMulticastLock("ComMessageReceiverLock").acquire();

                        joinedGroup = true;

                    } catch (IOException ex) {

                        Log.e(TAG, "Failed to join Multicast group: " + ex.getMessage());
                    }
                }

                try {

                    byte[] buffer = new byte[256];

                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                    multicastSocket.receive(packet);

                    Log.d(TAG, "Message received: " + message.message);

                } catch (SocketTimeoutException e) {
                } catch (IOException ex) {

                    multicastSocket = null;

                    Log.e(TAG, ex.getMessage());
                }
            } else
                joinedGroup = false;
        }
    }

}

Multicast code
private class ComServerThread extends Thread {

    private static final String LOG = "ComServerThread";
    private final static long INTERVAL = 1000;
    private boolean alert = true;

    private DatagramSocket socket;

    public ComServerThread() {

        try {

            socket = new DatagramSocket(5500);
        } catch (SocketException ex) {

            Log.e(LOG, "Error opening socket: " + ex.getMessage());
        }
    }

    @Override
    public void run() {

        while (!this.isInterrupted()) {

            try {

                try {

                    sleep(INTERVAL);
                } catch (InterruptedException ex) {

                    Log.e(LOG, "Interrupted the thread sleep! not cool: "
                            + ex.getMessage());
                }

                byte[] buffer;

                String msg = "Test"

                buffer = msg.getBytes();

                InetAddress group = InetAddress.getByName("230.0.0.1");

                DatagramPacket packet = new DatagramPacket(buffer,
                        buffer.length, group, 5500);
                socket.send(packet);

                Log.d(LOG, "Packet sent.");

            } catch (UnknownHostException ex) {

                Log.e(LOG, "Oops. Invalid host: " + ex.getMessage());
            } catch (IOException ex) {

                Log.e(LOG,
                        "Something bad happened while sending the packet. Take a look: "
                                + ex.getMessage());
            }
        }
    }
}

A: You are correct, it is a blocking method.
If you set a read timeout, it will throw a SocketTimeoutException, which you appear to be ignoring, so your code will just loop and block again.
You don't need to join the multicast group every time around the loop: that is just wasteful.


text:
Q: header inline with selectizeInput I would like to add selectizeInput() in one line with the header in my shiny app. Moreover I would like to align the header to the left and selectizeInput() to the right.
I tried this:
shinyUI(fluidPage(
  theme = shinytheme("simplex"),
  titlePanel(title = div(div(style = "display: inline-block; ",
                             "My shiny application"),
                         div(style = "width: 200px; display: inline-block;
                                      float: right; ",
                             selectInput(inputId = "opt",
                                         label = "",
                                         choices = c("opt1", "opt2", "opt3"),
                                         selected = "opt1")))),

  sidebarLayout(
    sidebarPanel(),
    mainPanel(),
    fluid = F)
))

But header and selectInput() are not on the same line. When I exclude float: right then they are, but they are not properly aligned.
Any suggestions are welcomed!

A: You can use something like this:
 shinyUI(fluidPage(
      theme = shinytheme("simplex"),
      tagList(div(div(style = "display: inline-block; ",
                                 h1("My shiny application"),class="main_title"),
                             div(style = "width: 200px; display: inline-block;
                                          float: right; ",
                                 selectInput(inputId = "opt",
                                             label = "",
                                             choices = c("opt1", "opt2", "opt3"),
                                             selected = "opt1")))),

      sidebarLayout(
        sidebarPanel(),
        mainPanel(),
        fluid = F)
    ))


text:
Q: How to assign a value from index[0] in first array to index[0] in second array? I need to assign a color to a person. I have two arrays: people and colors.
1.When I choose Adam, it should be pink, Estefania - yellow, Adrian -red, Wladimir - purple, Samantha - orange.
2.  In other words: index 0 from the array of people assign (connect) to the index 0 from the colors array,
index 1 from the people array assign(connect) with index 1 from the colors array,
index 2 from the people array assign(connect) to index 2 from the colors array; and so on
Example code: http://plnkr.co/edit/TPZjXkkSRrIc5ApzP07F?p=preview
index.html

  <meta charset="utf-8">
  <title>AngularJS ui-select</title>

  <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.css">

  <link rel="stylesheet" href="select.css">

  <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/select2/3.4.5/select2.css">
  <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.8.5/css/selectize.default.css">

Array of strings

  <button ng-click='clearTag()'>Delete</button>
  <ui-select tagging tagging-label="new tag" multiple ng-model="vm.multipleDemo"
  on-select="OnClickSelect($item)" on-remove="OnRemoveSelect($item)"
  theme="select2" ng-disabled="disabled" style="width: 300px;">
    <ui-select-match placeholder="Select name...">{{$item.name}}</ui-select-match>
    <ui-select-choices  repeat="item in people | filter:$select.search">
      {{item.name}}
    </ui-select-choices>
  </ui-select>

Selected: {{vm.multipleDemo}}

**demo.js**

'use strict';

var app = angular.module('demo', ['ngSanitize', 'ui.select']);

app.controller('DemoCtrl', function($scope, $http, $timeout) {
  $scope.vm = {multipleDemo: []};
    $scope.people = [
    { name: 'Adam',      email: 'adam@email.com',      age: 12, country: 'United States' },
    { name: 'Amalie',    email: 'amalie@email.com',    age: 12, country: 'Argentina' },
    { name: 'Estefanía', email: 'estefania@email.com', age: 21, country: 'Argentina' },
    { name: 'Adrian',    email: 'adrian@email.com',    age: 21, country: 'Ecuador' },
    { name: 'Wladimir',  email: 'wladimir@email.com',  age: 30, country: 'Ecuador' },
    { name: 'Samantha',  email: 'samantha@email.com',  age: 30, country: 'United States' },
    { name: 'Nicole',    email: 'nicole@email.com',    age: 43, country: 'Colombia' }

  ];

  $scope.colors = [
   'pink', 'yellow', 'red', 'purple', 'orange', 'green'
  ];

  $scope.OnClickSelect=function(item)
  {
   $scope.vm.multipleDemo.push(item.name);
  }

  $scope.OnRemoveSelect = function(item) {
    window.console.log($scope.people);
   var index = $scope.people.indexOf(item.name);
   $scope.people.splice(index, 1);
  }

  $scope.clearTag = function() {
    /*for(var i =0; i < $scope.vm.multipleDemo.length; i++) {
      $scope.vm.multipleDemo.splice($scope.vm.multipleDemo[i]);
      $scope.people.push($scope.vm.multipleDemo[i]);
    }*/
    var i =0;
    while(i < $scope.vm.multipleDemo.length) {
      i++;
      $scope.vm.multipleDemo.splice($scope.vm.multipleDemo[i]);
      $scope.people.push($scope.vm.multipleDemo[i]);
    }
  }
});```

A: You can use javascript .map function to map the array based on index. We can use the person object and assign color property to it and return it as a new Object for each item in People array. The result is assigned back to People.

let people = [
    { name: 'Adam',      email: 'adam@email.com',      age: 12, country: 'United States' },
    { name: 'Amalie',    email: 'amalie@email.com',    age: 12, country: 'Argentina' },
    { name: 'Estefanía', email: 'estefania@email.com', age: 21, country: 'Argentina' },
    { name: 'Adrian',    email: 'adrian@email.com',    age: 21, country: 'Ecuador' },
    { name: 'Wladimir',  email: 'wladimir@email.com',  age: 30, country: 'Ecuador' },
    { name: 'Samantha',  email: 'samantha@email.com',  age: 30, country: 'United States' },
    { name: 'Nicole',    email: 'nicole@email.com',    age: 43, country: 'Colombia' }

  ];

 const colors = [
   'pink', 'yellow', 'red', 'purple', 'orange', 'green'
  ];

  people= people.map((person, index) =>
    ({ ...person,
      color: colors[index]
    }))

    console.log(people);

A: I'm not sure about the Angular way of writing the code but I would use either Array.forEach or Array.map.  Here is how I would do it with vanilla js
For Each:
people.forEach((person, index) => {
    person.color = colors[index];
}

Map:
people = people.map((person, index) => {
    person.color = colors[index];
    return person;
}


text:
Q: change xcrun developer path for Android Studio/IntelliJ I'm using GIT and am trying to push my code and getting the following error when using the Terminal. I don't use XCode, I'm using Android Studio.
The command I tried using was:

git branch Networking

Error:

xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun`

I am running on El Capitan Beta 4 update if that helps in any way.

Update: This also happens for IntelliJ users, and for MacOS
  Catalina update

A: Instead of installing xcode you can install git from here and change the path in android studio to /usr/local/git/bin/git as shown in the image below.

This way you save time and memory.

A: Use /usr/local/git/bin/git as a path

A: I ran into the same problem, however with svn.  I found that by installing El Capitan, Xcode was "uninstalled".  I reinstalled Xcode from the App Store and then reinstalled Xcode Command Line Tools via Terminal with
xcode-select --install

After installation, my /Library/Developer/CommandLineTools/usr/bin directory reappeared and svn started working again.

A: In my case, Git did not work after upgrading Mac OS X High Sierra.
Fortunately, the answer provided by @Rob still works for High Sierra, so there was no need for me to actually change the xcrun developer path and no need to install all of XCode

A: I lost Git after upgrading to macOS Mojave.
The solution of re-installing XCode CLI still works fine.
In Terminal, type:
xcode-select --install

... and click "Install" on the prompt.


text:
Q: How do I get real-time position of finger as it moves from left to right? I'm really struggling on an Android app in Phonegap and JQuery.
All I want to do is, as I drag my finger from left to right, I want to be able to output to screen exactly what my x position is.
I can't use touchmove as that simply gives me the coordinates at the end of the movement, I need the real-time coordinates?
Are there any JQuery plugins I could use?
Does anyone have any ideas?

A: This ought to work:
text = document.getElementById('element to hold text'); // element that can write the x position

document.getElementById('element').ontouchmove = function (e)
{e.preventDefault();
e.stopPropagation();
text.innerHTML = e.touches[0].clientX; //set the inner html of the text element to be the x position of the touch
};

A: First you say appp then you say jquery ??
How is that possible ??
Anyways in case of app you can use
OnTouchListener

And for web you can use

MouseMove event (or)
click Event

All three methods would have postion as params


text:
Q: This site can't be reached - django setup I'm starting working with django and try to setup new project and after the command "py manage.py runserver"
Everything working and I get this address http://127.0.0.1:8000/
and when I try to enter this address I get that message " This site can't be reached127.0.0.1 refused to connect".
What I need to fix ?
Thanks

A: I think you're missing port 8000 in your url
"This site can't be reached127.0.0.1 refused to connect".
Check again, if it still doesn't works try using, python manage.py runserver 8000
You can refer here too change port for development server


text:
Q: How to deal with the error when using Gurobi with cvxpy :Unable to retrieve attribute 'BarIterCount' How to deal with the error when using Gurobi with cvxpy :AttributeError: Unable to retrieve attribute 'BarIterCount'.
I have an Integer programming problem, using cvxpy and set gurobi as a solver.
When the number of variables is small, the result is ok. After the number of variables reaches a level of like 43*13*6, then the error occurred.  I suppose it may be caused by the scale of the problem, in which the gurobi solver can not estimate the BarIterCount, which is the max Iterations needed.
Thus, I wonder, is there any way to manually set the BarItercount attribute of gurobi through the interface of the CVX? Or whether there exists another way to solve this problem?
Thanks for any suggestions you may provide for me.
The trace log is as follows:
If my model is small, like I set a number which indicates the scale of model as 3, then the program is ok. The trace is :
Using license file D:\software\lib\site-packages\gurobipy\gurobi.lic
Restricted license - for non-production use only - expires 2022-01-13
Parameter OutputFlag unchanged
   Value: 1  Min: 0  Max: 1  Default: 1
D:\software\lib\site-packages\cvxpy\reductions\solvers\solving_chain.py:326: DeprecationWarning: Deprecated, use Model.addMConstr() instead
  solver_opts, problem._solver_cache)
Changed value of parameter QCPDual to 1
   Prev: 0  Min: 0  Max: 1  Default: 0
Gurobi Optimizer version 9.1.0 build v9.1.0rc0 (win64)
Thread count: 16 physical cores, 32 logical processors, using up to 32 threads
Optimize a model with 126 rows, 370 columns and 2689 nonzeros
Model fingerprint: 0x70d49530
Variable types: 0 continuous, 370 integer (369 binary)
Coefficient statistics:
  Matrix range     [1e+00, 7e+00]
  Objective range  [1e+00, 1e+00]
  Bounds range     [1e+00, 1e+00]
  RHS range        [1e+00, 6e+00]
Found heuristic solution: objective 7.0000000
Presolve removed 4 rows and 90 columns
Presolve time: 0.01s
Presolved: 122 rows, 280 columns, 1882 nonzeros
Variable types: 0 continuous, 280 integer (279 binary)

Root relaxation: objective 4.307692e+00, 216 iterations, 0.00 seconds

    Nodes    |    Current Node    |     Objective Bounds      |     Work
 Expl Unexpl |  Obj  Depth IntInf | Incumbent    BestBd   Gap | It/Node Time

     0     0    4.30769    0   49    7.00000    4.30769  38.5%     -    0s
H    0     0                       6.0000000    4.30769  28.2%     -    0s
     0     0    5.00000    0   35    6.00000    5.00000  16.7%     -    0s
     0     0    5.00000    0   37    6.00000    5.00000  16.7%     -    0s
     0     0    5.00000    0    7    6.00000    5.00000  16.7%     -    0s

Cutting planes:
  Gomory: 4
  Cover: 9
  MIR: 4
  StrongCG: 1
  GUB cover: 9
  Zero half: 1
  RLT: 1

Explored 1 nodes (849 simplex iterations) in 0.12 seconds
Thread count was 32 (of 32 available processors)

Solution count 2: 6 7

Optimal solution found (tolerance 1.00e-04)
Best objective 6.000000000000e+00, best bound 6.000000000000e+00, gap 0.0000%

If the number is 6, then error occurs:
-------------------------------------------------------
Using license file D:\software\lib\site-packages\gurobipy\gurobi.lic
Restricted license - for non-production use only - expires 2022-01-13
Parameter OutputFlag unchanged
   Value: 1  Min: 0  Max: 1  Default: 1
D:\software\lib\site-packages\cvxpy\reductions\solvers\solving_chain.py:326: DeprecationWarning: Deprecated, use Model.addMConstr() instead
  solver_opts, problem._solver_cache)
Changed value of parameter QCPDual to 1
   Prev: 0  Min: 0  Max: 1  Default: 0
Gurobi Optimizer version 9.1.0 build v9.1.0rc0 (win64)
Thread count: 16 physical cores, 32 logical processors, using up to 32 threads
Traceback (most recent call last):
  File "model.py", line 274, in <module>
    problem.solve(solver=cp.GUROBI,verbose=True)
  File "D:\software\lib\site-packages\cvxpy\problems\problem.py", line 396, in solve
    return solve_func(self, *args, **kwargs)
  File "D:\software\lib\site-packages\cvxpy\problems\problem.py", line 754, in _solve
    self.unpack_results(solution, solving_chain, inverse_data)
  File "D:\software\lib\site-packages\cvxpy\problems\problem.py", line 1058, in unpack_results
    solution = chain.invert(solution, inverse_data)
  File "D:\software\lib\site-packages\cvxpy\reductions\chain.py", line 79, in invert
    solution = r.invert(solution, inv)
  File "D:\software\lib\site-packages\cvxpy\reductions\solvers\qp_solvers\gurobi_qpif.py", line 59, in invert
    s.NUM_ITERS:  model.BarIterCount,
  File "src\gurobipy\model.pxi", line 343, in gurobipy.gurobipy.Model.__getattr__
  File "src\gurobipy\model.pxi", line 1842, in gurobipy.gurobipy.Model.getAttr
  File "src\gurobipy\attrutil.pxi", line 100, in gurobipy.gurobipy.__getattr
AttributeError: Unable to retrieve attribute 'BarIterCount'

Hopefully this can provide more hint for solution.

A: BarIterCount is the number of barrier iterations performed to solve an LP. This is not a limit on the number of iterations and it should only be queried when the current optimization process has been finished. You cannot set this attribute either, of course.
To actually limit the number of iterations the barrier algorithm is allowed to take, you can use the parameter BarIterLimit.
Please inspect your log file for further information about the solver's behavior.


text:
Q: Existence of $V \subset \mathbb{R}^n : V, V^\perp \cap \mathbb{R}_{\geq0}^n = 0$ Is there a subspace $V \subset \mathbb{R}^n$ with $V \cap \mathbb{R}_{\geq0}^n = V^\perp \cap \mathbb{R}_{\geq0}^n = 0$?
My geometric intuition tells me that there is no such $V$ but i'am completely stuck on proof.

A: Suppose $V\cap \mathbb{R}^n_{\geq 0} = \{0\}$, and let $P$ denote orthogonal projection onto $V$.  A vector $w$ is in $V^\perp$ iff $P(w)=0$.
Let $H$ be the convex hull of $\{e_1,e_2,\dots,e_n\}$, where $e_i$ is a standard basis vector.  Note that $H\subset \mathbb{R}^n_{\geq 0}$.  The projection $P(H)$ is a convex subset of $V$.  For it to not contain $0$, there must be a hyperplane separating $0$ and $P(H)$, which means there exists some non-zero $v\in V$ such that $\forall(w\in P(H))\: w\cdot v > 0$.
But the condition that $V\cap \mathbb{R}^n_{\geq 0} = 0 $ means that for any non-zero $v\in V$ the components of $v$ cannot all be non-negative (nor all non-positive, else $-v\in\mathbb{R}^n_{\geq 0}$).  Hence for any $v\in V$ there is some $e_i$ such that $v\cdot e_i < 0$.  Thus $v\cdot P(e_i) = v\cdot e_i < 0$, and since $P(e_i)\in P(H)$, so there cannot be a hyperplane separating $0$ and $P(H)$.
Hence $0\in P(H)$, and thus $H\subset \mathbb{R}^n_{\geq}$ intersects $V^\perp$.

A: $\newcommand{\IR}{\mathbb{R}}$
Note that $C:=\IR_{\geq 0}^n$ is a cone, i.e. a subset that is closed under addition and multiplication with $\IR_{\geq 0}$. Following Paul Garrett's advice, we look at the dual cone, i.e. $C^\vee := \{v \mid \forall x\in C: \langle v,x\rangle \geq 0\}$. One can easily verify that $V^\vee = V^\perp$ for subspaces $V\leq\IR^n$ and $(\IR_{\geq 0}^n)^\vee = \IR_{\geq 0}^n$.
Now look at any basis $w_1,\ldots,w_k$ of $V^\perp$ and look at the linear map $\omega: \IR^n\to\IR^k, x\mapsto (\langle w_1,x\rangle, ..., \langle w_k,x\rangle)$. By assumption $\ker(\omega)=V$ so that $\omega(\IR_{\geq0}^n\setminus\{0\}) \subseteq \IR^k\setminus\{0\}$. This is now a cone in $\IR^k$ and by choosing a different basis of $\IR^k$ (or equivalently: choosing a different basis of $V^\perp$), we can assume that $\omega(\IR_{\geq0}^n) \subseteq \IR_{\geq0}^k$. But that means that $\langle w_i,x\rangle \geq 0$ for all $x\in C$, i.e. $w_i\in (\IR_{\geq 0}^n)^\vee = \IR_{\geq 0}^n$.
We have shown: If $V\cap\IR_{\geq 0}^n=0$, then $V^\perp\cap\IR_{\geq 0}^n$ contains a whole basis of $V^\perp$.

A: If $V$ has dimension strictly less than $n-1$ and it intersect trivially $\mathbb{R}^n_{n\ge0}$, it is easy to see that we can enlarge it keeping trivial the intersection with $\mathbb{R}^n_{n\ge0}$, hence it is enough to do the case in which $V$ has dimension $n-1$ and its orthogonal is a line $L$.
Now, if $L$ is not contained in $\mathbb{R}^n_{n\ge0}\cup\mathbb{R}^n_{n\le0}$, its points have two coordinates with opposite sign. But then it is easy to find a vector $v\in\mathbb{R}^n_{n\ge 0}$ orthogonal to $L$.


text:
Q: In Firebase Realtime Database, is there an advantage to attaching a .childChanged listener at main node instead of many observers to the children? I have a Realtime Database for a card game between players. Sometimes I am seeing logs of clients with disconnected sockets (monitoring with onDisconnect action), and players cannot continue game. My main structure is a game key register with about 14 observers attached to individual children listening for changes/register deletes/register additions.
My next steps I'm looking at to help are:

*

*One observer on game register that listens for child changed, verses having individual children observed.

*Using .keepsynced() on observers

*Enabling disc persistence

*Calling firebase function .goOnline() when client sees it's socket disconnect.
Any advice is appreciated :)
Many thanks!

A: If you register any child_* listener on a parent node, the SDK synchronizes all nodes under that location/query. So if you have many child nodes under a path and only need to monitor a few of them for changes, it may be more efficient bandwidth-wise to monitor the individual child nodes with a value listener on each.


text:
Q: Multiple Instances of the same Fragment in a FragmentStatePagerAdapter I have a FragmentStatePagerAdapter which displays different instances of the same fragment but having different data, as shown:
class MyAdapter extends FragmentStatePagerAdpater{

    public MyAdapter (FragmentManager fm){
        super(fm);
    }

    public Fragment getItem(int i){
        Frag f = new Frag();
        f.setState(i);   //sets the value of the "State" instance variable
                         //of the fragment
        return f;
    }

    public int getCount(){
    return 100;
    }
}

Now, my question is that as the FragmentStatePagerAdapter saves the state of a fragment instance before it destroys them, and as the different instances may have different data saved in the onSaveInstanceState, then how does the FragmentStatePagerAdapter decide which savedInstanceState to be restored on re-creation of the Fragment instances when they need to be re-displayed?

A: If you look at the source code to FragmentStatePagerAdapter, it looks like the state is saved and restored based on position.


text:
Q: async await with setInterval function first(){
  console.log('first')
}
function second(){
  console.log('second')
}
let interval = async ()=>{
  await setInterval(first,2000)
  await setInterval(second,2000)
}
interval();

Imagine that I have this code above.
When I run it, first() and second() will be called at the same time; how do I call second() after first)() returns some data, for example, if first() is done, only then call second()?
Because first() in my code will be working with a big amount of data and if this 2 functions will be calling at the same time, it will be hard for the server.
How do I call second() each time when first() will return some data?

A: As mentioned above setInterval does not play well with promises if you do not stop it. In case you clear the interval you can use it like:
async function waitUntil(condition) {
  return await new Promise(resolve => {
    const interval = setInterval(() => {
      if (condition) {
        resolve('foo');
        clearInterval(interval);
      };
    }, 1000);
  });
}

Later you can use it like
const bar = waitUntil(someConditionHere)

A: setInterval doesn't play well with promises because it triggers a callback multiple times, while promise resolves once.
It seems that it's setTimeout that fits the case. It should be promisified in order to be used with async..await:
async () => {
  await new Promise(resolve => setTimeout(() => resolve(first()), 2000));
  await new Promise(resolve => setTimeout(() => resolve(second()), 2000));
}

A: You have a few problems:

*

*Promises may only ever resolve once, setInterval() is meant to call the callback multiple times, Promises do not support this case well.

*Neither setInterval(), nor the more appropriate setTimeout() return Promises, therefore, awaiting on them is pointless in this context.

You're looking for a function that returns a Promise which resolves after some times (using setTimeout(), probably, not setInterval()).
Luckily, creating such a function is rather trivial:
async function delay(ms) {
  // return await for better async stack trace support in case of errors.
  return await new Promise(resolve => setTimeout(resolve, ms));
}

With this new delay function, you can implement your desired flow:
function first(){
  console.log('first')
}
function second(){
  console.log('second')
}
let run = async ()=>{
  await delay(2000);
  first();
  await delay(2000)
  second();
}
run();

A: await expression causes async to pause until a Promise is settled
so you can directly get the promise's result without await
for me, I want to initiate Http request every 1s

let intervalid
async function testFunction() {
    intervalid = setInterval(() => {
        // I use axios like: axios.get('/user?ID=12345').then
        new Promise(function(resolve, reject){
            resolve('something')
        }).then(res => {
            if (condition) {
               // do something
            } else {
               clearInterval(intervalid)
            }
        })
    }, 1000)
}
// you can use this function like
testFunction()
// or stop the setInterval in any place by
clearInterval(intervalid)

A: You could use an IFFE. This way you could escape the issue of myInterval not accepting Promise as a return type.
There are cases where you need setInterval, because you want to call some function unknown amount of times with some interval in between.
When I faced this problem this turned out to be the most straight-forward solution for me. I hope it help someone :)
For me the use case was that I wanted to send logs to CloudWatch but try not to face the Throttle exception for sending more than 5 logs per second. So I needed to keep my logs and send them as a batch in an interval of 1 second. The solution I'm posting here is what I ended up using.
  async function myAsyncFunc(): Promise<string> {
    return new Promise<string>((resolve) => {
      resolve("hello world");
    });
  }

  function myInterval(): void {
    setInterval(() => {
      void (async () => {
        await myAsyncFunc();
      })();
    }, 5_000);
  }

  // then call like so
  myInterval();

A: Looked through all the answers but still didn't find the correct one that would work exactly how the OP is asked. This is what I used for the same purpose:

async function waitInterval(callback, ms) {
    return new Promise(resolve => {
        let iteration = 0;
        const interval = setInterval(async () => {
            if (await callback(iteration, interval)) {
                resolve();
                clearInterval(interval);
            }
            iteration++;
        }, ms);
    });
}

function first(i) {
    console.log(`first: ${i}`);
    // If the condition below is true the timer finishes
    return i === 5;
}

function second(i) {
    console.log(`second: ${i}`);
    // If the condition below is true the timer finishes
    return i === 5;
}

(async () => {
    console.log('start');
    await waitInterval(first, 1000);
    await waitInterval(second, 1000);
    console.log('finish');
})()

In my example, I also put interval iteration count and the timer itself, just in case the caller would need to do something with it. However, it's not necessary

A: In my case, I needed to iterate through a list of images, pausing in between each, and then a longer pause at the end before re-looping through.
I accomplished this by combining several techniques from above, calling my function recursively and awaiting a timeout.
If at any point another trigger changes my animationPaused:boolean, my recursive function will exit.
    const loopThroughImages = async() => {
      for (let i=0; i<numberOfImages; i++){
        if (animationPaused) {
          return;
        }
        this.updateImage(i);
        await timeout(700);
      }
      await timeout(1000);
      loopThroughImages();
    }

    loopThroughImages();

A: Async/await do not make the promises synchronous.
To my knowledge, it's just a different syntax for return Promise and .then().
Here i rewrote the async function and left both versions, so you can see what it really does and compare.
It's in fact a cascade of Promises.

// by the way no need for async there. the callback does not return a promise, so no need for await.
function waitInterval(callback, ms) {
    return new Promise(resolve => {
        let iteration = 0;
        const interval = setInterval(async () => {
            if (callback(iteration, interval)) {
                resolve();
                clearInterval(interval);
            }
            iteration++;
        }, ms);
    });
}

function first(i) {
    console.log(`first: ${i}`);
    // If the condition below is true the timer finishes
    return i === 5;
}

function second(i) {
    console.log(`second: ${i}`);
    // If the condition below is true the timer finishes
    return i === 5;
}

// async function with async/await, this code ...
(async () => {
    console.log('start');
    await waitInterval(first, 1000);
    await waitInterval(second, 1000);
    console.log('finish');
})() //... returns a pending Promise and ...
console.log('i do not wait');

// ... is kinda identical to this code.
// still asynchronous but return Promise statements with then cascade.
(() => {
    console.log('start again');
    return waitInterval(first, 1000).then(() => {
        return waitInterval(second, 1000).then(() => {
                console.log('finish again');
        });
    });
})(); // returns a pending Promise...
console.log('i do not wait either');

You can see the two async functions both execute at the same time.
So using promises around intervals here is not very useful, as it's still just intervals, and promises changes nothing, and make things confusing...
As the code is calling callbacks repeatedly into an interval, this is, i think, a cleaner way:

function first(i) {
    console.log(`first: ${i}`);
    // If the condition below is true the timer finishes
    return i === 5;
}

function second(i) {
    console.log(`second: ${i}`);
    // If the condition below is true the timer finishes
    return i === 5;
}

function executeThroughTime(...callbacks){
    console.log('start');
    let callbackIndex = 0; // to track current callback.
    let timerIndex = 0; // index given to callbacks
    let interval = setInterval(() =>{
        if (callbacks[callbackIndex](timerIndex++)){ // callback return true when it finishes.
            timerIndex = 0; // resets for next callback
            if (++callbackIndex>=callbacks.length){ // if no next callback finish.
                clearInterval(interval);
                console.log('finish');
            }
        }
    },1000)
}

executeThroughTime(first,second);
console.log('and i still do not wait ;)');

Also, this solution execute a callback every secondes.
if the callbacks are async requests that takes more than one sec to resolve, and i can't afford for them to overlap, then, instead of doing iterative call with repetitive interval, i would get the request resolution to call the next request (through a timer if i don't want to harass the server).
Here the "recursive" task is called lTask, does pretty much the same as before, except that, as i do not have an interval anymore, i need a new timer each iteration.

// slow internet request simulation. with a Promise, could be a callback.
function simulateAsync1(i) {
    console.log(`first pending: ${i}`);
    return new Promise((resolve) =>{
        setTimeout(() => resolve('got that first big data'), Math.floor(Math.random()*1000)+ 1000);//simulate request that last between 1 and 2 sec.
    }).then((result) =>{
        console.log(`first solved: ${i} ->`, result);
        return i==2;
    });
}
// slow internet request simulation. with a Promise, could be a callback.
function simulateAsync2(i) {
    console.log(`second pending: ${i}`);
    return new Promise((resolve) =>{
        setTimeout(() => resolve('got that second big data'), Math.floor(Math.random()*1000) + 1000);//simulate request that last between 1 and 2 sec.
    }).then((result) =>{ // promise is resolved
        console.log(`second solved: ${i} ->`,result);
        return i==4; // return a promise
    });
}

function executeThroughTime(...asyncCallbacks){
    console.log('start');
    let callbackIndex = 0;
    let timerIndex = 0;
    let lPreviousTime = Date.now();
    let lTask = () => { // timeout callback.
        asyncCallbacks[callbackIndex](timerIndex++).then((result) => { // the setTimeout for the next task is set when the promise is solved.
            console.log('result',result)
            if (result) { // current callback is done.
                timerIndex = 0;
                if (++callbackIndex>=asyncCallbacks.length){//are all callbacks done ?
                    console.log('finish');
                    return;// its over
                }
            }
            console.log('time elapsed since previous call',Date.now() - lPreviousTime);
            lPreviousTime = Date.now();
            //console.log('"wait" 1 sec (but not realy)');
            setTimeout(lTask,1000);//redo task after 1 sec.
            //console.log('i do not wait');
        });
    }
    lTask();// no need to set a timer for first call.
}

executeThroughTime(simulateAsync1,simulateAsync2);
console.log('i do not wait');

Next step would be to empty a fifo with the interval, and fill it with web request promises...


text:
Q: "no A and B" or "no A and no B" or "no A or B" or "no A or no B"? If I mean "it does not contain A or B", which one of the following is correct?

*

*It contains no A and B.

*It contains no A and no B.

*It contains no A or B.

*It contains no A or no B.

I think 2 is correct, but I am not sure about others.

A: 'It contains neither A nor B' is how you can express this correctly in English.
'Either / or' and 'neither / nor' are matching pairs.
https://thewritepractice.com/how-to-use-either-neither-or-and-nor-correctly/

A: What is the problem of using "It does not contain A or B"?
You can add "any" for emphasis.
If you mean "both A and B" altogether simply say "It doesn't contain both A and B".


text:
Q: how do I clearInterval on-click, with React Hooks? I'm trying to refactor my code to react hooks, but I'm not sure if i'm doing it correctly.  I tried copying and pasting my setInterval/setTimout code into hooks, but it did not work as intended.  After trying different things I was able to get it to work, but I'm not sure if this is the best way to do it.
I know i can use useEffect to clear interval on un-mount, but I want to clear it before un-mounting.
Is the following good practice and if not what is a better way of clearing setInterval/setTimout  before un-mounting?
Thanks,
useTimeout
import { useState, useEffect } from 'react';

let timer = null;

const useTimeout = () => {
    const [count, setCount] = useState(0);
    const [timerOn, setTimerOn] = useState(false);

    useEffect(() => {
        if (timerOn) {
            console.log("timerOn ", timerOn);

            timer = setInterval(() => {
                setCount((prev) => prev + 1)
            }, 1000);

        } else {
            console.log("timerOn ", timerOn);
            clearInterval(timer);
            setCount(0);
        }
    return () => {
        clearInterval(timer);
    }
    }, [timerOn])

    return [count, setCount, setTimerOn];
}

export default useTimeout;

Component
import React from 'react';
import useTimeout from './useTimeout';

const UseStateExample = () => {
    const [count, setCount, setTimerOn] = useTimeout()
    return (

Notes:

New function are created on each render

count = {count}

            <button onClick={() => setCount(prev => prev + 1)}>Increment</button>

            <button onClick={() => setCount(prev => prev - 1)}>Decrement</button>

            <button onClick={() => setTimerOn(true)}>Set Interval</button>

            <button onClick={() => setTimerOn(false)}>Stop Interval</button>

    );
}

export default UseStateExample;

A: In this example, we add a couple of things...

*

*A on/off switch for the timeout (the 'running' arg) which will completely switch it on or off

*A reset function, allowing us to set the timeout back to 0 at any time:
If called while it's running, it'll keep running but return to 0.
If called while it's not running, it'll start it.

const useTimeout = (callback, delay, running = true) => {
  // save id in a ref so we make sure we're always clearing the latest timeout
  const timeoutId = useRef('');

  // save callback as a ref so we can update the timeout callback without resetting it
  const savedCallback = useRef();
  useEffect(
    () => {
      savedCallback.current = callback;
    },
    [callback],
  );

  // clear the timeout and start a new one, updating the timeoutId ref
  const reset = useCallback(
    () => {
      clearTimeout(timeoutId.current);

      const id = setTimeout(savedCallback.current, delay);
      timeoutId.current = id;
    },
    [delay],
  );

  // keep the timeout dynamic by resetting it whenever its' deps change
  useEffect(
    () => {
      if (running && delay !== null) {
        reset();

        return () => clearTimeout(timeoutId.current);
      }
    },
    [delay, running, reset],
  );

  return { reset };
};

So in your example above, we could use it like so...

const UseStateExample = ({delay}) => {
    // count logic
    const initCount = 0
    const [count, setCount] = useState(initCount)

    const incrementCount = () => setCount(prev => prev + 1)
    const decrementCount = () => setCount(prev => prev - 1)
    const resetCount = () => setCount(initCount)

    // timer logic
    const [timerOn, setTimerOn] = useState(false)
    const {reset} = useTimeout(incrementCount, delay, timerOn)

    const startTimer = () => setTimerOn(true)
    const stopTimer = () => setTimerOn(false)

    return (

Notes:

New function are created on each render

count = {count}

            <button onClick={incrementCount}>Increment</button>

            <button onClick={decrementCount}>Decrement</button>

            <button onClick={startTimer}>Set Interval</button>

            <button onClick={stopTimer}>Stop Interval</button>

            <button onClick={reset}>Start Interval Again</button>

    );
}

A: --- added @ 2019-02-11 15:58 ---
A good pattern to use setInterval with Hooks API:
https://overreacted.io/making-setinterval-declarative-with-react-hooks/

--- origin answer ---
Some issues:

*

*Do not use non-constant variables in the global scope of any modules. If you use two instances of this module in one page, they'll share those global variables.

*There's no need to clear timer in the "else" branch because if the timerOn change from true to false, the return function will be executed.
A better way in my thoughts:
import { useState, useEffect } from 'react';

export default (handler, interval) => {
  const [intervalId, setIntervalId] = useState();
  useEffect(() => {
    const id = setInterval(handler, interval);
    setIntervalId(id);
    return () => clearInterval(id);
  }, []);
  return () => clearInterval(intervalId);
};

Running example here:
https://codesandbox.io/embed/52o442wq8l?codemirror=1

A: Demo of clear many timers.
You should declare and clear timer.current instead of timer.

*

*Declare s and timer.

const [s, setS] = useState(0);
let timer = useRef<NodeJS.Timer>();

*Initialize timer in useEffect(() => {}).

useEffect(() => {
  if (s == props.time) {
    clearInterval(timer.current);
  }
  return () => {};
}, [s]);

*Clear timer.

useEffect(() => {
  if (s == props.time) {
    clearInterval(timer.current);
  }
  return () => {};
}, [s]);

A: After many attempts to make a timer work with setInterval, I decided to use setTimeOut, I hope it works for you.
  const [count, setCount] = useState(60);

  useEffect(() => {
    if (count > 0) {
      setTimeout(() => {
        setCount(count - 1);
      }, 1000);
    }
  }, [count]);


text:
Q: Should the Kaplan-Meier p-value be adjusted if new data are added? The event of interest is subscription purchase and the time variable is days since the creation of the subscription trial within an AB Test. The stakeholders want to monitor the progress each day as both new customers are added and subscription purchases are made.
I feel that presenting the survival curves is fine with updating data, however, should there be some kind of correction for the p-value due to the multiple testing?
Or should the p-value be calculated as standard and compared to a fixed alpha determined a priori?
If the latter how would I adjust alpha appropriately?


text:
Q: Container "pushed down" in IE7+ I am putting the finishing touches on http://eidman.krd-design.net/.  When I tested out the site on IE8, the main container is dropping below the navigation sidebar.  Elements of the navigation are also stacking on top of each other.  Has anyone run into these issues before and if so what is the fix?
Thank you for any and all help, I greatly appreciate it!

A: Check your markup using http://validator.w3.org/check you have a TON of errors such as stray </li> and </div> tags, white space between in a h ref and duplicate closing anchor tags </a></a>


text:
Q: Use Ajax handler with a form submitted by checkbox 'onchanged' event I'm trying to convert a form submission to jQuery's Ajax. The page holds a product filter (by Price,type) and product names - each row has a form with a checkbox where the onchanged property is submitting the form:
 <input type="checkbox" value="" name="pfilter" onchange="this.form.submit();"/>

Can anybody let me know, how to achieve this by ajax.
I tried below code
 $("form").live('submit', function (event) {
        event.preventDefault();
        var form = $(this);
        $.ajax({
            url: form.attr('action'),
            type: "POST",
            data: form.serialize(),
            success: function (data) {
                $("#myContainer").html(data);
            },
        });
    });

But products are not getting filtered.

A: <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<form id="form" action="page.php">
    <input type="checkbox" value="" name="pfilter" onchange="$('#form').submit();"/>
</form>
<script>
    $("#form").on('submit', function (event) {
        event.preventDefault();
        var form = $(this);
        $.ajax({
            url: form.attr('action'),
            type: 'POST',
            data: form.serialize(),
            success: function (data) {
                $("#myContainer").html(data);
            },
        });
    });
</script>


text:
Q: Firebase @Exclude annotation for both Firestore and Realtime Database? I have some marked fields with the @Exclude annotation, in order to keep them away from the database:
@IgnoreExtraProperties
public class Model {
    @Exclude private String id;
}

My problem is that this annotation is valid for only one database at a time.
I can improt this interface from the Firestore library like this:
import com.google.firebase.firestore.Exclude;

and I can import it from the Firebase Database library:
import com.google.firebase.database.Exclude;

The fact that I can't import both of them at the same time is a problem for me because I'd like to have the same object with the same excluded fields from both of the databases.
Is it possible to exclude fields in an object from both of the databases?

A: Any time you need to use two Java classes in the same source file, you need to refer to one or both of them by their fully qualified name.  For example:
@Exclude  // from Firestore
@com.google.firebase.database.Exclude  // from Realtime Database
int thing;


text:
Q: Add a constraint to a gobbing route parameter I have the following route:
get lib/2/subscriber:*params, to: 'lib2#subscriber_req'

I want a constraint that this route would match only if params is /\d+\//. I want it to match
lib/2/subscriber:1256/bla/blabla

but not
lib/2/subscriber:some_text1256/bla/blabla

I read this document. I wrote this route:
get lib/2/subscriber:*params, to: 'lib2#subscriber_req', , constraints:{params: /\d+\//}

But it doesn't work.
In general I don't know how to handle the GLOBS constraints. Some links would very helpful.

A: I don't get why you thought that /\d+\// would differentiate between:

*

*lib/2/subscriber:1256/bla/blabla

*lib/2/subscriber:some_text1256/bla/blabla
They both match that regex. If you want to match the params part of the first URL but not that of the second one, then perhaps this would work:
/\A\d+\//


text:
Q: Virtual Server or Not? I have been in an argument with a very stubborn guy for a long time about whether his server is virtual or dedicated. He uses his Root server for gameservers, the servers have problems with lag.
I tell him that this is because the server is operating on virtual CPUs, but he just won't listen.
As I understand it, the server is virtual, and the 'Root' part refers to the use of hosting various websites on it, hence the word 'root'.
Is this server a dedicated server or a virtual server?
http://www.hetzner.de/hosting/produktmatrix/rootserver-produktmatrix-ex

A: Judging by the link you posted it is a dedicated server (hardware). The most tell-tale sign is that it supports Intel's VT extensions, which is a hardware extension to optimize virtualization. These extensions cannot be virtualized into a guest container/OS.
Also the fact that you can get optional extra's like RAID controllers and disks indicate that he is renting dedicated hardware.

A: The menu shows it is the EX range is dedicated

There own website's meta data also shows this:

meta name="description" content="Unbeatable Web Hosting Offers: Whether Web space, dedicated root server, managed server, vServer or colocation server."

Here, they class a vServer as a different thing meaning it's most likely dedicated.
The feature list http://www.hetzner.de/en/hosting/produkte_rootserver/ex40 also suggests dedicated.
Also, reading about http://www.intel.com/content/www/us/en/virtualization/virtualization-technology/hardware-assist-virtualization-technology.html shows it's most likely dedicated as well...
And lastly, the price suggests it's dedicated.

A: The page does not make any mention of virtual machine specifications such as vCPUs or partitioned disk space, and in addition it offers "Wake on LAN" which is a function of a physical server, not a virtual server.  I would say it's a physical machine.