问:
Inserting several "new" items into the database with DBIC
I'm working in a bioinformatics project that requires me to read genomic data (nothing too fancy, just think of it as strings) from various organisms and insert it into a database. Each read belongs to one organism, and can contain from 5000 to 50000 thousand genes, which I need to process and analyze prior to storage.

The script currently doing this is written in perl and, after all calculations, stores the results in a hash likie this:

```<code>$new{$id}{gene_name}              = $id;
$new{$id}{gene_database_source} = $gene_database_source
$new{$id}{product}            = $product;
$new{$id}{sequence}               = $sequence;
$new{$id}{seqlength}              = $seqlength;
$new{$id}{digest}             = $digest;
$new{$id}{mw}                     = $mw;
$new{$id}{iep}                = $iep;
$new{$id}{tms}                = $tms;
</code>```

After all genes are read and, the insertions are made looping through the hash into an eval{} statement.

```<code>eval {
foreach my $id (keys %new) {

  my $rs = $schema->resultset('Genes')->create(
    {
        gene_name               => $new{$id}{gene_name},
        gene_product            => $new{$id}{product},
        sequence                => $new{$id}{sequence},
        gene_protein_length     => $new{$id}{seqlength},
        digest                  => $new{$id}{digest},
        gene_isoelectric_point  => $new{$id}{iep},
        gene_molecular_weight   => $new{$id}{mw},
        gene_tmd_count          => $new{$id}{tms},
        gene_species            => $species,
        species_code            => $spc,
        user_id                 => $tdruserid,
        gene_database_source    => $new{$id}{gene_database_source}

    }
  );
};
</code>```

While this "works", it has at least two problems I'd like to solve:

The eval statement is intended to "failsafe" the insertions: if one of the insertions fail, the eval dies and no insertion is done. This is clearly not how eval works. I'm pretty sure all insertions made
until failure point will be done and there's no rollback whatsoever.

The script needs to loop twice through very large datasets (one while reading and creating the hashes, and once again when reading
the hashes and performing the insertions). This makes the process' performance rather poor.

Instead of creating the hashes, I'd been thinking of using the new directive of DBIX $schema->new({..stuff..}); and then doing a massive insert transaction. That would solve the double iteration and the eval would either work (or not) with a single transaction, which would do the expected behaviour of < either all insertions or none > ... Is there a way to do this?

答:
You can create your massive transaction by using a TxnScopeGuard in DBIC. In the most basic form, that would be as follows.

```<code>eval { # or try from Try::Tiny
    my $guard = $schema->txn_scope_guard;

    foreach my $id ( keys %new ) {
        my $rs = $schema->resultset('Genes')->create(
            {
                gene_name              => $new{$id}{gene_name},
                gene_product           => $new{$id}{product},
                sequence               => $new{$id}{sequence},
                gene_protein_length    => $new{$id}{seqlength},
                digest                 => $new{$id}{digest},
                gene_isoelectric_point => $new{$id}{iep},
                gene_molecular_weight  => $new{$id}{mw},
                gene_tmd_count         => $new{$id}{tms},
                gene_species           => $species,
                species_code           => $spc,
                user_id                => $tdruserid,
                gene_database_source   => $new{$id}{gene_database_source}

            }
        );
    }
    $guard->commit;
}
</code>```

You create a scope guard object, and when you're done setting up your transaction, you commit it. If the object goes out of scope, i.e. because something died, it will rollback the transaction automatically.

The eval can catch the die, and your program will not crash. You had that part correct, but you're also right that your code will not undo previous inserts. Note that Try::Tiny's try provides nicer syntax. But it's not needed here.

Transaction in this case means that all queries are collected and run at the same time.

Note that this will still insert one row per INSERT statement only!

If you want to instead create larger INSERT statements, like the following, you need populate, not new.

```<code>INSERT INTO foo (bar, baz) VALUES
(1, 1),
(2, 2),
(3, 3),
...
</code>```

The populate method lets you pass in an array reference with multiple rows at one time. This is supposed to be way faster than inserting one at a time.

```<code>$schema->resultset("Artist")->populate([
  [ qw( artistid name ) ],
  [ 100, 'A Formally Unknown Singer' ],
  [ 101, 'A singer that jumped the shark two albums ago' ],
  [ 102, 'An actually cool singer' ],
]);
</code>```

Translated to your loop, that would be as follows. Note that the documentation claims that it's faster if you run it in void context.

```<code>eval {
    $schema->resultset('Genes')->populate(
        [
            [
                                qw(
                    gene_name             gene_product   sequence
                    gene_protein_length   digest         gene_isoelectric_point
                    gene_molecular_weight gene_tmd_count gene_species
                    species_code          user_id        gene_database_source
        )
            ],
            map {
                [
                    $new{$_}{gene_name}, $new{$_}{product},
                    $new{$_}{sequence},  $new{$_}{seqlength},
                    $new{$_}{digest},    $new{$_}{iep},
                    $new{$_}{mw},        $new{$_}{tms},
                    $species,            $spc,
                    $tdruserid,          $new{$_}{gene_database_source},
                ]
            } keys %new
        ],
    );
}
</code>```

Like this the scope guard is not needed. However, I would advise you to not do more than 1000 rows per statement though. Processing it in chunks might be a good idea for performance reasons. In that case, you'd loop over the keys 1000 at a time. List::MoreUtils has a nice natatime function for that.

```<code>use List::MoreUtils 'natatime';

eval {
    my $guard = $schema->txn_scope_guard;

    my $it = natatime 1_000, keys %new;

    while ( my @keys = $it->() ) {
        $schema->resultset('Genes')->populate(
            [
                [
                    qw(
                        gene_name             gene_product   sequence
                        gene_protein_length   digest         gene_isoelectric_point
                        gene_molecular_weight gene_tmd_count gene_species
                        species_code          user_id        gene_database_source
                        )
                ],
                map {
                    [
                        $new{$_}{gene_name}, $new{$_}{product},
                        $new{$_}{sequence},  $new{$_}{seqlength},
                        $new{$_}{digest},    $new{$_}{iep},
                        $new{$_}{mw},        $new{$_}{tms},
                        $species,            $spc,
                        $tdruserid,          $new{$_}{gene_database_source},
                    ]
                } @keys
            ],
        );
    }

    $guard->commit;
}
</code>```

Now it will do 1000 rows per insertion, and run all those queries in one big transaction. If one of them fails, none will be done.

The script needs to loop twice through very large datasets (one while reading and creating the hashes, and once again when reading the hashes and performing the insertions). This makes the process' performance rather poor.

You're not showing how you create the data, besides this assignment.

```<code>$new{$id}{gene_name}              = $id;
$new{$id}{gene_database_source} = $gene_database_source
$new{$id}{product}            = $product;
</code>```

If that's all there is to it, nothing is stopping you from using the approach I've shown above directly where you're processing the data the first time and building the hash. The following code is incomplete, because you're not telling us where the data is coming from, but you should get the gist.

```<code>eval {
    my $guard = $schema->txn_scope_guard;

    # we use this to collect rows to process
    my @rows;

    # this is where your data comes in
    while ( my $foo = <DATA> ) {

        # here you process the data and come up with your variables
        my ( $id, $gene_database_source, $product, $sequence, $seqlength,
             $digest, $mw, $iep, $tms );

        # collect the row so we can insert it later
        push(
            @rows,
            [
                $id, $gene_database_source, $product, $sequence, $seqlength,
                $digest, $mw, $iep, $tms,
            ]
        );

        # only insert if we reached the limit
        if ( scalar @rows == 1000 ) {
            $schema->resultset('Genes')->populate(
                [
                    [
                        qw(
                            gene_name             gene_product   sequence
                            gene_protein_length   digest         gene_isoelectric_point
                            gene_molecular_weight gene_tmd_count gene_species
                            species_code          user_id        gene_database_source
                            )
                    ],
                    \@rows,
                ],
            );

            # empty the list of values
            @rows = ();
        }
    }
    $guard->commit;
}
</code>```

Essentially we collect up to 1000 rows directly as array references while we process them, and when we've reached the limit, we pass them to the database. We then reset our row array and start over. Again, all of this is wrapped in a transaction, so it will only be committed if all the inserts are fine.

There is more information on transactions in DBIC in the cookbook.

Please note that I have not tested any of this code.

ContentLicense: CC BY-SA 4.0

Body:
I'm working in a bioinformatics project that requires me to read genomic data (nothing too fancy, just think of it as strings) from various organisms and insert it into a database. Each read belongs to one organism, and can contain from 5000 to 50000 thousand genes, which I need to process and analyze prior to storage.

The script currently doing this is written in perl and, after all calculations, stores the results in a hash likie this:

$new{$id}{gene_name}              = $id;
$new{$id}{gene_database_source} = $gene_database_source
$new{$id}{product}            = $product;
$new{$id}{sequence}               = $sequence;
$new{$id}{seqlength}              = $seqlength;
$new{$id}{digest}             = $digest;
$new{$id}{mw}                     = $mw;
$new{$id}{iep}                = $iep;
$new{$id}{tms}                = $tms;

After all genes are read and, the insertions are made looping through the hash into an eval{} statement.

eval {
foreach my $id (keys %new) {

  my $rs = $schema->resultset('Genes')->create(
    {
        gene_name               => $new{$id}{gene_name},
        gene_product            => $new{$id}{product},
        sequence                => $new{$id}{sequence},
        gene_protein_length     => $new{$id}{seqlength},
        digest                  => $new{$id}{digest},
        gene_isoelectric_point  => $new{$id}{iep},
        gene_molecular_weight   => $new{$id}{mw},
        gene_tmd_count          => $new{$id}{tms},
        gene_species            => $species,
        species_code            => $spc,
        user_id                 => $tdruserid,
        gene_database_source    => $new{$id}{gene_database_source}

    }
  );
};

While this "works", it has at least two problems I'd like to solve:

The eval statement is intended to "failsafe" the insertions: if one of the insertions fail, the eval dies and no insertion is done. This is clearly not how eval works. I'm pretty sure all insertions made
until failure point will be done and there's no rollback whatsoever.

The script needs to loop twice through very large datasets (one while reading and creating the hashes, and once again when reading
the hashes and performing the insertions). This makes the process' performance rather poor.

Instead of creating the hashes, I'd been thinking of using the new directive of DBIX $schema->new({..stuff..}); and then doing a massive insert transaction. That would solve the double iteration and the eval would either work (or not) with a single transaction, which would do the expected behaviour of < either all insertions or none > ... Is there a way to do this?

Body:
You can create your massive transaction by using a TxnScopeGuard in DBIC. In the most basic form, that would be as follows.

eval { # or try from Try::Tiny
    my $guard = $schema->txn_scope_guard;

    foreach my $id ( keys %new ) {
        my $rs = $schema->resultset('Genes')->create(
            {
                gene_name              => $new{$id}{gene_name},
                gene_product           => $new{$id}{product},
                sequence               => $new{$id}{sequence},
                gene_protein_length    => $new{$id}{seqlength},
                digest                 => $new{$id}{digest},
                gene_isoelectric_point => $new{$id}{iep},
                gene_molecular_weight  => $new{$id}{mw},
                gene_tmd_count         => $new{$id}{tms},
                gene_species           => $species,
                species_code           => $spc,
                user_id                => $tdruserid,
                gene_database_source   => $new{$id}{gene_database_source}

            }
        );
    }
    $guard->commit;
}

You create a scope guard object, and when you're done setting up your transaction, you commit it. If the object goes out of scope, i.e. because something died, it will rollback the transaction automatically.

The eval can catch the die, and your program will not crash. You had that part correct, but you're also right that your code will not undo previous inserts. Note that Try::Tiny's try provides nicer syntax. But it's not needed here.

Transaction in this case means that all queries are collected and run at the same time.

Note that this will still insert one row per INSERT statement only!

If you want to instead create larger INSERT statements, like the following, you need populate, not new.

INSERT INTO foo (bar, baz) VALUES
(1, 1),
(2, 2),
(3, 3),
...

The populate method lets you pass in an array reference with multiple rows at one time. This is supposed to be way faster than inserting one at a time.

$schema->resultset("Artist")->populate([
  [ qw( artistid name ) ],
  [ 100, 'A Formally Unknown Singer' ],
  [ 101, 'A singer that jumped the shark two albums ago' ],
  [ 102, 'An actually cool singer' ],
]);

Translated to your loop, that would be as follows. Note that the documentation claims that it's faster if you run it in void context.

eval {
    $schema->resultset('Genes')->populate(
        [
            [
                                qw(
                    gene_name             gene_product   sequence
                    gene_protein_length   digest         gene_isoelectric_point
                    gene_molecular_weight gene_tmd_count gene_species
                    species_code          user_id        gene_database_source
        )
            ],
            map {
                [
                    $new{$_}{gene_name}, $new{$_}{product},
                    $new{$_}{sequence},  $new{$_}{seqlength},
                    $new{$_}{digest},    $new{$_}{iep},
                    $new{$_}{mw},        $new{$_}{tms},
                    $species,            $spc,
                    $tdruserid,          $new{$_}{gene_database_source},
                ]
            } keys %new
        ],
    );
}

Like this the scope guard is not needed. However, I would advise you to not do more than 1000 rows per statement though. Processing it in chunks might be a good idea for performance reasons. In that case, you'd loop over the keys 1000 at a time. List::MoreUtils has a nice natatime function for that.

use List::MoreUtils 'natatime';

eval {
    my $guard = $schema->txn_scope_guard;

    my $it = natatime 1_000, keys %new;

    while ( my @keys = $it->() ) {
        $schema->resultset('Genes')->populate(
            [
                [
                    qw(
                        gene_name             gene_product   sequence
                        gene_protein_length   digest         gene_isoelectric_point
                        gene_molecular_weight gene_tmd_count gene_species
                        species_code          user_id        gene_database_source
                        )
                ],
                map {
                    [
                        $new{$_}{gene_name}, $new{$_}{product},
                        $new{$_}{sequence},  $new{$_}{seqlength},
                        $new{$_}{digest},    $new{$_}{iep},
                        $new{$_}{mw},        $new{$_}{tms},
                        $species,            $spc,
                        $tdruserid,          $new{$_}{gene_database_source},
                    ]
                } @keys
            ],
        );
    }

    $guard->commit;
}

Now it will do 1000 rows per insertion, and run all those queries in one big transaction. If one of them fails, none will be done.

The script needs to loop twice through very large datasets (one while reading and creating the hashes, and once again when reading the hashes and performing the insertions). This makes the process' performance rather poor.

You're not showing how you create the data, besides this assignment.

$new{$id}{gene_name}              = $id;
$new{$id}{gene_database_source} = $gene_database_source
$new{$id}{product}            = $product;

If that's all there is to it, nothing is stopping you from using the approach I've shown above directly where you're processing the data the first time and building the hash. The following code is incomplete, because you're not telling us where the data is coming from, but you should get the gist.

eval {
    my $guard = $schema->txn_scope_guard;

    # we use this to collect rows to process
    my @rows;

    # this is where your data comes in
    while ( my $foo = <DATA> ) {

        # here you process the data and come up with your variables
        my ( $id, $gene_database_source, $product, $sequence, $seqlength,
             $digest, $mw, $iep, $tms );

        # collect the row so we can insert it later
        push(
            @rows,
            [
                $id, $gene_database_source, $product, $sequence, $seqlength,
                $digest, $mw, $iep, $tms,
            ]
        );

        # only insert if we reached the limit
        if ( scalar @rows == 1000 ) {
            $schema->resultset('Genes')->populate(
                [
                    [
                        qw(
                            gene_name             gene_product   sequence
                            gene_protein_length   digest         gene_isoelectric_point
                            gene_molecular_weight gene_tmd_count gene_species
                            species_code          user_id        gene_database_source
                            )
                    ],
                    \@rows,
                ],
            );

            # empty the list of values
            @rows = ();
        }
    }
    $guard->commit;
}

Essentially we collect up to 1000 rows directly as array references while we process them, and when we've reached the limit, we pass them to the database. We then reset our row array and start over. Again, all of this is wrapped in a transaction, so it will only be committed if all the inserts are fine.

There is more information on transactions in DBIC in the cookbook.

Please note that I have not tested any of this code.


来源: stackexchange

问:
@RolesAllowed etc. without web.xml
I am currently working on a quite modular application where we have many jars that will be packaged and glued together in a war file.

Some of these jar files have REST resources that want to be secured. Common way is the @RolesAllowed annotation etc.

From my current knowledge this implies an existing web.xml in the WAR. This way we would have to implement jar-specific information (e.g. context roots) inside the WAR, not in the place where it belongs.

Like the most things nowadays - is there a way to programmatically set up security contexts etc. without a web.xml?

答:
I've not worked with JAX-RS for a while, but the last time I checked, when using annotation-based security, web.xml is not optional.

See my answer for details.
https://stackoverflow.com/a/20023018/839733

ContentLicense: CC BY-SA 3.0

Title: @RolesAllowed etc. without web.xml


问:
Advanced Json object handling in PHP
I'm trying to send some Json data to my server side PHP code, but i got an error message:

Notice:  Trying to get property of non-object in
  C:\xampp\htdocs\registration.php on line xy.

Here is my Json object. what I want to handle:

```<code>   registrationInputData:{"page1":{"regfnev":"John","reglnev":"Kerry","regemail":"john.kerry@gmail.com","regpassword":"Qwerty01"},"page2":{"regtelepules":"Budapest","regirsz":"1123","regutca":"","reghazszam":"","regemelet":"","regajto":"","regtelszam":""},"page3":{"regprofilimage":"dogProfileImage","regfeltetel":true}}
</code>```

And here is my PHP:

```<code><?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "getpet");
mysqli_set_charset($conn, "utf8");
$result = false;

if(isset($_POST['registrationInputData'])){
$registrationInputData = json_encode($_POST['registrationInputData']);

///page1
$fname = $registrationInputData->page1->regfnev;
$lname = $registrationInputData->page1->reglnev;
$email = $registrationInputData->page1->regemail;
$password = md5($registrationInputData->page1->regpassword);

$emailquery = "SELECT email FROM users WHERE email = '".$email."'";
$emailsql = mysqli_query($conn, $emailquery);
if(mysqli_num_rows($emailsql) == "0"){

    ///page2
    $settlement = $registrationInputData->page2->regtelepules;
    $postcode = $registrationInputData->page2->regirsz;
    $street = $registrationInputData->page2->regutca;
    $streetnumber = $registrationInputData->page2->regutca;
    $floor = $registrationInputData->page2->regemelet;
    $door = $registrationInputData->page2->regajto;
    $phone = $registrationInputData->page2->regtelszam;

    ///page3
    $profilimage = $registrationInputData->page3->regprofilimage;
    $conditionaccepted = $registrationInputData->page3->regfeltetel;

    $registrationquery =
    "INSERT INTO users (fname, lname, email, password, settlement, postcode, street, streetnumber, floor, door, phone, profilimage, conditionaccepted)
     VALUES ('".$fname."', '".$lname."', '".$email."', '".$password."', '".$settlement."', '".$postcode."', '".$street."', '".$streetnumber."', '".$floor."', '".$door."', '".$phone."', '".$profilimage."', '".$conditionaccepted."' )";
     $result = true;
}
}
echo $result;

?>
</code>```

Thanks for the answers!

答: You need to use json_decode function if it is json string you are getting in post. Then you can access the object elements.</p>

Title: Advanced Json object handling in PHP

Body:
I'm trying to send some Json data to my server side PHP code, but i got an error message:

Notice:  Trying to get property of non-object in
  C:\xampp\htdocs\registration.php on line xy.

Here is my Json object. what I want to handle:

   registrationInputData:{"page1":{"regfnev":"John","reglnev":"Kerry","regemail":"john.kerry@gmail.com","regpassword":"Qwerty01"},"page2":{"regtelepules":"Budapest","regirsz":"1123","regutca":"","reghazszam":"","regemelet":"","regajto":"","regtelszam":""},"page3":{"regprofilimage":"dogProfileImage","regfeltetel":true}}

And here is my PHP:

<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "getpet");
mysqli_set_charset($conn, "utf8");
$result = false;

if(isset($_POST['registrationInputData'])){
$registrationInputData = json_encode($_POST['registrationInputData']);

///page1
$fname = $registrationInputData->page1->regfnev;
$lname = $registrationInputData->page1->reglnev;
$email = $registrationInputData->page1->regemail;
$password = md5($registrationInputData->page1->regpassword);

$emailquery = "SELECT email FROM users WHERE email = '".$email."'";
$emailsql = mysqli_query($conn, $emailquery);
if(mysqli_num_rows($emailsql) == "0"){

    ///page2
    $settlement = $registrationInputData->page2->regtelepules;
    $postcode = $registrationInputData->page2->regirsz;
    $street = $registrationInputData->page2->regutca;
    $streetnumber = $registrationInputData->page2->regutca;
    $floor = $registrationInputData->page2->regemelet;
    $door = $registrationInputData->page2->regajto;
    $phone = $registrationInputData->page2->regtelszam;

    ///page3
    $profilimage = $registrationInputData->page3->regprofilimage;
    $conditionaccepted = $registrationInputData->page3->regfeltetel;

    $registrationquery =
    "INSERT INTO users (fname, lname, email, password, settlement, postcode, street, streetnumber, floor, door, phone, profilimage, conditionaccepted)
     VALUES ('".$fname."', '".$lname."', '".$email."', '".$password."', '".$settlement."', '".$postcode."', '".$street."', '".$streetnumber."', '".$floor."', '".$door."', '".$phone."', '".$profilimage."', '".$conditionaccepted."' )";
     $result = true;
}
}
echo $result;

?>

Thanks for the answers!


问:
Capture string that only has n words
In my case, I need n=2.

Can this be done with a regular expression? Looking for how many words there are in a string of text and capturing only the strings with 2 words?

Example:

```<code>this is a test string
another one
and another one
</code>```

Output:

```<code>another one
</code>```

For what I need, looking for strings where there is only one space should work, it's capturing the ones with only 2 words (or one space) that i don't know how to do.

答:
Something fairly simple like this should do you;

```<code>^\w+(?:\s\w+){1}$
</code>```

More generally you can use;

```<code>^\w+(?:\s\w+){N}$
</code>```

Where N = n - 1 and n, as specified, is the number of words to capture.

Title: Capture string that only has n words

Body:
In my case, I need n=2.

Can this be done with a regular expression? Looking for how many words there are in a string of text and capturing only the strings with 2 words?

Example:

this is a test string
another one
and another one

Output:

another one

For what I need, looking for strings where there is only one space should work, it's capturing the ones with only 2 words (or one space) that i don't know how to do.

Body:
Something fairly simple like this should do you;

^\w+(?:\s\w+){1}$

More generally you can use;

^\w+(?:\s\w+){N}$

Where N = n - 1 and n, as specified, is the number of words to capture.


问:
MomentJS: how to parse dates in MM/DD/YYYY & DD/MM/YYYY
How can i use moment.js in both: Australia & USA time formats?

For example:

07/08/2017 - is good for both time formats, but!

30/08/2017 - is invalid for moment.js, but i can have such dateTime

You can check it here:

http://jsfiddle.net/rLjQx/2135/

答:
The parser is assuming that digits of the form XX-XX-XXXX are representing DD-MM-YYYY. If you'd like it to accept MM-DD-YYYY then you need to specify this.

eg var now2 = moment('08/30/2017', 'MM-DD-YYYY').format('MMM DD h:mm A');

You can also specify an array of different formats that you'd like it to accept so that it will recognise both:

var now2 = moment('08/30/2017', ['DD-MM-YYYY', 'MM-DD-YYYY']).format('MMM DD h:mm A');


问:
Align icon vertically to the center of the first line of text
Here are the eyes with align-items: center property. They are OK for one-line text and FAIL for multiline text:

<img src="https://i.stack.imgur.com/FeuRN.png" alt="">

Here are the eyes with align-items: baseline (or flex-start). They are better for multiline text but not ideal for all of them because I want to align the eye to the center of first line of the text:

What I’m trying to achieve is this:

See how the eye image is centered at the first line of the text?

Is it possible to do it elegantly with flexbox properties, without using padding or margin?

(This is a simplified example. In the real problem I don’t want to introduce padding because it will affect other items.)

Here is jsfiddle to play with: http://jsfiddle.net/sqp1wdap/

答:
```<code>.LegendItem_Eye {
  width: $slotWidth; // keep width
  float:left; // float left
  line-height:1.3; // define line height
}
</code>```

That should be all you need. Demo.

Body:
.LegendItem_Eye {
  width: $slotWidth; // keep width
  float:left; // float left
  line-height:1.3; // define line height
}

That should be all you need. Demo.


问:
Identify all possible combinations of a variable, including if values are missing in R
I'm curious about the total number of ways people could have completed a training in a 'choose your own adventure format'

For example, there are 10 different levels to the training in total (i.e., level 1, 2 ... 10). People can complete 1:10; 10:1; 1,2,3,5,10; 2,1,3,5,4,6,7,9,8,10; or any combination of the levels using all, some, or none of the levels before taking their exit test.

I'm hoping to find a way to make these combinations into a categorical variable because I'm wondering if sequence matters in the users likelihood of passing the exit test.

I'd like to know how to do this in R, but if anyone has other creative solutions to offer regarding better ways to use sequence as a variable, I'm all ears for that too.

Thanks!

答:
Because 1,2,3 is different than 3,2,1, you want to use permutations, not combinations.

In addition, the size of the target vectors should range from 1 to 10 (1,2 is a possible solution, never including 3).

Be careful, all permutations of 1:10 can take a while. Going much above 10 can increase the time and memory demands. Here is how to do it with 3 values.

```<code>library(gtools)
library(data.table)

levelnum <- 3
lval <- lapply(1:levelnum, function(x) {
  dat <- data.table(permutations(levelnum, x))
  setnames(dat, as.character(1:x))})
dval <- rbindlist(lval, use.names = TRUE, fill = TRUE)
</code>```

Results in:

```<code>    1  2  3
 1: 1 NA NA
 2: 2 NA NA
 3: 3 NA NA
 4: 1  2 NA
 5: 1  3 NA
 6: 2  1 NA
 7: 2  3 NA
 8: 3  1 NA
 9: 3  2 NA
10: 1  2  3
11: 1  3  2
12: 2  1  3
13: 2  3  1
14: 3  1  2
15: 3  2  1
</code>```

Changing levelnum to 10 results in 9864100 rows.

```<code>          1  2  3  4  5  6  7  8  9 10
      1:  1 NA NA NA NA NA NA NA NA NA
      2:  2 NA NA NA NA NA NA NA NA NA
      3:  3 NA NA NA NA NA NA NA NA NA
      4:  4 NA NA NA NA NA NA NA NA NA
      5:  5 NA NA NA NA NA NA NA NA NA
     ---
9864096: 10  9  8  7  6  5  4  1  3  2
9864097: 10  9  8  7  6  5  4  2  1  3
9864098: 10  9  8  7  6  5  4  2  3  1
9864099: 10  9  8  7  6  5  4  3  1  2
9864100: 10  9  8  7  6  5  4  3  2  1
</code>```

This took a few minutes to run.

Body:
Because 1,2,3 is different than 3,2,1, you want to use permutations, not combinations.

In addition, the size of the target vectors should range from 1 to 10 (1,2 is a possible solution, never including 3).

Be careful, all permutations of 1:10 can take a while. Going much above 10 can increase the time and memory demands. Here is how to do it with 3 values.

library(gtools)
library(data.table)

levelnum <- 3
lval <- lapply(1:levelnum, function(x) {
  dat <- data.table(permutations(levelnum, x))
  setnames(dat, as.character(1:x))})
dval <- rbindlist(lval, use.names = TRUE, fill = TRUE)

Results in:

    1  2  3
 1: 1 NA NA
 2: 2 NA NA
 3: 3 NA NA
 4: 1  2 NA
 5: 1  3 NA
 6: 2  1 NA
 7: 2  3 NA
 8: 3  1 NA
 9: 3  2 NA
10: 1  2  3
11: 1  3  2
12: 2  1  3
13: 2  3  1
14: 3  1  2
15: 3  2  1

Changing levelnum to 10 results in 9864100 rows.

          1  2  3  4  5  6  7  8  9 10
      1:  1 NA NA NA NA NA NA NA NA NA
      2:  2 NA NA NA NA NA NA NA NA NA
      3:  3 NA NA NA NA NA NA NA NA NA
      4:  4 NA NA NA NA NA NA NA NA NA
      5:  5 NA NA NA NA NA NA NA NA NA
     ---
9864096: 10  9  8  7  6  5  4  1  3  2
9864097: 10  9  8  7  6  5  4  2  1  3
9864098: 10  9  8  7  6  5  4  2  3  1
9864099: 10  9  8  7  6  5  4  3  1  2
9864100: 10  9  8  7  6  5  4  3  2  1

This took a few minutes to run.


问:
Can pip be used with Python Tools in Visual Studio?
I'm collaborating with some fellow students to build a python app, and was hoping to use the 'training wheels' of Visual Studio intelli-sense. They use python on mac and linux, so ideally our source control repo would consist of just *.py source files that we wrote, and a requirements.txt export of pip dependancies (using the pip freeze method).

I would love to be able to create a new Visual Studio project, then be able to run the following commands (for instance) within that project:

```<code>pip install boto
pip install fabric
pip install cuisine
pip freeze > requirements.txt
</code>```

And after that, be able to write some code that references these libraries and be able to run it from within Visual Studio.

Is there any way to do this?  Is Python within Visual Studio even able to handle modules in the format they are available within pip, or do all python libraries used in VS have to have been pre-compiled for Windows?

答: On VS 2017, switch to the "solution explorer" and right click as indicated:

Body:
I'm collaborating with some fellow students to build a python app, and was hoping to use the 'training wheels' of Visual Studio intelli-sense. They use python on mac and linux, so ideally our source control repo would consist of just *.py source files that we wrote, and a requirements.txt export of pip dependancies (using the pip freeze method).

I would love to be able to create a new Visual Studio project, then be able to run the following commands (for instance) within that project:

pip install boto
pip install fabric
pip install cuisine
pip freeze > requirements.txt

And after that, be able to write some code that references these libraries and be able to run it from within Visual Studio.

Is there any way to do this?  Is Python within Visual Studio even able to handle modules in the format they are available within pip, or do all python libraries used in VS have to have been pre-compiled for Windows?


问:
Does Qt slots run in parallel with other code?
On this function example:

```<code>void MyClass::myFunction()
  {
    emit MySignal1();
    emit MySignal2();
  }
</code>```

If I have slot1 listening for MySignal1, and slot2 listening for MySignal2:

1) Is slot1 going to be always executed before slot2?

2) Will one slot be executed until the other one finishes? Or can both slots run in parallel?

答:
Slots are invoked in the order they are connected to the signal. And are invoked at the time of emit; so in your case (ignoring threads) the slots connected to the first signal will run before those connected to the second (for Qt 4.6+, before that the order was undefined).

The slots may run on other threads (and thus execute concurrently) - see  (for example) http://doc.qt.io/qt-4.8/threads-qobject.html#signals-and-slots-across-threads for details.

Body:
On this function example:

void MyClass::myFunction()
  {
    emit MySignal1();
    emit MySignal2();
  }

If I have slot1 listening for MySignal1, and slot2 listening for MySignal2:

1) Is slot1 going to be always executed before slot2?

2) Will one slot be executed until the other one finishes? Or can both slots run in parallel?


问:
How many people can connect to ServerSocket?
I'm working with sockets. I'd like to know how many people can connect to my SocketServer using Sockets?

According to Cameron it is 2^16 different connection. So, as much as 2^16 people can actually use my chat at the same time(resources for handling so much users and other factors are not considered)???

https://www.quora.com/How-many-connections-can-a-JAVA-socket-server-hold

答: On Mac and Linux, you can do "ulimit", which will tell you the limit defined by the operating system.</p>


问:
Trouble Scraping site with BS4
usually I'm able to write a script that works for scraping, but I've been having some difficulty scraping this site for the table enlisted for this research project I'm working on. I'm planning to verify the script working on one State before entering the URL of my targeted states.

```<code>import requests
import bs4 as bs

url = ("http://programs.dsireusa.org/system/program/detail/284")
dsire_get = requests.get(url)
soup = bs.BeautifulSoup(dsire_get.text,'lxml')
table = soup.findAll('div', {'data-ng-controller': 'DetailsPageCtrl'})
print(table)
#I'm printing "Table" just to ensure that the table information I'm looking for is within this sections
</code>```

I'm not sure if the site is attempting to block people from scraping, but all the info that I'm looking to grab is within "&quot"if you look what Table outputs.

答:
So I finally managed to solve the issue, and successfuly grab the data from the Javascript page the code as follows worked for me if anyone encounters a same issue when trying to use python to scrape a javascript webpage using windows (dryscrape incompatible).</p>

```<code>import bs4 as bs
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
browser = webdriver.Chrome()
url = ("http://programs.dsireusa.org/system/program/detail/284")
browser.get(url)
html_source = browser.page_source
browser.quit()
soup = bs.BeautifulSoup(html_source, "html.parser")
table = soup.find('div', {'class': 'programOverview'})
data = []
for n in table.findAll("div", {"class": "ng-binding"}):
    trip = str(n.text)
    data.append(trip)
</code>```

Title: Trouble Scraping site with BS4

Body:
usually I'm able to write a script that works for scraping, but I've been having some difficulty scraping this site for the table enlisted for this research project I'm working on. I'm planning to verify the script working on one State before entering the URL of my targeted states.

import requests
import bs4 as bs

url = ("http://programs.dsireusa.org/system/program/detail/284")
dsire_get = requests.get(url)
soup = bs.BeautifulSoup(dsire_get.text,'lxml')
table = soup.findAll('div', {'data-ng-controller': 'DetailsPageCtrl'})
print(table)
#I'm printing "Table" just to ensure that the table information I'm looking for is within this sections

I'm not sure if the site is attempting to block people from scraping, but all the info that I'm looking to grab is within "&quot"if you look what Table outputs.

Body:
So I finally managed to solve the issue, and successfuly grab the data from the Javascript page the code as follows worked for me if anyone encounters a same issue when trying to use python to scrape a javascript webpage using windows (dryscrape incompatible).

import bs4 as bs
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
browser = webdriver.Chrome()
url = ("http://programs.dsireusa.org/system/program/detail/284")
browser.get(url)
html_source = browser.page_source
browser.quit()
soup = bs.BeautifulSoup(html_source, "html.parser")
table = soup.find('div', {'class': 'programOverview'})
data = []
for n in table.findAll("div", {"class": "ng-binding"}):
    trip = str(n.text)
    data.append(trip)


问:
Divide every other column with values in the last column
I have data as shown below. I would like to divide every other row with the weight column. Is there an automated way to do this? My data has about several columns.

What I looking for is the result of A/Weight should be replaced in column A and the result of C/Weight should be replaced in Column C and so on until the last pair of columns.

```<code>          A            B           C           D       Weight
 0   2.056494    -3.002088   0.516822    -1.338846      0.40
 1   0.082295    1.387734    -0.495226   1.119553       0.50
 2   0.298618    -0.130158   0.804705    -0.120110      0.25
 3   0.178088    1.137238    1.331856    -0.472720      0.50
 4   -0.378670   1.649041    -0.240723   2.044113       0.65
 5   3.602587    1.152502    -0.170646   -0.961922      0.50
 6   -0.285846   -0.154891   1.492879    0.752487       0.56
 7   -0.412809   1.076796    -2.001025   -0.954021      0.25
</code>```

I have something like this but it does not work:

```<code>results=results.iloc[:, 0::2].div(results['Weight'], axis=0)
</code>```

The code below works for every other column (B/A and D/C). But I need the denominator static with just the 'Weight' column.

```<code>results_201.iloc[:,1::2] /= results_201.iloc[:,::2].values
</code>```

Thanks for reading this and for your help!

Body:
I have data as shown below. I would like to divide every other row with the weight column. Is there an automated way to do this? My data has about several columns.

What I looking for is the result of A/Weight should be replaced in column A and the result of C/Weight should be replaced in Column C and so on until the last pair of columns.

          A            B           C           D       Weight
 0   2.056494    -3.002088   0.516822    -1.338846      0.40
 1   0.082295    1.387734    -0.495226   1.119553       0.50
 2   0.298618    -0.130158   0.804705    -0.120110      0.25
 3   0.178088    1.137238    1.331856    -0.472720      0.50
 4   -0.378670   1.649041    -0.240723   2.044113       0.65
 5   3.602587    1.152502    -0.170646   -0.961922      0.50
 6   -0.285846   -0.154891   1.492879    0.752487       0.56
 7   -0.412809   1.076796    -2.001025   -0.954021      0.25

I have something like this but it does not work:

results=results.iloc[:, 0::2].div(results['Weight'], axis=0)

The code below works for every other column (B/A and D/C). But I need the denominator static with just the 'Weight' column.

results_201.iloc[:,1::2] /= results_201.iloc[:,::2].values

Thanks for reading this and for your help!

Body:
We would need broadcasting here. So, one approach would involve using the underlying array data for in-situ edit, like so -

df.iloc[:,:-1:2] = df.iloc[:,:-1:2].values / df.iloc[:,[-1]].values

Sample run -

In [62]: df
Out[62]:
        A       B       C       D  Weight
0  2.0565 -3.0021  0.5168 -1.3388  0.4000
1  0.0823  1.3877 -0.4952  1.1196  0.5000
2  0.2986 -0.1302  0.8047 -0.1201  0.2500
3  0.1781  1.1372  1.3319 -0.4727  0.5000
4 -0.3787  1.6490 -0.2407  2.0441  0.6500
5  3.6026  1.1525 -0.1706 -0.9619  0.5000
6 -0.2858 -0.1549  1.4929  0.7525  0.5600
7 -0.4128  1.0768 -2.0010 -0.9540  0.2500

In [63]: df.iloc[:,:-1:2] = df.iloc[:,:-1:2].values / df.iloc[:,[-1]].values

In [64]: df
Out[64]:
        A       B       C       D  Weight
0  5.1412 -3.0021  1.2921 -1.3388  0.4000
1  0.1646  1.3877 -0.9905  1.1196  0.5000
2  1.1945 -0.1302  3.2188 -0.1201  0.2500
3  0.3562  1.1372  2.6637 -0.4727  0.5000
4 -0.5826  1.6490 -0.3703  2.0441  0.6500
5  7.2052  1.1525 -0.3413 -0.9619  0.5000
6 -0.5104 -0.1549  2.6659  0.7525  0.5600
7 -1.6512  1.0768 -8.0041 -0.9540  0.2500

An easier on eyes alternative would be to get the entire data as array view and process on that array itself -

In [96]: df
Out[96]:
        A       B       C       D  Weight
0  2.0565 -3.0021  0.5168 -1.3388  0.4000
1  0.0823  1.3877 -0.4952  1.1196  0.5000
2  0.2986 -0.1302  0.8047 -0.1201  0.2500
3  0.1781  1.1372  1.3319 -0.4727  0.5000
4 -0.3787  1.6490 -0.2407  2.0441  0.6500
5  3.6026  1.1525 -0.1706 -0.9619  0.5000
6 -0.2858 -0.1549  1.4929  0.7525  0.5600
7 -0.4128  1.0768 -2.0010 -0.9540  0.2500

In [97]: a = df.values

In [98]: a[:,:-1:2] /= a[:,[-1]]

In [99]: df
Out[99]:
        A       B       C       D  Weight
0  5.1412 -3.0021  1.2921 -1.3388  0.4000
1  0.1646  1.3877 -0.9905  1.1196  0.5000
2  1.1945 -0.1302  3.2188 -0.1201  0.2500
3  0.3562  1.1372  2.6637 -0.4727  0.5000
4 -0.5826  1.6490 -0.3703  2.0441  0.6500
5  7.2052  1.1525 -0.3413 -0.9619  0.5000
6 -0.5104 -0.1549  2.6659  0.7525  0.5600
7 -1.6512  1.0768 -8.0041 -0.9540  0.2500


问:
Add a text near my checkbox slider
I'm using some slider to replace my checkboxes.

```<code><div class="col-sm-4">
    <label class="switch small">
        <input type="checkbox">
        <div class="slider small"></div>
    </label>
</div>
</code>```

https://jsfiddle.net/dky16b53/

How can I add some text near each sliders please ?

Thanks.

答:
Put some text after the label tag, but still in the div.col-sm-4. See the span element below.</p>

```<code><div class="col-sm-4">
    <label class="switch small">
        <input type="checkbox">
        <div class="slider small"></div>
    </label>
    <span>Text next to slider</span>
</div>
</code>```

Title: Add a text near my checkbox slider

Body:
I'm using some slider to replace my checkboxes.

        <input type="checkbox">

https://jsfiddle.net/dky16b53/

How can I add some text near each sliders please ?

Thanks.

Body:
Put some text after the label tag, but still in the div.col-sm-4. See the span element below.

<div class="col-sm-4">
    <label class="switch small">
        <input type="checkbox">
        <div class="slider small"></div>
    </label>
    <span>Text next to slider</span>
</div>


问:
Delete user from MySQL table if no other users exist with similar traits
I have the following table called tbl_test in a MySQL database :

```<code>+------+------------+------------+
| name | fav_color  | dob        |
+======+============+============+
| jane | blue       | 1996-07-07 |
+------+------------+------------+
| jane | pink       | 1996-07-07 |
+------+------------+------------+
| jane | pink       | 2016-07-07 |
+------+------------+------------+
| joe  | pink       | 2001-07-07 |
+------+------------+------------+
| john | red        | 1997-07-07 |
+------+------------+------------+
</code>```

In English, here's what I want to accomplish:

delete all users with dob < 2001-01-01 but keep a user if there exists another user with the same name AND fav_color whose dob >= 2001-01-01.

So in this example, the jane whose favorite color is blue and john would be deleted.

So far, I've tried:

```<code>DELETE FROM tbl_test
WHERE dob < '2000-01-01' AND name, fav_color NOT IN
(SELECT T.name, T.fav_color FROM
(SELECT name, fav_color FROM tbl_test WHERE dob >= '2000-01-01') T);
</code>```

But MySQL throws a syntax error when I enter this command. Any tips for how I can achieve this?

答:
You can do this without subqueries by using an exclusion join.

Try to join a user "t1" to another user "t2" with the criteria you describe. If none is found, the OUTER JOIN will make all columns NULL for t2. Where this happens, delete t1.

```<code>DELETE t1
FROM tbl_test AS t1
LEFT OUTER JOIN tbl_test AS t2
  ON t1.name = t2.name AND t1.fav_color = t2.fav_color AND t2.dob >= '2000-01-01'
WHERE t1.dob < '2000-01-01'
  AND t2.name IS NULL;
</code>```

Body:
I have the following table called tbl_test in a MySQL database :

+------+------------+------------+
| name | fav_color  | dob        |
+======+============+============+
| jane | blue       | 1996-07-07 |
+------+------------+------------+
| jane | pink       | 1996-07-07 |
+------+------------+------------+
| jane | pink       | 2016-07-07 |
+------+------------+------------+
| joe  | pink       | 2001-07-07 |
+------+------------+------------+
| john | red        | 1997-07-07 |
+------+------------+------------+

In English, here's what I want to accomplish:

delete all users with dob < 2001-01-01 but keep a user if there exists another user with the same name AND fav_color whose dob >= 2001-01-01.

So in this example, the jane whose favorite color is blue and john would be deleted.

So far, I've tried:

DELETE FROM tbl_test
WHERE dob < '2000-01-01' AND name, fav_color NOT IN
(SELECT T.name, T.fav_color FROM
(SELECT name, fav_color FROM tbl_test WHERE dob >= '2000-01-01') T);

But MySQL throws a syntax error when I enter this command. Any tips for how I can achieve this?

Body:
You can do this without subqueries by using an exclusion join.

Try to join a user "t1" to another user "t2" with the criteria you describe. If none is found, the OUTER JOIN will make all columns NULL for t2. Where this happens, delete t1.

DELETE t1
FROM tbl_test AS t1
LEFT OUTER JOIN tbl_test AS t2
  ON t1.name = t2.name AND t1.fav_color = t2.fav_color AND t2.dob >= '2000-01-01'
WHERE t1.dob < '2000-01-01'
  AND t2.name IS NULL;


问:
Unable to fetch code from git repository for a specific SHA in ansible
I want to fetch code using a particular SHA-id.This is what I am trying

```<code>- git:
        repo: http://<git-url>/Vara-Internal/mongo-db-dev.git
        dest: "{{ app_path }}/{{ app_dir }}"
        version: "{{ GIT_TAG }}"
        refspec: '+refs/heads/{{ GIT_TAG }}:refs/remotes/origin/{{ GIT_TAG }}'
        update: yes
        force: true
      register: cloned
</code>```

It throwing me this error

```<code>FAILED! => {"changed": false, "cmd": ["/usr/bin/git", "fetch", "--tags", "origin", "+refs/heads/dbde451f203a112d0838fb09bc19ed28bd231e6e:refs/remotes/origin/dbde451f203a112d0838fb09bc19ed28bd231e6e"], "failed": true, "msg": "Failed to download remote objects and refs:  fatal: Couldn't find remote ref refs/heads/dbde451f203a112d0838fb09bc19ed28bd231e6e\n"}
</code>```

答:
(Note: I know very little about ansible, being just a casual user.)

Most (but not all) Git servers will not let you retrieve objects by hash IDs at all.  Most servers require that the object have a name, such as refs/heads/master (branch master) or refs/tags/v1.1 (the tag named v1.1).

If a server does allow retrieval by hash ID (see VonC's answer here), you must not qualify the hash ID: it's not refs/heads/dbde451f203a112d0838fb09bc19ed28bd231e6e bit rather simply dbde451f203a112d0838fb09bc19ed28bd231e6e.  That would become the src part of a src:dst refspec.

Typically you would use a tag name here, not a hash ID, but if your server does allow retrieval by hash ID, the refspec line would logically have to read:

```<code>refspec: '+{{ GIT_TAG }}:refs/remotes/origin/some-particular-name'
</code>```

as it is not a good idea to use hash IDs as names (for several reasons, the main one being that you will confuse humans).

Body:
I want to fetch code using a particular SHA-id.This is what I am trying

- git:
        repo: http://<git-url>/Vara-Internal/mongo-db-dev.git
        dest: "{{ app_path }}/{{ app_dir }}"
        version: "{{ GIT_TAG }}"
        refspec: '+refs/heads/{{ GIT_TAG }}:refs/remotes/origin/{{ GIT_TAG }}'
        update: yes
        force: true
      register: cloned

It throwing me this error

FAILED! => {"changed": false, "cmd": ["/usr/bin/git", "fetch", "--tags", "origin", "+refs/heads/dbde451f203a112d0838fb09bc19ed28bd231e6e:refs/remotes/origin/dbde451f203a112d0838fb09bc19ed28bd231e6e"], "failed": true, "msg": "Failed to download remote objects and refs:  fatal: Couldn't find remote ref refs/heads/dbde451f203a112d0838fb09bc19ed28bd231e6e\n"}

Body:
(Note: I know very little about ansible, being just a casual user.)

Most (but not all) Git servers will not let you retrieve objects by hash IDs at all.  Most servers require that the object have a name, such as refs/heads/master (branch master) or refs/tags/v1.1 (the tag named v1.1).

If a server does allow retrieval by hash ID (see VonC's answer here), you must not qualify the hash ID: it's not refs/heads/dbde451f203a112d0838fb09bc19ed28bd231e6e bit rather simply dbde451f203a112d0838fb09bc19ed28bd231e6e.  That would become the src part of a src:dst refspec.

Typically you would use a tag name here, not a hash ID, but if your server does allow retrieval by hash ID, the refspec line would logically have to read:

refspec: '+{{ GIT_TAG }}:refs/remotes/origin/some-particular-name'

as it is not a good idea to use hash IDs as names (for several reasons, the main one being that you will confuse humans).


问:
How do I create an average from a Ruby array?
How would get find an average from an array?

If I have the array:

```<code>[0,4,8,2,5,0,2,6]
</code>```

Averaging would give me 3.375.

答:
You could try something like the following:</p>

```<code>a = [1,2,3,4,5]
# => [1, 2, 3, 4, 5]
(a.sum/a.length).to_f
# => 3.0
</code>```

Body:
How would get find an average from an array?

If I have the array:

[0,4,8,2,5,0,2,6]

Averaging would give me 3.375.

Body:
You could try something like the following:

a = [1,2,3,4,5]
# => [1, 2, 3, 4, 5]
(a.sum/a.length).to_f
# => 3.0


问:
How do I use ArrayAdapter to display a list view?
I want to display a list view in my application. Each row should contain a text and an image. I have used ArrayAdapter to display this but how to insert an image after the text.
Here is the code:

```<code>String lvr[]={"Android","iPhone","BlackBerry","AndroidPeople"};
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list1 = (ListView) findViewById(R.id.cg_listview1);
list1.setAdapter(new ArrayAdapter<String>(this,R.layout.alerts , lvr));
</code>```

Here alerts is my layout which contains only a textView.

答:
You would need to create a custom adapter to achieve this.

```<code>public class ResultAdapter extends BaseAdapter {

    private final Context context;
    private final List<Result> results;

    public ResultAdapter(Context context, List<Result> results) {
        this.context = context;
        this.results = results;
    }

    @Override
    public int getCount() {
        return this.results.size();
    }

    @Override
    public Object getItem(int position) {
        return this.results.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    }
}
</code>```

Create a Result class for storing the text and the image. In the getView method create your View either programmatically or by loading it from an XML layout using LayoutInflater.

Body:
I want to display a list view in my application. Each row should contain a text and an image. I have used ArrayAdapter to display this but how to insert an image after the text.
Here is the code:

String lvr[]={"Android","iPhone","BlackBerry","AndroidPeople"};
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list1 = (ListView) findViewById(R.id.cg_listview1);
list1.setAdapter(new ArrayAdapter<String>(this,R.layout.alerts , lvr));

Here alerts is my layout which contains only a textView.

Body:
You would need to create a custom adapter to achieve this.

public class ResultAdapter extends BaseAdapter {

    private final Context context;
    private final List<Result> results;

    public ResultAdapter(Context context, List<Result> results) {
        this.context = context;
        this.results = results;
    }

    @Override
    public int getCount() {
        return this.results.size();
    }

    @Override
    public Object getItem(int position) {
        return this.results.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    }
}

Create a Result class for storing the text and the image. In the getView method create your View either programmatically or by loading it from an XML layout using LayoutInflater.

ContentLicense: CC BY-SA 2.5


问:
Groupby max value and return corresponding row in pandas dataframe
My dataframe consists of students, dates, and test scores. I want to find the max date for each student and return the corresponding row (ultimately, I am most interested in the student's most recent score). How could I do this in pandas?

Let's say my dataframe looks like this (an abbreviated version):

```<code>Student_id  Date     Score
Tina1       1/17/17   .95
John2       1/18/17   .8
Lia1        12/13/16  .845
John2       1/25/17   .975
Tina1       1/1/17    .78
Lia1        6/12/16   .89
</code>```

This is what I want:

```<code>Student_id  Date     Score
Tina1       1/17/17   .95
Lia1        12/13/16  .845
John2       1/25/17   .975
</code>```

I found this on SO but it gives me a positional indexers out-of-bounds error.

```<code>df.iloc[df.groupby('student_id').apply(lambda x: x['date'].idxmax())]
</code>```

What are other approaches to achieve the same thing?

答:
You can sort the data frame by Date and then use groupby.tail to get the most recent record:

```<code>df.iloc[pd.to_datetime(df.Date, format='%m/%d/%y').argsort()].groupby('Student_id').tail(1)

#Student_id     Date    Score
#2     Lia1 12/13/16    0.845
#0    Tina1  1/17/17    0.950
#3    John2  1/25/17    0.975
</code>```

Or avoid sorting, use idxmax (this works if you don't have duplicated index):

```<code>df.loc[pd.to_datetime(df.Date, format='%m/%d/%y').groupby(df.Student_id).idxmax()]

# Student_id       Date Score
#3     John2    1/25/17 0.975
#2      Lia1   12/13/16 0.845
#0     Tina1    1/17/17 0.950
</code>```

Body:
My dataframe consists of students, dates, and test scores. I want to find the max date for each student and return the corresponding row (ultimately, I am most interested in the student's most recent score). How could I do this in pandas?

Let's say my dataframe looks like this (an abbreviated version):

Student_id  Date     Score
Tina1       1/17/17   .95
John2       1/18/17   .8
Lia1        12/13/16  .845
John2       1/25/17   .975
Tina1       1/1/17    .78
Lia1        6/12/16   .89

This is what I want:

Student_id  Date     Score
Tina1       1/17/17   .95
Lia1        12/13/16  .845
John2       1/25/17   .975

I found this on SO but it gives me a positional indexers out-of-bounds error.

df.iloc[df.groupby('student_id').apply(lambda x: x['date'].idxmax())]

What are other approaches to achieve the same thing?

Body:
You can sort the data frame by Date and then use groupby.tail to get the most recent record:

df.iloc[pd.to_datetime(df.Date, format='%m/%d/%y').argsort()].groupby('Student_id').tail(1)

#Student_id     Date    Score
#2     Lia1 12/13/16    0.845
#0    Tina1  1/17/17    0.950
#3    John2  1/25/17    0.975

Or avoid sorting, use idxmax (this works if you don't have duplicated index):

df.loc[pd.to_datetime(df.Date, format='%m/%d/%y').groupby(df.Student_id).idxmax()]

# Student_id       Date Score
#3     John2    1/25/17 0.975
#2      Lia1   12/13/16 0.845
#0     Tina1    1/17/17 0.950


问:
node js Array.push() not working using mongoose
I am beginner in meanstack development. I am trying to push value inside an array in foreach loop but last i am getting empty array.

My code:

```<code>router.get("/", function(req, res) {

 ourpackage.find({}).sort({_id:1}).exec(function(err,resdoc){

  var rest = [];
  resdoc.forEach(function(doc){
    masterRoomimage.find({ourpackageId:doc._id},function(err,ourpackageimagevalue){
      if(err) res.send(err);
      var ourpackagedetail = JSON.parse(JSON.stringify(doc));
      var stringifyimages = JSON.parse(JSON.stringify(ourpackageimagevalue));
      var ourpackage = _.merge({},ourpackagedetail,{masterRoomimages:stringifyimages});
      rest.push(ourpackageimagevalue);
             //print all rest array value
             console.log(rest);
           });
  });
      //print empty rest array value
      console.log(rest);
      res.send(rest);
    });
});
</code>```

ourpackage Schema

```<code>  {
            "_id": "58e396d4215bc61338d2c06e",
            "first_title": "test 1",
            "berief_text": "<p>testing </p>",
   }
</code>```

ourpackagesimages Schema

```<code>[
            {
                "_id": "59424d49fcc8100050916bf4",
                "imageLocation": "first.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            },
            {
                "_id": "59424d49fcc8100050916bf5",
                "imageLocation": "third.jpg",
                "ourpackageId": "58e396d4215bc61338d2c077",
                "__v": 0
            },
            {
                "_id": "59490ad44e26c13324906433",
                "imageLocation": "second.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            }
    ]
</code>```

expected output

```<code>[
    {
        "_id": "58e396d4215bc61338d2c06e",
        "first_title": "test 1",
        "berief_text": "<p>testing </p>",
        "ourpackagesimages": [
            {
                "_id": "59424d49fcc8100050916bf4",
                "imageLocation": "first.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            },
            {
                "_id": "59490ad44e26c13324906433",
                "imageLocation": "second.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            }

        ]
    }
]
</code>```

obtained output empty

```<code>[]
</code>```

答:
You can't call an asynchronous function inside a synchronous function (forEach in this case). The result is accessed before it's collected and that's why the empty array output.

A very handy and easy to use library for this purpose is async. For your particular use case, map or mapLimit function will do.

```<code>var async = require('async');

router.get("/", function(req, res) {
    ourpackage.find({}).sort({
        _id: 1
    }).exec(function(err, resdoc) {

        async.mapLimit(resdoc, 5, function(doc, callback){
            masterRoomimage.find({
                ourpackageId: doc._id
            }, function(err, ourpackageimagevalue) {
                if (err) return callback(err);

                var ourpackagedetail = JSON.parse(JSON.stringify(doc));
                var stringifyimages = JSON.parse(JSON.stringify(ourpackageimagevalue));
                var ourpackage = _.merge({}, ourpackagedetail, {
                    masterRoomimages: stringifyimages
                });
                return callback(null, ourpackageimagevalue);
            });

        }, function(err, rest) {
            if(err){
                res.send(err);
            }
            else{
                res.send(rest);
            }
        });
    });
});
</code>```

Body:
I am beginner in meanstack development. I am trying to push value inside an array in foreach loop but last i am getting empty array.

My code:

router.get("/", function(req, res) {

 ourpackage.find({}).sort({_id:1}).exec(function(err,resdoc){

  var rest = [];
  resdoc.forEach(function(doc){
    masterRoomimage.find({ourpackageId:doc._id},function(err,ourpackageimagevalue){
      if(err) res.send(err);
      var ourpackagedetail = JSON.parse(JSON.stringify(doc));
      var stringifyimages = JSON.parse(JSON.stringify(ourpackageimagevalue));
      var ourpackage = _.merge({},ourpackagedetail,{masterRoomimages:stringifyimages});
      rest.push(ourpackageimagevalue);
             //print all rest array value
             console.log(rest);
           });
  });
      //print empty rest array value
      console.log(rest);
      res.send(rest);
    });
});

ourpackage Schema

  {
            "_id": "58e396d4215bc61338d2c06e",
            "first_title": "test 1",
            "berief_text": "
testing
",
   }

ourpackagesimages Schema

[
            {
                "_id": "59424d49fcc8100050916bf4",
                "imageLocation": "first.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            },
            {
                "_id": "59424d49fcc8100050916bf5",
                "imageLocation": "third.jpg",
                "ourpackageId": "58e396d4215bc61338d2c077",
                "__v": 0
            },
            {
                "_id": "59490ad44e26c13324906433",
                "imageLocation": "second.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            }
    ]

expected output

[
    {
        "_id": "58e396d4215bc61338d2c06e",
        "first_title": "test 1",
        "berief_text": "
testing
",
        "ourpackagesimages": [
            {
                "_id": "59424d49fcc8100050916bf4",
                "imageLocation": "first.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            },
            {
                "_id": "59490ad44e26c13324906433",
                "imageLocation": "second.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            }

        ]
    }
]

obtained output empty

[]

Body:
You can't call an asynchronous function inside a synchronous function (forEach in this case). The result is accessed before it's collected and that's why the empty array output.

A very handy and easy to use library for this purpose is async. For your particular use case, map or mapLimit function will do.

var async = require('async');

router.get("/", function(req, res) {
    ourpackage.find({}).sort({
        _id: 1
    }).exec(function(err, resdoc) {

        async.mapLimit(resdoc, 5, function(doc, callback){
            masterRoomimage.find({
                ourpackageId: doc._id
            }, function(err, ourpackageimagevalue) {
                if (err) return callback(err);

                var ourpackagedetail = JSON.parse(JSON.stringify(doc));
                var stringifyimages = JSON.parse(JSON.stringify(ourpackageimagevalue));
                var ourpackage = _.merge({}, ourpackagedetail, {
                    masterRoomimages: stringifyimages
                });
                return callback(null, ourpackageimagevalue);
            });

        }, function(err, rest) {
            if(err){
                res.send(err);
            }
            else{
                res.send(rest);
            }
        });
    });
});


问:
"getaddrinfo ENOTFOUND" error on heroku
I am tring to deploy a webRTC signaling server on Heroku. It works on my local machine but gave:

```<code>Error: getaddrinfo ENOTFOUND global.xirsys.net global.xirsys.net`
</code>```

when deployed on Heroku.

I am using simpleWebRTC + signalmaster + XirSys

The official doc from xirSys shows:

```<code>// Node Get ICE STUN and TURN list
var https = require("https");
var options = {
      host: "global.xirsys.net",
      path: "/_turn/Acumany",
      method: "PUT",
      headers: {
          "Authorization": "Basic " + new Buffer("acumany:4b6aea04-6152-11e7-9d16-3fa9b82ffd4f").toString("base64")
      }
};
var httpreq = https.request(options, function(httpres) {
      var str = "";
      httpres.on("data", function(data){ str += data; });
      httpres.on("error", function(e){ console.log("error: ",e); });
      httpres.on("end", function(){
          console.log("ICE List: ", str);
      });
});
httpreq.end();
</code>```

And I used axios:

```<code>axios.put("https://acumany:4b6aea04-6152-11e7-9d16-3fa9b82ffd4f@global.xirsys.net/_turn/Acumany")
            .then((res) => {
              var result = res.data;
              var iceServers = result.v.iceServers;
              var turnservers = [],
                  stunservers = [];
              iceServers.forEach(function (server) {
                  if(server.url.indexOf("stun:") != -1){
                      stunservers.push(server);
                  }else{
                      turnservers.push(server);
                  }
              });
              console.log("emitting server info => ", stunservers, turnservers);
              client.emit('stunservers', stunservers || []);
              client.emit('turnservers', turnservers);
            })
            .catch(function (err) {
              console.log("axios error => ", err);
            });
</code>```

My guess is that heroku switch http/https in its own load balancer.
How can I change this code to make it work? (either with https or axios)

答:
global.xirsys.net is a dynamic domain which geographically routes your request. Maybe something about that is incompatible with Heroku. Try a static xirsys endpoint instead. Like ss.xirsys.com for Singapore or us.xirsys.com for US east coast.

You can see a list of endpoints here: https://us.xirsys.com:9000/api-intro

Title: "getaddrinfo ENOTFOUND" error on heroku

Body:
I am tring to deploy a webRTC signaling server on Heroku. It works on my local machine but gave:

Error: getaddrinfo ENOTFOUND global.xirsys.net global.xirsys.net`

when deployed on Heroku.

I am using simpleWebRTC + signalmaster + XirSys

The official doc from xirSys shows:

// Node Get ICE STUN and TURN list
var https = require("https");
var options = {
      host: "global.xirsys.net",
      path: "/_turn/Acumany",
      method: "PUT",
      headers: {
          "Authorization": "Basic " + new Buffer("acumany:4b6aea04-6152-11e7-9d16-3fa9b82ffd4f").toString("base64")
      }
};
var httpreq = https.request(options, function(httpres) {
      var str = "";
      httpres.on("data", function(data){ str += data; });
      httpres.on("error", function(e){ console.log("error: ",e); });
      httpres.on("end", function(){
          console.log("ICE List: ", str);
      });
});
httpreq.end();

And I used axios:

axios.put("https://acumany:4b6aea04-6152-11e7-9d16-3fa9b82ffd4f@global.xirsys.net/_turn/Acumany")
            .then((res) => {
              var result = res.data;
              var iceServers = result.v.iceServers;
              var turnservers = [],
                  stunservers = [];
              iceServers.forEach(function (server) {
                  if(server.url.indexOf("stun:") != -1){
                      stunservers.push(server);
                  }else{
                      turnservers.push(server);
                  }
              });
              console.log("emitting server info => ", stunservers, turnservers);
              client.emit('stunservers', stunservers || []);
              client.emit('turnservers', turnservers);
            })
            .catch(function (err) {
              console.log("axios error => ", err);
            });

My guess is that heroku switch http/https in its own load balancer.
How can I change this code to make it work? (either with https or axios)


问:
Assign multiple feature group in edit control in leaflet draw
How can i assign multiple the feature groups in edit control,

Assume we have two feature groups(It can be multiple),and we want to assign edit control to both groups.

This is groups,

```<code>var attLayerGroup = new L.FeatureGroup();
var photoLayerGroup = new L.FeatureGroup();
</code>```

And this is, How i assign control to groups,

```<code>    var drawControl = map.addControl(new L.Control.Draw({
    edit: {
        featureGroup: photoLayerGroup,attLayerGroup,
        poly: {
            allowIntersection: true
        }
    },
    draw: {
        polygon: {
            allowIntersection: false,
            showArea: true
        }

    }
}));
</code>```

Is it right way to assigning Edit control to FeatureGroup ?
  If not,How can we do it?

答:
If there is no specific distinction between your 2 initial Feature Groups, then simply copy the reference of each individual layer into a new parent Feature Group and use the latter as Leaflet.draw featureGroup option:

var fg = L.featureGroup();

photoLayerGroup.eachLayer(function (layer) {
  if (!layer instanceof L.LayerGroup) {
    fg.addLayer(layer);
  }
});

// Same for attLayerGroup.

new L.Control.Draw({
  edit: {
    featureGroup: fg
  }
});
```

Body:
How can i assign multiple the feature groups in edit control,

Assume we have two feature groups(It can be multiple),and we want to assign edit control to both groups.

This is groups,

var attLayerGroup = new L.FeatureGroup();
var photoLayerGroup = new L.FeatureGroup();

And this is, How i assign control to groups,

    var drawControl = map.addControl(new L.Control.Draw({
    edit: {
        featureGroup: photoLayerGroup,attLayerGroup,
        poly: {
            allowIntersection: true
        }
    },
    draw: {
        polygon: {
            allowIntersection: false,
            showArea: true
        }

    }
}));

Is it right way to assigning Edit control to FeatureGroup ?
  If not,How can we do it?


问:
How to create a synonym where the dot dentifies row elements
I want to define this constants: Bool.True, Bool.False, and Bool.Null, to make more readable SQL queries.

One possibility is to create a table storing the values for true and false, and creating a synonym named "Bool", for the table, but then I cannot use "Bool.True", because that would  be a column named "True", instead of a specific value in a row.

Is there any way to do it, or something equivalent? (One possibility would be to create a package named "Bool", with functions named "True_", "False_", and "Null_")

答:
The package helps to clarify the meaning of "true_", but cannot enforce his use.

You could use object types and subtypes to do both, but it's not terribly pretty, particularly if this is only a simple example; but just to demonstrate:

```<code>create type bool as object (
  flag number(1)
)
not final not instantiable
/

create type bool_false under bool (
  constructor function bool_false return self as result
)
final
/
show errors;

create type body bool_false as
  constructor function bool_false return self as result is
  begin
    self.flag := 0;
    return;
  end;
end;
/

create type bool_true under bool (
  constructor function bool_true return self as result
) final
/

create type body bool_true as
  constructor function bool_true return self as result is
  begin
    self.flag := 1;
    return;
  end;
end;
/
</code>```

Then you can have a table with a column using the supertype (which isn't instantiable), and you can put instances of either type into it:

```<code>create table t42 (id number, bool_flag bool);
insert into t42 values (1, bool_true());
insert into t42 values (2, bool_false());
insert into t42 values (3, null);

select * from t42;

        ID BOOL_FLAG(FLAG)
---------- ---------------
         1 BOOL_TRUE(1)
         2 BOOL_FALSE(0)
         3

3 rows selected.
</code>```

or filter on it:

```<code>select * from t42 where bool_flag = bool_true();

        ID BOOL_FLAG(FLAG)
---------- ---------------
         1 BOOL_TRUE(1)

1 row selected.
</code>```

You can't create an index on the object-type column though, which might be an issue. You could have an FBI but then queries get even more complicated.

It would still be simpler to just use a scalar data type and check constraint, e.g. with a number:

```<code>create table t42 (id number, bool_flag number(1) check (bool_flag in (1,0)));
insert into t42 values (1, 1);
insert into t42 values (2, 0);
insert into t42 values (3, null);
</code>```

Or a single character, T?F or Y/N or whatever works for you:

```<code>create table t42 (id number, bool_flag varchar2(1) check (bool_flag in ('T','F')));
insert into t42 values (1, 'T');
insert into t42 values (2, 'F');
insert into t42 values (3, null);
</code>```

Or if you're really concerned that future developers will be confused about the meaning of T and F, you could even store whole words - at extra cost in terms of storage, of course:

```<code>create table t42 (id number, bool_flag varchar2(5) check (bool_flag in ('TRUE','FALSE')));
insert into t42 values (1, 'TRUE');
insert into t42 values (2, 'FALSE');
insert into t42 values (3, null);
</code>```

And if they're confused by true/false, they'll be equally confused by something like bool_true and bool_false...

Body:
The package helps to clarify the meaning of "true_", but cannot enforce his use.

You could use object types and subtypes to do both, but it's not terribly pretty, particularly if this is only a simple example; but just to demonstrate:

create type bool as object (
  flag number(1)
)
not final not instantiable
/

create type bool_false under bool (
  constructor function bool_false return self as result
)
final
/
show errors;

create type body bool_false as
  constructor function bool_false return self as result is
  begin
    self.flag := 0;
    return;
  end;
end;
/

create type bool_true under bool (
  constructor function bool_true return self as result
) final
/

create type body bool_true as
  constructor function bool_true return self as result is
  begin
    self.flag := 1;
    return;
  end;
end;
/

Then you can have a table with a column using the supertype (which isn't instantiable), and you can put instances of either type into it:

create table t42 (id number, bool_flag bool);
insert into t42 values (1, bool_true());
insert into t42 values (2, bool_false());
insert into t42 values (3, null);

select * from t42;

        ID BOOL_FLAG(FLAG)
---------- ---------------
         1 BOOL_TRUE(1)
         2 BOOL_FALSE(0)
         3

3 rows selected.

or filter on it:

select * from t42 where bool_flag = bool_true();

        ID BOOL_FLAG(FLAG)
---------- ---------------
         1 BOOL_TRUE(1)

1 row selected.

You can't create an index on the object-type column though, which might be an issue. You could have an FBI but then queries get even more complicated.

It would still be simpler to just use a scalar data type and check constraint, e.g. with a number:

create table t42 (id number, bool_flag number(1) check (bool_flag in (1,0)));
insert into t42 values (1, 1);
insert into t42 values (2, 0);
insert into t42 values (3, null);

Or a single character, T?F or Y/N or whatever works for you:

create table t42 (id number, bool_flag varchar2(1) check (bool_flag in ('T','F')));
insert into t42 values (1, 'T');
insert into t42 values (2, 'F');
insert into t42 values (3, null);

Or if you're really concerned that future developers will be confused about the meaning of T and F, you could even store whole words - at extra cost in terms of storage, of course:

create table t42 (id number, bool_flag varchar2(5) check (bool_flag in ('TRUE','FALSE')));
insert into t42 values (1, 'TRUE');
insert into t42 values (2, 'FALSE');
insert into t42 values (3, null);

And if they're confused by true/false, they'll be equally confused by something like bool_true and bool_false...


问:
Any reason I shoudn't add GUID validation to my Visual C++ program?
In order to make my Visual C++ program more robust I'm tempted to insert checks that GUID variables contain valid version 4 GUIDs (and are not left uninitialized):

```<code>GUID guid;
UuidCreate( &guid );
// many lines of code later...
// the following assert should not fire for valid version 4 GUIDs
int data3 = guid.Data3;
assert( ( data3 >> 12 ) == 4 );
</code>```

I'm completely sure that all GUIDs will either normally come from within UuidCreate() function or be uninitialized variables (and the latter is what I'd like to diagnose with those checks). My only concern is Microsoft could suddenly change GUID implementation in future versions of Windows.

What other factors should I consider to decide whether such checks won't hurt? Also how likely is it that GUID implementation changes on future versions of Windows?

答:
My only concern is Microsoft could suddenly change GUID implementation in future versions of Windows.

Deal with it, if it happens. No, seriously, you could also worry about the implementation of integer, Microsoft could decide to switch to the .NET datatypes and make the integer system-wide a 4-byte value.

Worry about other things, if implementations are changing, you'll have to rewrite/change/fix your program anyway.

Edit: If I understand you right, you're worrying about the return value of the function, not the GUID-Structure itself. And you mean that at the moment it can return either a GUID or the uninitialized value, but in future implementations it might return a 0-filled-GUID?

In that case I stick to my first paragraph, worry about it if it happens. At the moment the function has a clearly defined behavior, work with that. Check for uninitialized values and that's it. You can't guess what Microsoft will do in the future (hell, sometimes even Microsoft can't).

Body:
In order to make my Visual C++ program more robust I'm tempted to insert checks that GUID variables contain valid version 4 GUIDs (and are not left uninitialized):

GUID guid;
UuidCreate( &guid );
// many lines of code later...
// the following assert should not fire for valid version 4 GUIDs
int data3 = guid.Data3;
assert( ( data3 >> 12 ) == 4 );

I'm completely sure that all GUIDs will either normally come from within UuidCreate() function or be uninitialized variables (and the latter is what I'd like to diagnose with those checks). My only concern is Microsoft could suddenly change GUID implementation in future versions of Windows.

What other factors should I consider to decide whether such checks won't hurt? Also how likely is it that GUID implementation changes on future versions of Windows?


问:
How to know if docker is already logged in to a docker registry server
I'm not sure if I have already logged in to a docker registry in cmd line by using cmd: docker login. How can you test or see whether you are logged in or not, without trying to push?</p>

答:
For private registries, nothing is shown in docker info. However, the logout command will tell you if you were logged in:

```<code> $ docker logout private.example.com
 Not logged in to private.example.com
</code>```

(Though this will force you to log in again.)

Body:
For private registries, nothing is shown in docker info. However, the logout command will tell you if you were logged in:

 $ docker logout private.example.com
 Not logged in to private.example.com

(Though this will force you to log in again.)


问:
How to hide bootstrap hamburger icon onclick/tap?
How do I hide the hamburger icon when a user clicks or taps the icon on mobile? I assume I have to set it to display: none, but not sure how to do it with JavaScript. Don't worry, for usability I have the close button on the mobile drop menu. Is there an easy way to do this? I have googled but haven't been able to find anything.</p>

答:
Based on what you're asking, I'll just make a guess that you want to hide an element when a user clicks on it. I'd rather use jQuery:</p>

```<code>$("[icon]").click(function(){
    $(this).hide();
});
</code>```

Body:
Based on what you're asking, I'll just make a guess that you want to hide an element when a user clicks on it. I'd rather use jQuery:

$("[icon]").click(function(){
    $(this).hide();
});


问:
generating column names iteratively in pandas
I have an 11 column Pandas DataFrame, df

```<code>Name aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk
</code>```

I want to rename the columns so that the new header is

```<code>Name type_1 type_2 type_3 type_4 type_5 expt_1 expt_2 expt_3 expt_4 expt_5
</code>```

I can use df.rename but I will have to manually type in the new names.

Can you tell me how I can change the names iteratively to type_* or expt_*? where

```<code>* = half the number of columns excluding the first one (Name)
</code>```

I ask this because I want to generalize this naming system to a large table with 1000 columns.

答:
Edit: this will be better suited to an arbitrary number of columns (either even or odd in number)

```<code># get length of df's columns
num_cols = len(list(df))

# generate range of ints for suffixes
# with length exactly half that of num_cols;
# if num_cols is even, truncate concatenated list later
# to get to original list length
rng = range(1, (num_cols / 2) + 1)

new_cols = ['Name'] + ['type_' + str(i) for i in rng] + ['expt_' + str(i) for i in rng]

# ensure the length of the new columns list is equal to the length of df's columns
df.columns = new_cols[:num_cols]
</code>```

Body:
I have an 11 column Pandas DataFrame, df

Name aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk

I want to rename the columns so that the new header is

Name type_1 type_2 type_3 type_4 type_5 expt_1 expt_2 expt_3 expt_4 expt_5

I can use df.rename but I will have to manually type in the new names.

Can you tell me how I can change the names iteratively to type_* or expt_*? where

* = half the number of columns excluding the first one (Name)

I ask this because I want to generalize this naming system to a large table with 1000 columns.

Body:
Edit: this will be better suited to an arbitrary number of columns (either even or odd in number)

# get length of df's columns
num_cols = len(list(df))

# generate range of ints for suffixes
# with length exactly half that of num_cols;
# if num_cols is even, truncate concatenated list later
# to get to original list length
rng = range(1, (num_cols / 2) + 1)

new_cols = ['Name'] + ['type_' + str(i) for i in rng] + ['expt_' + str(i) for i in rng]

# ensure the length of the new columns list is equal to the length of df's columns
df.columns = new_cols[:num_cols]


问:
spring-data-elasticsearch and update
i'm using spring-data-elasticsearch to do CRUD operations.

I have a custom Repository that extends ElasticsearchRepository.

Ultimately ElasticsearchRepository extends CrudRepository which implies updating an existing record is possible.

The question is, how do you accomplish this?  I haven't found a method called "update()"

I thought doing the following would work (code stolen from https://github.com/BioMedCentralLtd/spring-data-elasticsearch-sample-application)

```<code>    //create
    Book book = new Book();
    book.setId("123455");
    book.setName("Spring Data Elasticsearch");
    book.setVersion(System.currentTimeMillis());
    repository.save(book);

    //update
    book.setName("THIS IS A COMPLETELY NEW TITLE");
    repository.save(book);
</code>```

However the 2nd save throws an InvocationTargetException

Examining it with the debugger shows:

```<code>[book][0] [book][123455]: version conflict, current [1447792071681], provided [1447792071681]
</code>```

The Book object looks like:

```<code>@Document(indexName = "book",type = "book" , shards = 1, replicas = 0, indexStoreType = "memory", refreshInterval = "-1")
public class Book {

    @Id
    private String id;
    private String name;
    private Long price;
    @Version
    private Long version;

    public Map<Integer, Collection<String>> getBuckets() {
        return buckets;
    }

    public void setBuckets(Map<Integer, Collection<String>> buckets) {
        this.buckets = buckets;
    }

    @Field(type = FieldType.Nested)
    private Map<Integer, Collection<String>> buckets = new HashMap();

    public Book(){}

    public Book(String id, String name,Long version) {
        this.id = id;
        this.name = name;
        this.version = version;
    }

    getters and setters removed for space
</code>```

}

My Repository code is even simpler:

```<code>import org.springframework.data.elasticsearch.entities.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface BookRepository extends ElasticsearchRepository<Book, Long> {

}
</code>```

Do I have to provide an update method?

EDIT:

Nevermind.  I changed the update to:

```<code>    //update
    book.setName("THIS IS A COMPLETELY NEW TITLE");
    book.setVersion(System.currentTimeMillis());
    repository.save(book);
</code>```

and it updated the record.

答:
The second update fails because you're trying to update an entity whose version hasn't changed. The error message you're getting is ES telling you, "hey, you can't save the same version twice!" Try this:</p>

```<code>//create
Book book = new Book();
book.setId("123455");
book.setName("Spring Data Elasticsearch");
book.setVersion(System.currentTimeMillis());
repository.save(book);

//update
book.setName("THIS IS A COMPLETELY NEW TITLE");
book.setVersion(System.currentTimeMillis()); // you're saving a new version
repository.save(book);
</code>```

Title: spring-data-elasticsearch and update

Body:
i'm using spring-data-elasticsearch to do CRUD operations.

I have a custom Repository that extends ElasticsearchRepository.

Ultimately ElasticsearchRepository extends CrudRepository which implies updating an existing record is possible.

The question is, how do you accomplish this?  I haven't found a method called "update()"

I thought doing the following would work (code stolen from https://github.com/BioMedCentralLtd/spring-data-elasticsearch-sample-application)

    //create
    Book book = new Book();
    book.setId("123455");
    book.setName("Spring Data Elasticsearch");
    book.setVersion(System.currentTimeMillis());
    repository.save(book);

    //update
    book.setName("THIS IS A COMPLETELY NEW TITLE");
    repository.save(book);

However the 2nd save throws an InvocationTargetException

Examining it with the debugger shows:

[book][0] [book][123455]: version conflict, current [1447792071681], provided [1447792071681]

The Book object looks like:

@Document(indexName = "book",type = "book" , shards = 1, replicas = 0, indexStoreType = "memory", refreshInterval = "-1")
public class Book {

    @Id
    private String id;
    private String name;
    private Long price;
    @Version
    private Long version;

    public Map<Integer, Collection<String>> getBuckets() {
        return buckets;
    }

    public void setBuckets(Map<Integer, Collection<String>> buckets) {
        this.buckets = buckets;
    }

    @Field(type = FieldType.Nested)
    private Map<Integer, Collection<String>> buckets = new HashMap();

    public Book(){}

    public Book(String id, String name,Long version) {
        this.id = id;
        this.name = name;
        this.version = version;
    }

    getters and setters removed for space

}

My Repository code is even simpler:

import org.springframework.data.elasticsearch.entities.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface BookRepository extends ElasticsearchRepository<Book, Long> {

}

Do I have to provide an update method?

EDIT:

Nevermind.  I changed the update to:

    //update
    book.setName("THIS IS A COMPLETELY NEW TITLE");
    book.setVersion(System.currentTimeMillis());
    repository.save(book);

and it updated the record.

Body:
The second update fails because you're trying to update an entity whose version hasn't changed. The error message you're getting is ES telling you, "hey, you can't save the same version twice!" Try this:

//create
Book book = new Book();
book.setId("123455");
book.setName("Spring Data Elasticsearch");
book.setVersion(System.currentTimeMillis());
repository.save(book);

//update
book.setName("THIS IS A COMPLETELY NEW TITLE");
book.setVersion(System.currentTimeMillis()); // you're saving a new version
repository.save(book);


问:
scala: missing parameter type for expanded function: the argument types of an anonymous function must be fully known
I am new to scala and I have no idea at all what's wrong with my code:

I have some Future which may throw exception:

```<code>var clean: Future[Boolean];
</code>```

However, when I try to map

```<code>clean.map( b => {
  case true => Ok("success")
  case false => Ok("failed")
}).recover {
  case t => Ok("error: " + t)
}
</code>```

I get compile error specified in the title.. I totally have no idea where and/which part of my code exactly causes it.. I have googled but it is so difficult to find any clue because scala syntax is so flexible thus so many variations in the internet but the error I get is quite misleading...

Any help will be very appreciated...

答:
The function you are passing to .map as written is supposed to accept a boolean argument b, and return another function (the stuff in curly braces). The compiler cannot guess the type of that inner function, so it complains about the parameter type not being known.

That's actually a good thing, because it's not what you really wanted to write at all.

Just remove the whole (b => ...) business:

```<code>clean.map {
  case true => Ok("success")
  case false => Ok("failed")
}.recover {
  case t => Ok("error: " + t)
}
</code>```

Also, make clean val rather than var. Mutable variables aren't a good idea. 99% of time, writing code in scala, you should not need them, so, I'd recommend that you just pretend that var keyword doesn't exist at all for now, until you learn the language well enough to be able to identify that 1% of cases where mutable state is actually needed.

Body:
I am new to scala and I have no idea at all what's wrong with my code:

I have some Future which may throw exception:

var clean: Future[Boolean];

However, when I try to map

clean.map( b => {
  case true => Ok("success")
  case false => Ok("failed")
}).recover {
  case t => Ok("error: " + t)
}

I get compile error specified in the title.. I totally have no idea where and/which part of my code exactly causes it.. I have googled but it is so difficult to find any clue because scala syntax is so flexible thus so many variations in the internet but the error I get is quite misleading...

Any help will be very appreciated...

Body:
The function you are passing to .map as written is supposed to accept a boolean argument b, and return another function (the stuff in curly braces). The compiler cannot guess the type of that inner function, so it complains about the parameter type not being known.

That's actually a good thing, because it's not what you really wanted to write at all.

Just remove the whole (b => ...) business:

clean.map {
  case true => Ok("success")
  case false => Ok("failed")
}.recover {
  case t => Ok("error: " + t)
}

Also, make clean val rather than var. Mutable variables aren't a good idea. 99% of time, writing code in scala, you should not need them, so, I'd recommend that you just pretend that var keyword doesn't exist at all for now, until you learn the language well enough to be able to identify that 1% of cases where mutable state is actually needed.


问:
Copy files to same directory with another name
I need to copy all html files inside the same directory with another name and I need to navigate all directories inside the source directory.

Here is my code so far,

```<code>import os
import shutil
os.chdir('/')

dir_src = ("/home/winpc/test/copy/")

for filename in os.listdir(dir_src):
    if filename.endswith('.html'):
        shutil.copy( dir_src + filename, dir_src)
    print(filename)
</code>```

答:
Solution

```<code>import os
import shutil

def navigate_and_rename(src):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        if os.path.isdir(s):
            navigate_and_rename(s)
        else if s.endswith(".html"):
            shutil.copy(s, os.path.join(src, "newname.html"))

dir_src = "/home/winpc/test/copy/"
navigate_and_rename(dir_src)
</code>```

Explanation

Navigate all files in source folder including subfolders

```<code>import os
def navigate(src):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        if os.path.isdir(s):
            navigate(s)
        else:
            # Do whatever to the file
</code>```

Copy to the same folder with new name

```<code>import shutil
shutil.copy(src_file, dst_file)
</code>```

Reference

Checkout my answer to another question.

Body:
I need to copy all html files inside the same directory with another name and I need to navigate all directories inside the source directory.

Here is my code so far,

import os
import shutil
os.chdir('/')

dir_src = ("/home/winpc/test/copy/")

for filename in os.listdir(dir_src):
    if filename.endswith('.html'):
        shutil.copy( dir_src + filename, dir_src)
    print(filename)

Body:
Solution

import os
import shutil

def navigate_and_rename(src):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        if os.path.isdir(s):
            navigate_and_rename(s)
        else if s.endswith(".html"):
            shutil.copy(s, os.path.join(src, "newname.html"))

dir_src = "/home/winpc/test/copy/"
navigate_and_rename(dir_src)

Explanation

Navigate all files in source folder including subfolders

import os
def navigate(src):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        if os.path.isdir(s):
            navigate(s)
        else:
            # Do whatever to the file

Copy to the same folder with new name

import shutil
shutil.copy(src_file, dst_file)

Reference

Checkout my answer to another question.