问:
What is the different?
I can't find the different between these codes as below:

1. Sample 1

```<code>modules = ["os", "sys", "random"]
def intersection_sets(modules):
    #for module in modules:
    sets = [set(dir(__import__(module))) for module in modules]
    return set.intersection(*sets)

a = intersection_sets(modules)
print(a)
</code>```

2. Sample 2

```<code>print(100*"=")
modules = ['os', 'sys', 'random']

def intersection_sets(modules):
    sets = [set(dir(__import__(module))) for module in modules]
    return set.intersection(*sets)

print(intersection_sets(modules))
</code>```

答:
Both code samples achieve the same result/output with two slight differences.

The first difference is in the modules list. With Python, you can write strings with single quotes or with double quotes. It does not matter as long as you close with the same symbol as you open with. You can also mix them like this:

```<code>modules = ['os', "sys", 'random']
</code>```

The second difference is how you are printing the result of the function. When you call a function with a return value, the function call itself becomes equal to the return. So you could save it to a variable and print the variable as shown in sample 1, or you could just print it directly without saving it as shown in sample 2.

Title: What is the different?

Body:
I can't find the different between these codes as below:

1. Sample 1

modules = ["os", "sys", "random"]
def intersection_sets(modules):
    #for module in modules:
    sets = [set(dir(__import__(module))) for module in modules]
    return set.intersection(*sets)

a = intersection_sets(modules)
print(a)

2. Sample 2

print(100*"=")
modules = ['os', 'sys', 'random']

def intersection_sets(modules):
    sets = [set(dir(__import__(module))) for module in modules]
    return set.intersection(*sets)

print(intersection_sets(modules))

Body:
Both code samples achieve the same result/output with two slight differences.

The first difference is in the modules list. With Python, you can write strings with single quotes or with double quotes. It does not matter as long as you close with the same symbol as you open with. You can also mix them like this:

modules = ['os', "sys", 'random']

The second difference is how you are printing the result of the function. When you call a function with a return value, the function call itself becomes equal to the return. So you could save it to a variable and print the variable as shown in sample 1, or you could just print it directly without saving it as shown in sample 2.


来源: stackexchange

问:
Cannot link library when compiling with gcc
My directory structure is:

```<code>── bin
│   ├── mylib-osx.so.1.72
│   ├── mylib.so.1.72
├── my.c
</code>```

I am trying to compile my.c and link mylib-osx.so.1.72 (I'm on a macOS), but to no avail:

```<code>ld: library not found for -l:PhotoDNAx64.so.1.72
</code>```

I tried:

gcc -o my -lmylib-osx my.c

gcc -o my -lmylib-osx.so.1.72 my.c

gcc -o my -lmylib my.c

gcc -o my -L./bin -lmylib-osx my.c

gcc -o my -L./bin -l:"mylib-osx.so.1.72" my.c

What am I doing wrong and why cannot the library be found?

答:
What am I doing wrong and why cannot the library be found?

Read about Invoking GCC. You was wrong in not reading that (or any other documentation of gcc).

Order of program arguments to gcc matters a lot (and in practice several arguments are very useful, e.g. both -Wall and -g at least, and probably -v sometimes). You want something like

```<code>gcc -v -Wall -g my.c -lmylib-osx -o my
</code>```

(also try variants of that), since gcc is running some ld or equivalent linker command, and if you want to pass some -Llib-directory use something like

```<code>gcc -v -Wall -g my.c  -L./bin -lmylib-osx -o my
</code>```

and you also need to read the documentation of MacOSX linker (probably named  ld). You could also read Levine's Linkers and loaders book.

If you are not happy with gcc (but please use a recent version, so GCC 8 in 2019, not the crappy software sold by Apple named gcc) consider using Clang (a recent version too, e.g. Clang 8 in 2019). It has the same limitation regarding order of program arguments than gcc does (since order of program arguments even mattered for Unix or POSIX cc).

In general, read the documentation of a command before asking questions here about that command. A minima, man gcc on your Apple (or Linux) computer.

PS. The last time I have used some MacOSX was in 2004. My biased recommendation is to install and use Linux (which I use since 1993; I tried MacOSX around 2004 during less than a year, and have been disappointed both by the operating system, including its display server and GUI desktop environment, and by the Apple hardware).

ContentLicense: CC BY-SA 4.0

Body:
My directory structure is:

── bin
│   ├── mylib-osx.so.1.72
│   ├── mylib.so.1.72
├── my.c

I am trying to compile my.c and link mylib-osx.so.1.72 (I'm on a macOS), but to no avail:

ld: library not found for -l:PhotoDNAx64.so.1.72

I tried:

gcc -o my -lmylib-osx my.c

gcc -o my -lmylib-osx.so.1.72 my.c

gcc -o my -lmylib my.c

gcc -o my -L./bin -lmylib-osx my.c

gcc -o my -L./bin -l:"mylib-osx.so.1.72" my.c

What am I doing wrong and why cannot the library be found?

Body:
What am I doing wrong and why cannot the library be found?

Read about Invoking GCC. You was wrong in not reading that (or any other documentation of gcc).

Order of program arguments to gcc matters a lot (and in practice several arguments are very useful, e.g. both -Wall and -g at least, and probably -v sometimes). You want something like

gcc -v -Wall -g my.c -lmylib-osx -o my

(also try variants of that), since gcc is running some ld or equivalent linker command, and if you want to pass some -Llib-directory use something like

gcc -v -Wall -g my.c  -L./bin -lmylib-osx -o my

and you also need to read the documentation of MacOSX linker (probably named  ld). You could also read Levine's Linkers and loaders book.

If you are not happy with gcc (but please use a recent version, so GCC 8 in 2019, not the crappy software sold by Apple named gcc) consider using Clang (a recent version too, e.g. Clang 8 in 2019). It has the same limitation regarding order of program arguments than gcc does (since order of program arguments even mattered for Unix or POSIX cc).

In general, read the documentation of a command before asking questions here about that command. A minima, man gcc on your Apple (or Linux) computer.

PS. The last time I have used some MacOSX was in 2004. My biased recommendation is to install and use Linux (which I use since 1993; I tried MacOSX around 2004 during less than a year, and have been disappointed both by the operating system, including its display server and GUI desktop environment, and by the Apple hardware).


问:
select with index on DataTable?
After I get DataTable from sqlAdapter I'm closing connection.
If I preform SELECT from this DataTable, does the select use the index
I created in the DB?

what code do I need to write for using the index?

答: If I understand your question, you want to know if the index that's defined in the DB will be present in the DataTable?  Unfortunately the answer is no, the DataTable is separate from the database.</p>

ContentLicense: CC BY-SA 3.0

Title: select with index on DataTable?


问:
String list multiplication in Python
Beginner question:
If I have 2 lists containing only strings, how do I concatenate them in a third list containing all the elements + each element of one list + each element in the other list? I thought about for loops, but isn't there a more simple way to do it?
Example:

```<code>listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']

resulting list = ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun', 'catbinsun', 'catsunbin', 'catcat', 'catdog', 'dogbin', 'dogcat']
</code>```

EDIT: Thank you all for replies, but i didn't explain what I want to do well enough.
The number of string in each list should be indefinite, and every word has to be concatenated with every other word, but not only in the form "x + y".
I want also to concatenate it to the other words. Like u = x+y+z

答:
You can get this result with comparatively simple code if you use list comprehensions:</p>

```<code>listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']
result_list = listone + listtwo + [x + y for x in listone for y in listtwo]
</code>```

Title: String list multiplication in Python

Body:
Beginner question:
If I have 2 lists containing only strings, how do I concatenate them in a third list containing all the elements + each element of one list + each element in the other list? I thought about for loops, but isn't there a more simple way to do it?
Example:

listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']

resulting list = ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun', 'catbinsun', 'catsunbin', 'catcat', 'catdog', 'dogbin', 'dogcat']

EDIT: Thank you all for replies, but i didn't explain what I want to do well enough.
The number of string in each list should be indefinite, and every word has to be concatenated with every other word, but not only in the form "x + y".
I want also to concatenate it to the other words. Like u = x+y+z

Body:
You can get this result with comparatively simple code if you use list comprehensions:

listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']
result_list = listone + listtwo + [x + y for x in listone for y in listtwo]


问:
How can I resolve "Your requirements could not be resolved to an installable set of packages" error?
When I run composer update I receive some wired output.

Here is my composer.json look like.

```<code>{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.", "keywords": ["framework", "laravel"],
    "license": "MIT",
    "repositories": [{
        "type": "vcs",
        "url": "https://github.com/Zizaco/ardent.git"
    }],
    "require-dev": {
        "phpunit/phpunit": "4.3.*"
    },
    "require": {
        "laravel/framework": "4.2.*",
        "laravelbook/ardent": "dev-master as 2.4.0",
        "zizaco/entrust": "dev-master",
        "sebklaus/profiler": "dev-master",
        "doctrine/dbal": "dev-master"
    },
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations", "app/database/seeds", "app/tests",
            "app/libraries"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "stable"
}
</code>```

How do I fix that ?

答:
CAUSE:

The error is happening because your project folder is owned by the root user.

SOLUTION

Change ownership to the currently signed in user and not the root user. If you only have root as the sole user, create another user with root privileges.

$ sudo chown -R current_user /my/project/directory/

then

$ composer install

Body:
When I run composer update I receive some wired output.

Here is my composer.json look like.

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.", "keywords": ["framework", "laravel"],
    "license": "MIT",
    "repositories": [{
        "type": "vcs",
        "url": "https://github.com/Zizaco/ardent.git"
    }],
    "require-dev": {
        "phpunit/phpunit": "4.3.*"
    },
    "require": {
        "laravel/framework": "4.2.*",
        "laravelbook/ardent": "dev-master as 2.4.0",
        "zizaco/entrust": "dev-master",
        "sebklaus/profiler": "dev-master",
        "doctrine/dbal": "dev-master"
    },
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations", "app/database/seeds", "app/tests",
            "app/libraries"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "stable"
}

How do I fix that ?


问:
How to create this signup form - NativeScript GridView
I am new to NativeScript, and am overwhelmed at the moment.

I am trying to get this layout (pictured below) just in a skeleton form, so I can learn and fill in the details.

Starting at the top, it appears I need a grid of 8 rows, and 2 columns.

```<code>  <GridLayout rows="*, auto" columns="250, *">
    <Label text="First Name" />
    <Label text="Middle Initial" col="1" />

<TextField hint="First Name"
        secure="false"
        autocorrect="false"
        maxLength="10"
        class="input input-border"/>

    <TextField hint="Middle Initial"
        secure="false"
        autocorrect="false"
        maxLength="1"
        class="input input-border"/>

<!-- continue... -->

    <Label text="This is Label in row 0, col 0" rowSpan="2" colSpan="2" />
  </GridLayout>
</Page>
</code>```

This method is not working. The layout does not reflect what I need in the image.

Can you please help me to at least rough out this layout? I am having a heck of a time.

Thank you for looking.

答:
Your form may look something like this,

```<code> <ScrollView>
    <StackLayout class="form">
        <Label class="m-5 h2" text="1. Lets create your account"></Label>
        <GridLayout columns="*,*">
            <StackLayout col="0" class="m-5">
                <Label text="First Name"></Label>
                <TextField class="input input-border"></TextField>
            </StackLayout>
            <StackLayout col="1" class="m-5">
                <Label text="Last Name"></Label>
                <TextField class="input input-border"></TextField>
            </StackLayout>
        </GridLayout>
        <GridLayout columns="*,*">
            <StackLayout col="0" class="m-5">
                <Label text="Email Address"></Label>
                <TextField class="input input-border"></TextField>
            </StackLayout>
            <StackLayout col="1" class="m-5">
                <Label text="Birth month and year"></Label>
                <TextField class="input input-border"></TextField>
            </StackLayout>
        </GridLayout>
    </StackLayout>
</ScrollView>
</code>```

Learn more about layouts at https://www.nslayouts.com/

Body:
I am new to NativeScript, and am overwhelmed at the moment.

I am trying to get this layout (pictured below) just in a skeleton form, so I can learn and fill in the details.

Starting at the top, it appears I need a grid of 8 rows, and 2 columns.

  <GridLayout rows="*, auto" columns="250, *">

<TextField hint="First Name"
        secure="false"
        autocorrect="false"
        maxLength="10"
        class="input input-border"/>

    <TextField hint="Middle Initial"
        secure="false"
        autocorrect="false"
        maxLength="1"
        class="input input-border"/>

  </GridLayout>
</Page>

This method is not working. The layout does not reflect what I need in the image.

Can you please help me to at least rough out this layout? I am having a heck of a time.

Thank you for looking.

Body:
Your form may look something like this,

 <ScrollView>
    <StackLayout class="form">
        <Label class="m-5 h2" text="1. Lets create your account"></Label>
        <GridLayout columns="*,*">
            <StackLayout col="0" class="m-5">
                <Label text="First Name"></Label>
                <TextField class="input input-border"></TextField>
            </StackLayout>
            <StackLayout col="1" class="m-5">
                <Label text="Last Name"></Label>
                <TextField class="input input-border"></TextField>
            </StackLayout>
        </GridLayout>
        <GridLayout columns="*,*">
            <StackLayout col="0" class="m-5">
                <Label text="Email Address"></Label>
                <TextField class="input input-border"></TextField>
            </StackLayout>
            <StackLayout col="1" class="m-5">
                <Label text="Birth month and year"></Label>
                <TextField class="input input-border"></TextField>
            </StackLayout>
        </GridLayout>
    </StackLayout>
</ScrollView>

Learn more about layouts at https://www.nslayouts.com/


问:
Issue on delete record from SQL Server database through C# program
I'm new to C# programming. I've written a program in C# which has been connected to a SQL Server database through LINQ connector. Everything ran smoothly. But now I get below error when I want to delete a record from program with a specific condition:

An unhandled exception of type 'System.ArgumentNullException' occurred in EntityFramework.dll

Additional information: Value cannot be null.

This is my C# code:

```<code>private void btnDel_Click(object sender, EventArgs e)
{
    DialogResult result = MessageBox.Show("Sales system ", "Are you sure to delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

    if (result == DialogResult.Yes)
    {
        string photo = txtPhoto.ToString();

        var edit = db.tblPersons.Where(c => c.PhotoNo == photo || c.ReceiptNo == photo).FirstOrDefault();
        db.tblPersons.Remove(edit);
        db.SaveChanges();

        MessageBox.Show("Info deleted");
    }
}
</code>```

Does anyone know about my issue in this occasion?

答:
You should check if your var edit is not null before try to remove

private void btnDel_Click(object sender, EventArgs e)   {
        DialogResult result = MessageBox.Show("Sales system ", "Are you sure to delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (result == DialogResult.Yes)
        {
            string photo = txtPhoto.ToString();

            var edit = db.tblPersons.Where(c => c.PhotoNo == photo || c.ReceiptNo == photo).FirstOrDefault();
            if(edit != null)
            {
              db.tblPersons.Remove(edit);
              db.SaveChanges();
              MessageBox.Show("Info deleted");
            }
            else
            {
             MessageBox.Show(photo + " Incorrect");
            }
        }
    }
```

Body:
I'm new to C# programming. I've written a program in C# which has been connected to a SQL Server database through LINQ connector. Everything ran smoothly. But now I get below error when I want to delete a record from program with a specific condition:

An unhandled exception of type 'System.ArgumentNullException' occurred in EntityFramework.dll

Additional information: Value cannot be null.

This is my C# code:

private void btnDel_Click(object sender, EventArgs e)
{
    DialogResult result = MessageBox.Show("Sales system ", "Are you sure to delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

    if (result == DialogResult.Yes)
    {
        string photo = txtPhoto.ToString();

        var edit = db.tblPersons.Where(c => c.PhotoNo == photo || c.ReceiptNo == photo).FirstOrDefault();
        db.tblPersons.Remove(edit);
        db.SaveChanges();

        MessageBox.Show("Info deleted");
    }
}

Does anyone know about my issue in this occasion?


问:
Maven: download artifact and its deps to a specific directory
I must be missing something.  I have searched and searched, and played and tinkered, and I still can't figure out how to do the following with Maven:

I would like to download an artifact and all its dependencies (and transitive dependencies), from our internal Nexus server, into a user-specified location.  The idea here is to allow the person who is deploying the solution into production a way that they can easily get all the jar files they need in one place.

There is dependency:get, and this is close-but-no-cigar.  With dependency:get, all the artifacts are downloaded into the local mvn repository, under directories according to each artifact's groupId and artifactId.  This is NOT what I want, because then you have to trudge around all those directories to get at the jars.  I want all the files downloaded to one directory so that they are in one place.

Then there is dependency:copy-dependencies.  This again does almost what I want; it copies all of an artifact's deps into target/dependency.  The two problems with this are 1) You need to have a pom.xml; you can't specify arbitrary coordinates like you can with dependency:get, and 2) dependency:copy-dependencies does't copy the main artifact itself into target/dependencies.

There must be a better way to do this, but I can't figure out where else to look for a solution.  To summarize, I want to be able to given someone a set of maven coordinates (groupId:artifactId:version) and our internal Nexus URL, and have them download everything with one command into a directory of their choosing.

答:
You can combine the use of dependency:copy and dependency:copy-dependencies to achieve your goal.

The idea is simple:

Use dependency:copy to fetch the pom.xml of your starting artifact.

Use dependency:copy-dependencies feeding it the pom.xml you fetched in the previous step to fetch all of the starting artifact's dependencies.

Use dependency:copy again to fetch the starting artifact itself.

#!/bin/sh

if [ "$#" -ne 2 ]; then
    echo "Usage: $(basename $0) <artifact> <directory>" > /dev/stderr
    exit 1
fi

ARTIFACT="$1"
OUTPUT="$2"

mkdir -p "$OUTPUT"

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

mvn dependency:copy              "-DoutputDirectory=${TMP}"    "-Dartifact=${ARTIFACT}:pom"

POM=$(find "$TMP" -type f)

mvn dependency:copy              "-DoutputDirectory=${OUTPUT}" "-Dartifact=${ARTIFACT}"
mvn dependency:copy-dependencies "-DoutputDirectory=${OUTPUT}" -f "$POM" -DincludeScope=runtime
```

<p>Save as <code>download-jars</code> and use like this:</p>

<pre class="lang-sh prettyprint-override"><code>download-jars org.apache.hadoop:hadoop-aws:2.7.3 /tmp/jars
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can combine the use of dependency:copy and dependency:copy-dependencies to achieve your goal.

The idea is simple:

Use dependency:copy to fetch the pom.xml of your starting artifact.

Use dependency:copy-dependencies feeding it the pom.xml you fetched in the previous step to fetch all of the starting artifact's dependencies.

Use dependency:copy again to fetch the starting artifact itself.

#!/bin/sh

if [ "$#" -ne 2 ]; then
    echo "Usage: $(basename $0) <artifact> <directory>" > /dev/stderr
    exit 1
fi

ARTIFACT="$1"
OUTPUT="$2"

mkdir -p "$OUTPUT"

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

mvn dependency:copy              "-DoutputDirectory=${TMP}"    "-Dartifact=${ARTIFACT}:pom"

POM=$(find "$TMP" -type f)

mvn dependency:copy              "-DoutputDirectory=${OUTPUT}" "-Dartifact=${ARTIFACT}"
mvn dependency:copy-dependencies "-DoutputDirectory=${OUTPUT}" -f "$POM" -DincludeScope=runtime

Save as download-jars and use like this:

download-jars org.apache.hadoop:hadoop-aws:2.7.3 /tmp/jars


问:
mongoose - array of subdocument are not saved in parent document
I'm trying to push subdocuments into a parent document using push() method.
After that, I want to save the parent document calling save() method on it. But the result is an empty array.

I've also tried to call parent.markModified('children') before saving the parent doc, but it makes no difference.

Below is my Schemas and the code that should save the subdocuments :

Schema :

const profileSessionSchema = mongoose.Schema({
    firstName: { type: String, trim:true},
...
   realisations : [realisationSchema],
 });
ProfileSession = mongoose.model('ProfileSession',profileSessionSchema);

const realisationSchema = mongoose.Schema({
   profileId :{ type: mongoose.Schema.Types.ObjectId, ref: 'ProfileSession'},
   ...
   type : { type: String, enum:conf.wallTypes, required:true, default:'classic'},
});
Realisation = mongoose.model('Realisation', realisationSchema);

```

<pre class="lang-js prettyprint-override"><code>ProfileSession.create(profileData,function(err,profile){
   for(j=0;j<realisations.length;j++){  // realisations array is not empty
     var r = Realisation(realisations[j])
     r.save(function(a,real){
        profile.realisations.push(real)
     })
   }

   profile.markModified('realisations')
   profile.save()
})
</code>```

The profile document is indeed created in DB, but without the realisations subdocuments. I've found plenty of subjects about this, and it appears that the method markModified should solve the issue. But it does not in my case and I can't understand why...

Thank you for you help.
Cheers

答:
If you are actually trying to create new Realisation then you would need to use the keyword to create a new model from the schema:

```<code>ProfileSession.create(profileData,function(err,profile){
   for(j=0;j<realisations.length;j++){  // realisations array is not empty
     var r = new Realisation(realisations[j])  // <-- use new
     r.save(function(a,real){
        profile.realisations.push(real)
     })
   }

   profile.markModified('realisations')
   profile.save()
})
</code>```

Body:
I'm trying to push subdocuments into a parent document using push() method.
After that, I want to save the parent document calling save() method on it. But the result is an empty array.

I've also tried to call parent.markModified('children') before saving the parent doc, but it makes no difference.

Below is my Schemas and the code that should save the subdocuments :

Schema :

const profileSessionSchema = mongoose.Schema({
    firstName: { type: String, trim:true},
...
   realisations : [realisationSchema],
 });
ProfileSession = mongoose.model('ProfileSession',profileSessionSchema);

const realisationSchema = mongoose.Schema({
   profileId :{ type: mongoose.Schema.Types.ObjectId, ref: 'ProfileSession'},
   ...
   type : { type: String, enum:conf.wallTypes, required:true, default:'classic'},
});
Realisation = mongoose.model('Realisation', realisationSchema);

ProfileSession.create(profileData,function(err,profile){
   for(j=0;j<realisations.length;j++){  // realisations array is not empty
     var r = Realisation(realisations[j])
     r.save(function(a,real){
        profile.realisations.push(real)
     })
   }

   profile.markModified('realisations')
   profile.save()
})

The profile document is indeed created in DB, but without the realisations subdocuments. I've found plenty of subjects about this, and it appears that the method markModified should solve the issue. But it does not in my case and I can't understand why...

Thank you for you help.
Cheers

Body:
If you are actually trying to create new Realisation then you would need to use the keyword to create a new model from the schema:

ProfileSession.create(profileData,function(err,profile){
   for(j=0;j<realisations.length;j++){  // realisations array is not empty
     var r = new Realisation(realisations[j])  // <-- use new
     r.save(function(a,real){
        profile.realisations.push(real)
     })
   }

   profile.markModified('realisations')
   profile.save()
})


问:
Need to add 0 to match the length
I have unique identifiers for each row. For example 19Jan187938 or 19Jan206414 but there are some which are like 19Jan17333. I need to add a 0 before the number if it's 5 digits, so it becomes 19Jan017333.

I tried,

```<code>=TEXT(CONCATENATE(19,AB2,C2),"000000")
</code>```

even with 11 0's, since the total length is 11. Nothing changes.

答:
If your identifier is on A1, you can try this:

```<code>=IF(LEN(A1)<11;CONCATENATE(LEFT(A1;5);RIGHT("000000"&MID(A1;6;5);6));A1)
</code>```

See what happens.

Title: Need to add 0 to match the length

Body:
I have unique identifiers for each row. For example 19Jan187938 or 19Jan206414 but there are some which are like 19Jan17333. I need to add a 0 before the number if it's 5 digits, so it becomes 19Jan017333.

I tried,

=TEXT(CONCATENATE(19,AB2,C2),"000000")

even with 11 0's, since the total length is 11. Nothing changes.

Body:
If your identifier is on A1, you can try this:

=IF(LEN(A1)<11;CONCATENATE(LEFT(A1;5);RIGHT("000000"&MID(A1;6;5);6));A1)

See what happens.


问:
Access property/environment variables without launching Eclipse?
I want to set the log4j configuration file path/other folder paths that can be used across other class files, without hard-coding the folder path.

Rightnow, I have set the variables as Environment variable. But It can only be modified if I launch Eclipse. How do I set this variable in such away that anyone (doesn't want to launch Eclipse) can modify it, from outside. Also, it will be used in test configurations. So it's better to not hard-code it and have all the file paths etc. easy to refactor.

```<code>final static String log4jpath = System.getenv("LOG4J_PATH");
</code>```

答:
Soni, If you want to put the log4j configuration file in one place so that everybody can access. Follow the steps.

Create a project with some name and inside src/main/resources folder keep the log4j configuration file.

Create a jar file which must contain this log4j configuration file.

Use this created jar file wherever it is required. Log4j will automatically use the configuration for desired logging. If you want, you can distribute this jar file to anybody who wants to use it.

The above option is if you do not want to change the configuration file.

Now if there is a situation where someone wants to modify the configuration file.
In this case, simply put the configuration in any project classpath, means inside resource folder. As long as log4j jar files are there in the classpath and configuration files. It will log everything.

However, if you want, you can extend the functionality of Log4j by passing configuration as an object. You can refer below the link to access pro grammatically.

https://howtodoinjava.com/log4j/how-to-programmatically-configure-appenders-in-log4j/

Body:
I want to set the log4j configuration file path/other folder paths that can be used across other class files, without hard-coding the folder path.

Rightnow, I have set the variables as Environment variable. But It can only be modified if I launch Eclipse. How do I set this variable in such away that anyone (doesn't want to launch Eclipse) can modify it, from outside. Also, it will be used in test configurations. So it's better to not hard-code it and have all the file paths etc. easy to refactor.

final static String log4jpath = System.getenv("LOG4J_PATH");


问:
Entity Framework Core : Access parent from child
Might be a silly question but I'm a bit confused here.

I have a parent entity which contains a list of children.

```<code>public class Parent
{
    public int Id { get; set; }

    public List<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
}
</code>```

EFcore will create a ParentId as a foreign key in the table Child.

Now, let's say I want to retrieve all the children that have a specific Parent, how should I do it ? The ParentId is not available in the Child object.

Therefore, I cannot do something like:

```<code>var result = model.Child.Where(child => child.ParentId == 3);
</code>```

I could add the ParentId property to the child in the entity, but I really don't want this property to be assigned manually. And if I set it as readonly by specifying the getter only, the migration doesn't work anymore.

答:
EF Core allows you to access the associated shadow property in LINQ to Entities query using the EF.Property method:

Addresses a given property on an entity instance. This is useful when you want to reference a shadow state property in a LINQ query. Currently this method can only be used in LINQ queries and can not be used to access the value assigned to a property in other scenarios.

All you need to know is the name and the type - in your case they are "ParentId" and int? (optional):

```<code>var result = model.Child.Where(child => EF.Property<int?>(child, "ParentId") == 3);
</code>```

Body:
Might be a silly question but I'm a bit confused here.

I have a parent entity which contains a list of children.

public class Parent
{
    public int Id { get; set; }

    public List<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
}

EFcore will create a ParentId as a foreign key in the table Child.

Now, let's say I want to retrieve all the children that have a specific Parent, how should I do it ? The ParentId is not available in the Child object.

Therefore, I cannot do something like:

var result = model.Child.Where(child => child.ParentId == 3);

I could add the ParentId property to the child in the entity, but I really don't want this property to be assigned manually. And if I set it as readonly by specifying the getter only, the migration doesn't work anymore.

Body:
EF Core allows you to access the associated shadow property in LINQ to Entities query using the EF.Property method:

Addresses a given property on an entity instance. This is useful when you want to reference a shadow state property in a LINQ query. Currently this method can only be used in LINQ queries and can not be used to access the value assigned to a property in other scenarios.

All you need to know is the name and the type - in your case they are "ParentId" and int? (optional):

var result = model.Child.Where(child => EF.Property<int?>(child, "ParentId") == 3);


问:
Error parsing JSON with escaped quotes inside single quotes
I have a variable var jsonData = '{"Key":"query","Value":"dept=\"Human Resources*\"","ValueType":"Edm.String"}';

I'm trying to parse the variable with JSON.parse(jsonData), however, I'm getting an error "Unexpected token H in JSON at position 30." I can't change how the variable is returned, so here's what I think I understand about the problem:

The JSON.parse(jsonData) errors out because it's not recognizing the escaped double quotes as escaped since it is fully enclosed in single quotes

jsonData.replace(/\\"/g, "\\\\"") or other combinations that I've tried aren't finding the \" because javascript treats \" as just "

QUESTION How can I parse this properly, by either replacing the escaped quotes with something JSON.parse() can handle or using something else to parse this correctly? I'd like to stick with JSON.parse() on account of it's simplicity, but open to other options.

EDIT: Unfortunately I can't change the variable at this stage, it is just a small example of a larger JSON response. This is a temporary solution until the app is granted access to the API, but I needed the solution in the interim until that happens (IT dept can be slow). What I'm doing now its getting a large JSON response back by hitting the API address directly and the browser uses the cookies from the user OAuth for authentication. I then copy and paste the JSON response into my application so I can work with the data. The response is riddled with the escaped quotes and manually editing the text would be laborious and I'm trying to avoid copying into text processor before copying into the variable.

答:
The unfortunate thing about this situation is that in the JavaScript code there is no difference between

var jsonData = '{"Key":"query","Value":"dept=\"Human Resources*\"","ValueType":"Edm.String"}'

and

var jsonData = '{"Key":"query","Value":"dept="Human Resources*"","ValueType":"Edm.String"}'.

You could hardcode information you have about the JSON into the way you program it. For example, you could replace occurences of the regex ([\[\{,:]\s+)\" by $1\" but this would fail to work if the string Human Resources* could also end in a :, { or ,. This would also potentially cause security issues.

In my opinion, the best way to solve your problem would be to put the json response in a json file somewhere so that it can be read into a string by the javascript code that needs to use it.


问:
How can I get the client's IP address in a PHP webservice?
I have developed a PHP webservice. I would like to log all incoming connections of the WS clients, which are consuming this web service. How can I obtain the client's IP address? The value of ```<code>$_SERVER['HTTP_CLIENT_IP']</code>```
seems to be always empty.</p>

答:
The functions getUserIpAddr() and getRealIpAddr() are not reliable!

The only reliable IP is from $ip = $_SERVER["REMOTE_ADDR"];
Otherwise anyone could fake his IP address by sending the CLIENT_IP header for example.

This Firefox Addon can help you send custom headers. Sending the CLIENT_IP=x.x.x.x header to a server running any of the functions on this page, would mean that clients can choose any IP they want...

Body:
I have developed a PHP webservice. I would like to log all incoming connections of the WS clients, which are consuming this web service. How can I obtain the client's IP address? The value of
$_SERVER['HTTP_CLIENT_IP']

seems to be always empty.


问:
Adding hours across the DST transition in moments
I'm trying to create a graph that has a vertical grid line (coming off the X axis) on every 0, 6am, midday and 6pm, using d3. I'm doing this by manually calculating the tick values in momentjs. I calculate the start of the day easily with

```<code> firstPoint = momenttz(startDate).startOf('day')
</code>```

And then add 6 hours to it in a loop.

```<code>for (let i = 0; i <= days * 24; i += 6) {
    hourTickValues.push(firstPoint.clone().add(i, 'hours'));
}
</code>```

When crossing into or out of daylight saving time I want to keep the lines at the local time of 6am, midday and 6pm. This will mean that twice a year the grid spacing will be different as there are only 5 hours between 12am and 6am going in to DST and 7 hours when coming out.

Momentjs's docs clearly state that when adding hours to a time it does not adjust for daylight saving, but when adding days it will. I've also discovered that adding fractional days does not work, it always rounds up to an integer.

So, how can I reliably create a (momentjs) date object for every 6th hour according the DST adjusting clock?

答:
I solved this by manually setting each time objects hour after creation.</p>

```<code>for (let i = 0; i <= days * 24; i += 6) {
    hourTickValues.push(firstPoint.clone().add(i, 'hours'));
    hourTickValues[hourTickValues length - 1].hours(i % 24);
}
</code>```

Body:
I'm trying to create a graph that has a vertical grid line (coming off the X axis) on every 0, 6am, midday and 6pm, using d3. I'm doing this by manually calculating the tick values in momentjs. I calculate the start of the day easily with

 firstPoint = momenttz(startDate).startOf('day')

And then add 6 hours to it in a loop.

for (let i = 0; i <= days * 24; i += 6) {
    hourTickValues.push(firstPoint.clone().add(i, 'hours'));
}

When crossing into or out of daylight saving time I want to keep the lines at the local time of 6am, midday and 6pm. This will mean that twice a year the grid spacing will be different as there are only 5 hours between 12am and 6am going in to DST and 7 hours when coming out.

Momentjs's docs clearly state that when adding hours to a time it does not adjust for daylight saving, but when adding days it will. I've also discovered that adding fractional days does not work, it always rounds up to an integer.

So, how can I reliably create a (momentjs) date object for every 6th hour according the DST adjusting clock?

Body:
I solved this by manually setting each time objects hour after creation.

for (let i = 0; i <= days * 24; i += 6) {
    hourTickValues.push(firstPoint.clone().add(i, 'hours'));
    hourTickValues[hourTickValues length - 1].hours(i % 24);
}


问:
Pyspark : How to pick the values till last from the first occurrence in an array based on the matching values in another column
I have an dataframe where I need to search a value present in one column i.e., StringType in another column i.e., ArrayType but I want to pick the values from the second column till last value in array from the first occurences of the first column.

Explained below with examples :

Input DF is below :

```<code>Employee_Name|Employee_ID|Mapped_Project_ID
Name1|E101|[E101, E102, E103]
Name2|E102|[E101, E102, E103]
Name3|E103|[E101, E102, E103, E104, E105]
</code>```

Output DF Should look like as below:

```<code>Employee_Name|Employee_ID|Mapped_Project_ID
Name1|E101|[E101, E102, E103]
Name2|E102|[E102, E103]
Name3|E103|[E103, E104, E105]
</code>```

答:
As of Spark 2.4 you can use array_position and slice functions:

```<code>import pyspark.sql.functions as f
from pyspark.sql.functions import array_position
from pyspark.sql.functions import slice

df = spark.createDataFrame([(["c", "b", "a","e","f"],'a')], ['arraydata','item'])

df.select(df.arraydata, f.expr("slice(arraydata,array_position(arraydata, item),size(arraydata))").alias("res")).show()

+---------------+---------+
|      arraydata|      res|
+---------------+---------+
|[c, b, a, e, f]|[a, e, f]|
+---------------+---------+
</code>```

Please just translate this into your df colnames. Hope this helps.

Body:
I have an dataframe where I need to search a value present in one column i.e., StringType in another column i.e., ArrayType but I want to pick the values from the second column till last value in array from the first occurences of the first column.

Explained below with examples :

Input DF is below :

Employee_Name|Employee_ID|Mapped_Project_ID
Name1|E101|[E101, E102, E103]
Name2|E102|[E101, E102, E103]
Name3|E103|[E101, E102, E103, E104, E105]

Output DF Should look like as below:

Employee_Name|Employee_ID|Mapped_Project_ID
Name1|E101|[E101, E102, E103]
Name2|E102|[E102, E103]
Name3|E103|[E103, E104, E105]

Body:
As of Spark 2.4 you can use array_position and slice functions:

import pyspark.sql.functions as f
from pyspark.sql.functions import array_position
from pyspark.sql.functions import slice

df = spark.createDataFrame([(["c", "b", "a","e","f"],'a')], ['arraydata','item'])

df.select(df.arraydata, f.expr("slice(arraydata,array_position(arraydata, item),size(arraydata))").alias("res")).show()

+---------------+---------+
|      arraydata|      res|
+---------------+---------+
|[c, b, a, e, f]|[a, e, f]|
+---------------+---------+

Please just translate this into your df colnames. Hope this helps.


问:
How to assign a class to divs based on a calulcated number
Is there a way to assign a class to a div based on a variable?

My example code:

```<code><button id="prev-item">Calculate</button>
<div class="main">
  <div class="item"><div class="current">item 1</div></div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  <div class="item">item 4</div>
  <div class="item">item 5</div>
  <div class="item">item 6</div>
  <div class="item">item 7</div>
  <div class="item">item 8</div>
  <div class="item">item 9</div>
  <div class="item">item 10</div>
</div>
</code>```

Example JS:

```<code>$("#prev-item").on("click", function(){
  var firstcal = $('.main').children().length;
  var actual = firstcal - 7
});
</code>```

The code I provided counts how many divs there are in .main and stores the number in firstcal and then actual takes the number in firstcal and subtracts 7 from it. In this example, it's 3.

I'm looking for a way to assign a class called .scroll to .items based on the number in the variable actual. So in this example, assign .scroll to the first three items in .main (item 1, item 2, item 3).

JS fiddle: https://jsfiddle.net/openbayou/xfa34qup/

答:
You can loop through it using .each which gets parameter index indicating the index of the element being loop then check if the iterating element index is less than the actual (maximum) index.

$("#prev-item").on("click", function(){
  var $children = $('.main').children();
  var firstcal = $children.length;
  var actual = firstcal - 7
  $( "span" ).text( actual );

  // reset for previously added class
  // $children.removeClass('scrollup')

  $children.each(function (i) {
    if (i < actual) {
      $(this).addClass('scrollup')
    }
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.current {color:red}
.item {padding: 7px}
.main {height:265px;overflow:auto}
.scrollup {border-left:5px solid blue}</code>```

<button id="prev-item">Calculate</button>

item 1

item 2

item 3

item 4

item 5

item 6

item 7

item 8

item 9

item 10

```

Body:
Is there a way to assign a class to a div based on a variable?

My example code:

<button id="prev-item">Calculate</button>

item 1

item 2

item 3

item 4

item 5

item 6

item 7

item 8

item 9

item 10

Example JS:

$("#prev-item").on("click", function(){
  var firstcal = $('.main').children().length;
  var actual = firstcal - 7
});

The code I provided counts how many divs there are in .main and stores the number in firstcal and then actual takes the number in firstcal and subtracts 7 from it. In this example, it's 3.

I'm looking for a way to assign a class called .scroll to .items based on the number in the variable actual. So in this example, assign .scroll to the first three items in .main (item 1, item 2, item 3).

JS fiddle: https://jsfiddle.net/openbayou/xfa34qup/

Body:
You can loop through it using .each which gets parameter index indicating the index of the element being loop then check if the iterating element index is less than the actual (maximum) index.

$("#prev-item").on("click", function(){
  var $children = $('.main').children();
  var firstcal = $children.length;
  var actual = firstcal - 7
  $( "span" ).text( actual );

  // reset for previously added class
  // $children.removeClass('scrollup')

  $children.each(function (i) {
    if (i < actual) {
      $(this).addClass('scrollup')
    }
  })
});

.current {color:red}
.item {padding: 7px}
.main {height:265px;overflow:auto}
.scrollup {border-left:5px solid blue}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<button id="prev-item">Calculate</button>
<div class="main">
  <div class="item"><div class="current">item 1</div></div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  <div class="item">item 4</div>
  <div class="item">item 5</div>
  <div class="item">item 6</div>
  <div class="item">item 7</div>
  <div class="item">item 8</div>
  <div class="item">item 9</div>
  <div class="item">item 10</div>
</div>
<span></span>


问:
How to fix constraints for allocation optimisation in PuLP python
Background:

I am trying to allocate customers Ci to financial advisers Pj. Each customer has a policy value xi. I'm assuming that the number of customers (n) allocated to each adviser is the same, and that the same customer cannot be assigned to multiple advisers. Therefore each partner will have an allocation of policy values like so:

P1=[x1,x2,x3] , P2=[x4,x5,x6], P3=[x7,x8,x9]

I am trying to find the optimal allocation to minimise dispersion in fund value between the advisers. I am defining dispersion as  the difference between the adviser with the highest fund value (z_max) and the lowest fund value (z_min).

The formulation for this problem is therefore:

where yij=1 if we allocate customer Ci to adviser Pj, 0 otherwise

The first constraint says that zmax has to be greater than or equal to each policy value; since the objective function encourages smaller values of zmax, this means that zmax will equal the largest policy value. Similarly, the second constraint sets zmin equal to the smallest policy value. The third constraint says that each customer must be assigned to exactly one adviser. The fourth says that each adviser must have n customers assigned to him/her. Credit: @LarrySnyder610

Problem:

When implementing this problem in PulP, I expect 1740 (n x p) customers to be allocated across the 173 advisers based on constraint 3 and 4. However 72036 and no optimal allocation is obtained.

import random
import pandas as pd
import pulp

=============================================================================
# SAMPLE DATA
=============================================================================

n = 10 # number of customers for each financial adviser
c = 414 #number of customers
p = 174 #number of financial adviser
policy_values = random.sample(range(1, 1000000), c)

set_I = range(c)
set_J = range(p)
set_N = range(n)
x = {i: policy_values[i] for i in set_I} #customer policy values
y = {(i,j): random.randint(0, 1) for i in set_I for j in set_J} # allocation dummies

model = pulp.LpProblem("Allocation Model", pulp.LpMinimize)

# =============================================================================
# DECISION VARIABLES
# =============================================================================

y_vars  = {(i,j): pulp.LpVariable(cat=pulp.LpBinary, name="y_{0}_{1}".format(i,j)) for i in set_I for j in set_J}
z_max = pulp.LpVariable("Max Policy Value", 0)
z_min = pulp.LpVariable("Min Policy Value", 0)

# =============================================================================
# OBJECTIVE FUNCTION
# =============================================================================

model += z_max - z_min

# =============================================================================
# CONSTRAINTS
# =============================================================================
model += {j: pulp.lpSum(y_vars[i,j] * x[i] for i in set_I) for j in set_J} <= z_max # constraint 1
model += {j: pulp.lpSum(y_vars[i,j] * x[i] for i in set_I) for j in set_J} >= z_min # constraint 2
model += {i: pulp.lpSum(y_vars[i,j] for j in set_J) for i in set_I} == 1 # constraint 3
model += {j: pulp.lpSum(y_vars[i,j] for i in set_I) for j in set_J} == n #constraint 4

# =============================================================================
# SOLVE MODEL
# =============================================================================

model.solve()
print('Optimised model status: '+str(pulp.LpStatus[model.status]))

count=0
for v in model.variables():
    if v.varValue == 1.0:
        count+=1
        #print(v.name, "=", v.varValue)
print(count)
#>>> 72036 # expecting 1740

print('Optimal difference between highest and lowest summed policy_value: ' + str(pulp.value(model.objective)))
```

<p>Do I need to make changes to the objective function/constraints to implement the above equations?</p>

<p>EDIT: Below snippet to try and implement @Erwin Kalvelagen's suggested changes. Still has extremely long durations for higher values of n,p and c:  </p>

<pre class="lang-py prettyprint-override"><code>y_sum = {}

# =============================================================================
# DECISION VARIABLES
# =============================================================================

model = pulp.LpProblem("Allocation Model", pulp.LpMinimize)

y_vars = pulp.LpVariable.dicts('y_vars',((i,j) for i in set_I for j in set_J), lowBound=0, upBound = 1, cat=pulp.LpInteger)
z_max = pulp.LpVariable("Max Policy Value")
z_min = pulp.LpVariable("Min Policy Value")
for j in set_J:
    y_sum[j] = pulp.lpSum([y_vars[i,j] * x[i] for i in set_I])

# =============================================================================
# OBJECTIVE FUNCTION
# =============================================================================

model += z_max - z_min

# =============================================================================
# CONSTRAINTS
# =============================================================================

for j in set_J:
    model += pulp.lpSum([y_vars[i,j] for i in set_I]) == n
    model += y_sum[j] <= z_max
    model += y_sum[j] >= z_min

for i in set_I:
    model += pulp.lpSum([y_vars[i,j] for j in set_J]) == 1
</code>```

答:
I don't think you can use that format to add constraints. Try this format instead:

```<code>for j in set_J:
    model += pulp.lpSum([y_vars[i,j] * x[i] for i in set_I]) <= z_max
</code>```

etc.

Note also the [...] inside the lpSum(...).

Finally, I don't think you can declare variables the way you did. I usually use LpVariable.dicts(), as in:

```<code>y_vars = pulp.lpVariable.dicts('y_vars', set_I, 0, 1, pulp.LpInteger)
</code>```

Body:
Background:

I am trying to allocate customers Ci to financial advisers Pj. Each customer has a policy value xi. I'm assuming that the number of customers (n) allocated to each adviser is the same, and that the same customer cannot be assigned to multiple advisers. Therefore each partner will have an allocation of policy values like so:

P1=[x1,x2,x3] , P2=[x4,x5,x6], P3=[x7,x8,x9]

I am trying to find the optimal allocation to minimise dispersion in fund value between the advisers. I am defining dispersion as  the difference between the adviser with the highest fund value (z_max) and the lowest fund value (z_min).

The formulation for this problem is therefore:

where yij=1 if we allocate customer Ci to adviser Pj, 0 otherwise

The first constraint says that zmax has to be greater than or equal to each policy value; since the objective function encourages smaller values of zmax, this means that zmax will equal the largest policy value. Similarly, the second constraint sets zmin equal to the smallest policy value. The third constraint says that each customer must be assigned to exactly one adviser. The fourth says that each adviser must have n customers assigned to him/her. Credit: @LarrySnyder610

Problem:

When implementing this problem in PulP, I expect 1740 (n x p) customers to be allocated across the 173 advisers based on constraint 3 and 4. However 72036 and no optimal allocation is obtained.

import random
import pandas as pd
import pulp

=============================================================================
# SAMPLE DATA
=============================================================================

n = 10 # number of customers for each financial adviser
c = 414 #number of customers
p = 174 #number of financial adviser
policy_values = random.sample(range(1, 1000000), c)

set_I = range(c)
set_J = range(p)
set_N = range(n)
x = {i: policy_values[i] for i in set_I} #customer policy values
y = {(i,j): random.randint(0, 1) for i in set_I for j in set_J} # allocation dummies

model = pulp.LpProblem("Allocation Model", pulp.LpMinimize)

# =============================================================================
# DECISION VARIABLES
# =============================================================================

y_vars  = {(i,j): pulp.LpVariable(cat=pulp.LpBinary, name="y_{0}_{1}".format(i,j)) for i in set_I for j in set_J}
z_max = pulp.LpVariable("Max Policy Value", 0)
z_min = pulp.LpVariable("Min Policy Value", 0)

# =============================================================================
# OBJECTIVE FUNCTION
# =============================================================================

model += z_max - z_min

# =============================================================================
# CONSTRAINTS
# =============================================================================
model += {j: pulp.lpSum(y_vars[i,j] * x[i] for i in set_I) for j in set_J} <= z_max # constraint 1
model += {j: pulp.lpSum(y_vars[i,j] * x[i] for i in set_I) for j in set_J} >= z_min # constraint 2
model += {i: pulp.lpSum(y_vars[i,j] for j in set_J) for i in set_I} == 1 # constraint 3
model += {j: pulp.lpSum(y_vars[i,j] for i in set_I) for j in set_J} == n #constraint 4

# =============================================================================
# SOLVE MODEL
# =============================================================================

model.solve()
print('Optimised model status: '+str(pulp.LpStatus[model.status]))

count=0
for v in model.variables():
    if v.varValue == 1.0:
        count+=1
        #print(v.name, "=", v.varValue)
print(count)
#>>> 72036 # expecting 1740

print('Optimal difference between highest and lowest summed policy_value: ' + str(pulp.value(model.objective)))

Do I need to make changes to the objective function/constraints to implement the above equations?

EDIT: Below snippet to try and implement @Erwin Kalvelagen's suggested changes. Still has extremely long durations for higher values of n,p and c:

y_sum = {}

# =============================================================================
# DECISION VARIABLES
# =============================================================================

model = pulp.LpProblem("Allocation Model", pulp.LpMinimize)

y_vars = pulp.LpVariable.dicts('y_vars',((i,j) for i in set_I for j in set_J), lowBound=0, upBound = 1, cat=pulp.LpInteger)
z_max = pulp.LpVariable("Max Policy Value")
z_min = pulp.LpVariable("Min Policy Value")
for j in set_J:
    y_sum[j] = pulp.lpSum([y_vars[i,j] * x[i] for i in set_I])

# =============================================================================
# OBJECTIVE FUNCTION
# =============================================================================

model += z_max - z_min

# =============================================================================
# CONSTRAINTS
# =============================================================================

for j in set_J:
    model += pulp.lpSum([y_vars[i,j] for i in set_I]) == n
    model += y_sum[j] <= z_max
    model += y_sum[j] >= z_min

for i in set_I:
    model += pulp.lpSum([y_vars[i,j] for j in set_J]) == 1

Body:
I don't think you can use that format to add constraints. Try this format instead:

for j in set_J:
    model += pulp.lpSum([y_vars[i,j] * x[i] for i in set_I]) <= z_max

etc.

Note also the [...] inside the lpSum(...).

Finally, I don't think you can declare variables the way you did. I usually use LpVariable.dicts(), as in:

y_vars = pulp.lpVariable.dicts('y_vars', set_I, 0, 1, pulp.LpInteger)


问:
How to get maximum values from pandas.value_counts for each variable?
I am actually trying to get only maximum values for each year returned from the pandas.value_count() function?

I have tried using the apply function with lambda function but was not successful:

```<code>print(match_won_by_team.apply(lambda x : match_won_by_team[x].index[0]))

remove_duplicate_match_codes = data.drop_duplicates(subset='match_code', keep='first').reset_index(drop=True)

match_won_by_team = remove_duplicate_match_codes.groupby('year')['winner'].value_counts()

print('Match won by each team in respective seasons:- ', match_won_by_team)
</code>```

I am expecting the output to display 2008: Rajasthan Royals: 13, 2009: Delhi Daredevils: 10 and so on from the series.

```<code>2008  Rajasthan Royals               13
      Kings XI Punjab                10
      Chennai Super Kings             9
2009  Delhi Daredevils               10
      Deccan Chargers                 9
      Royal Challengers Bangalore     9
2010  Mumbai Indians                 11
      Chennai Super Kings             9
      Deccan Chargers                 8
</code>```

I am getting this error when I am using the apply function and lambda on it.
AttributeError: 'numpy.int64' object has no attribute 'index'

答:
IIUC:

I think you need to use the following:

```<code>remove_duplicate_match_codes.groupby('year')['winner'].apply(lambda x: x.value_counts().head(1))
</code>```

This will apply value_counts to each part of winners by Year and use head to retrieve the first record, or the winner with the most counts in that year.

Body:
I am actually trying to get only maximum values for each year returned from the pandas.value_count() function?

I have tried using the apply function with lambda function but was not successful:

print(match_won_by_team.apply(lambda x : match_won_by_team[x].index[0]))

remove_duplicate_match_codes = data.drop_duplicates(subset='match_code', keep='first').reset_index(drop=True)

match_won_by_team = remove_duplicate_match_codes.groupby('year')['winner'].value_counts()

print('Match won by each team in respective seasons:- ', match_won_by_team)

I am expecting the output to display 2008: Rajasthan Royals: 13, 2009: Delhi Daredevils: 10 and so on from the series.

2008  Rajasthan Royals               13
      Kings XI Punjab                10
      Chennai Super Kings             9
2009  Delhi Daredevils               10
      Deccan Chargers                 9
      Royal Challengers Bangalore     9
2010  Mumbai Indians                 11
      Chennai Super Kings             9
      Deccan Chargers                 8

I am getting this error when I am using the apply function and lambda on it.
AttributeError: 'numpy.int64' object has no attribute 'index'

Body:
IIUC:

I think you need to use the following:

remove_duplicate_match_codes.groupby('year')['winner'].apply(lambda x: x.value_counts().head(1))

This will apply value_counts to each part of winners by Year and use head to retrieve the first record, or the winner with the most counts in that year.


问:
Casting a generic dictionary containing a generic dictionary
I have:

```<code>var someConcreteInstance = new Dictionary<string, Dictionary<string, bool>>();
</code>```

and I wish to cast it to an interface version, i.e.:

```<code>someInterfaceInstance = (IDictionary<string, IDictionary<string, bool>>)someConcreteInstance;
</code>```

'someInterfaceInstance' is a public property:

```<code>IDictionary<string, IDictionary<string, bool>> someInterfaceInstance { get; set; }
</code>```

This compiles correctly, but throws a runtime casting error.

```<code>Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.Boolean]]' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Collections.Generic.IDictionary`2[System.String,System.Boolean]]'.
</code>```

What am I missing? (Problems with the nested generic type/Property?)

答:
The other answers are right, but just to be crystal clear as to why this is illegal, consider the following:

```<code>interface IAnimal {}
class Tiger : IAnimal {}
class Giraffe : IAnimal {}
...
Dictionary<string, Giraffe> d1 = whatever;
IDictionary<string, IAnimal> d2 = d1; // suppose this were legal
d2["blake"] = new Tiger(); // What stops this?
</code>```

No mortal hand can stop you putting a tiger into a dictionary of IAnimals. But that dictionary is actually constrained to contain only giraffes.

For the same reason you can't go the other way either:

```<code>Dictionary<string, IAnimal> d3 = whatever;
d3["blake"] = new Tiger();
IDictionary<string, Giraffe> d4 = d3; // suppose this were legal
Giraffe g = d4["blake"]; // What stops this?
</code>```

Now you're putting a tiger in a variable of type giraffe.

Generic interface covariance is only legal in C# 4 if the compiler can prove that situations like this cannot arise.

Body:
I have:

var someConcreteInstance = new Dictionary<string, Dictionary<string, bool>>();

and I wish to cast it to an interface version, i.e.:

someInterfaceInstance = (IDictionary<string, IDictionary<string, bool>>)someConcreteInstance;

'someInterfaceInstance' is a public property:

IDictionary<string, IDictionary<string, bool>> someInterfaceInstance { get; set; }

This compiles correctly, but throws a runtime casting error.

Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.Boolean]]' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Collections.Generic.IDictionary`2[System.String,System.Boolean]]'.

What am I missing? (Problems with the nested generic type/Property?)

Body:
The other answers are right, but just to be crystal clear as to why this is illegal, consider the following:

interface IAnimal {}
class Tiger : IAnimal {}
class Giraffe : IAnimal {}
...
Dictionary<string, Giraffe> d1 = whatever;
IDictionary<string, IAnimal> d2 = d1; // suppose this were legal
d2["blake"] = new Tiger(); // What stops this?

No mortal hand can stop you putting a tiger into a dictionary of IAnimals. But that dictionary is actually constrained to contain only giraffes.

For the same reason you can't go the other way either:

Dictionary<string, IAnimal> d3 = whatever;
d3["blake"] = new Tiger();
IDictionary<string, Giraffe> d4 = d3; // suppose this were legal
Giraffe g = d4["blake"]; // What stops this?

Now you're putting a tiger in a variable of type giraffe.

Generic interface covariance is only legal in C# 4 if the compiler can prove that situations like this cannot arise.


答:
```<code>public class Child
{
    public int Id { get; set; }

    // add these navigation properties to access the Parent
    public int ParentId {get; set; }
    public Parent Parent {get; set; }
}
</code>```

https://www.learnentityframeworkcore.com/conventions/one-to-many-relationship

Title: Entity Framework Core : Access parent from child

Body:
public class Child
{
    public int Id { get; set; }

    // add these navigation properties to access the Parent
    public int ParentId {get; set; }
    public Parent Parent {get; set; }
}

https://www.learnentityframeworkcore.com/conventions/one-to-many-relationship


问:
TypeError: cannot convert the series to <class 'int'>
I have a dataset train with more than 16k observation.I have a variable fare_amount and i want to filter out all the negative values that are present in the variable.

fare_amount
0         4.5
1        16.9
2         5.7
3         7.7
4         5.3
5        12.1
6         7.5
7        16.5
9         8.9
10        0
11        5.5
12        4.1
13        7.0
.           .
.           .
16065

```<code>train.isnull().sum().sort_values(ascending=False)
train = train.drop(train[train.isnull().any(1)].index, axis = 0)
from collections import Counter
Counter(int(train['fare_amount'])<0)
```TypeError: cannot convert the series to <class 'int'>

want to remove all the values that are less than 0
keep getting an error
TypeError: cannot convert the series to <class 'int'>
```

答:
I don't know how the Counter class works, but I believe the following should work for removing negative numbers from the fare_amount list:

```<code>tempList = [item for item in fare_amount if item >= 0]
fare_amount = tempList
</code>```

See more: Python: Removing negatives from a list of numbers (answered January 2014)

Body:
I have a dataset train with more than 16k observation.I have a variable fare_amount and i want to filter out all the negative values that are present in the variable.

fare_amount
0         4.5
1        16.9
2         5.7
3         7.7
4         5.3
5        12.1
6         7.5
7        16.5
9         8.9
10        0
11        5.5
12        4.1
13        7.0
.           .
.           .
16065

train.isnull().sum().sort_values(ascending=False)
train = train.drop(train[train.isnull().any(1)].index, axis = 0)
from collections import Counter
Counter(int(train['fare_amount'])<0)
```TypeError: cannot convert the series to <class 'int'>

want to remove all the values that are less than 0
keep getting an error
TypeError: cannot convert the series to <class 'int'>

Body:
I don't know how the Counter class works, but I believe the following should work for removing negative numbers from the fare_amount list:

tempList = [item for item in fare_amount if item >= 0]
fare_amount = tempList

See more: Python: Removing negatives from a list of numbers (answered January 2014)


问:
How to display db results as options in HTML dropdown with PHP and Mysqli?
I am trying to to let users choose the state filed from a drop down in the form, but although the query works, the DB is connected, the drop down does not display the list.

Not sure if relevant but i'm running Windows Server, IIS 10 and the latest PHP and MySql.

    State
    <select class="form-control" name="state" id="state">

    <?php
    // Query to find STATE
    $sql1 = "SELECT * FROM codetable WHERE category = 'state'";
    $result1 = $conn->query($sql1);

    $row1 = mysqli_fetch_array($result1);

    while($row1 = mysqli_fetch_array($result1))
        {
            echo '<option value=" '.$row1['code'].' "> '.$row1['description'].' </option>';
         }
     ?>
    </select>

```

I expect the list from the DB to be in the dropdown, but it is empty (No dropdown list).

答:
delete your first

```<code>$row1 = mysqli_fetch_array($result1);
</code>```

line &
put your two variables(result & row1) in var_dump to get debug

Body:
I am trying to to let users choose the state filed from a drop down in the form, but although the query works, the DB is connected, the drop down does not display the list.

Not sure if relevant but i'm running Windows Server, IIS 10 and the latest PHP and MySql.

    State
    <select class="form-control" name="state" id="state">

    <?php
    // Query to find STATE
    $sql1 = "SELECT * FROM codetable WHERE category = 'state'";
    $result1 = $conn->query($sql1);

    $row1 = mysqli_fetch_array($result1);

    while($row1 = mysqli_fetch_array($result1))
        {
            echo '<option value=" '.$row1['code'].' "> '.$row1['description'].' </option>';
         }
     ?>
    </select>

I expect the list from the DB to be in the dropdown, but it is empty (No dropdown list).

Body:
delete your first

$row1 = mysqli_fetch_array($result1);

line &
put your two variables(result & row1) in var_dump to get debug


问:
Azure Function Detailed logging on Internal Server Error
I have a v2 Azure Function with an HTTP trigger. Occasionally, it will return a 500 with no additional information. I would like to set it to log more detailed information, including the error message and stack trace.

I have tried setting my host.json to look like this:

```<code>{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "default": "Trace"
    }
  }
}
</code>```

but it has not resulted in any more detailed information when running locally.

With the built in logging settings seeming to fail me, I'm trying a top level try/catch, but I can't figure out how to return both the status code 500 and the exception object.

[FunctionName("Http-UploadFiles")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "uploadFiles")] HttpRequest request,
    ILogger log)
{
    try
    {
        var requestBody = await new StreamReader(request.Body).ReadToEndAsync();
        var body = JsonConvert.DeserializeObject<JObject>(requestBody);

        var inventorySetGuid = Guid.Parse(body["inventorySetGuid"].ToString());
        var files = body["files"].Select(FileComponentUtilities.GetFile).ToList();
        var componentsAndErrors = await FileComponentUtilities.InsertSuitableComponentFiles(files, inventorySetGuid);

        return new JsonResult(componentsAndErrors, StorageFramework.Storage.SerializerSettings);
    }
    catch (Exception exception)
    {
        return new StatusCodeResult(500);
    }
}
```

This code returns the status code 500, but does not return the exception object. I cannot find a suitable IActionResult for returning a 500 with an exception object. How can I accomplish this for this v2 Azure Function?

答:
You can return a ContentResult that allows you to set any status code, content, and content type.

return new ContentResult
{
    StatusCode = 500,
    Content = "Something went wrong"
};
```

But do not use this to return your stack trace! It's a security concern for your app and there are better ways... Turn on Application Insights in your function app and use it to see your traces and errors.

Body:
I have a v2 Azure Function with an HTTP trigger. Occasionally, it will return a 500 with no additional information. I would like to set it to log more detailed information, including the error message and stack trace.

I have tried setting my host.json to look like this:

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "default": "Trace"
    }
  }
}

but it has not resulted in any more detailed information when running locally.

With the built in logging settings seeming to fail me, I'm trying a top level try/catch, but I can't figure out how to return both the status code 500 and the exception object.

[FunctionName("Http-UploadFiles")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "uploadFiles")] HttpRequest request,
    ILogger log)
{
    try
    {
        var requestBody = await new StreamReader(request.Body).ReadToEndAsync();
        var body = JsonConvert.DeserializeObject<JObject>(requestBody);

        var inventorySetGuid = Guid.Parse(body["inventorySetGuid"].ToString());
        var files = body["files"].Select(FileComponentUtilities.GetFile).ToList();
        var componentsAndErrors = await FileComponentUtilities.InsertSuitableComponentFiles(files, inventorySetGuid);

        return new JsonResult(componentsAndErrors, StorageFramework.Storage.SerializerSettings);
    }
    catch (Exception exception)
    {
        return new StatusCodeResult(500);
    }
}

This code returns the status code 500, but does not return the exception object. I cannot find a suitable IActionResult for returning a 500 with an exception object. How can I accomplish this for this v2 Azure Function?

Body:
You can return a ContentResult that allows you to set any status code, content, and content type.

return new ContentResult
{
    StatusCode = 500,
    Content = "Something went wrong"
};

But do not use this to return your stack trace! It's a security concern for your app and there are better ways... Turn on Application Insights in your function app and use it to see your traces and errors.


问:
Why is R HTTR content statement not producing the expected request body?
I am using R to call on Cybersource API. When I use the GET request I obtain a successful response of 200. When I read the body of the the response rather than get the csv data  back I get a path to a csv file path. I wonder what I am doing wrong.

content(request) gives

```<code> "/space/download_reports/output/dailyreports/reports/2018/10/27/testrest/TRRReport-7931d82d-cf4a-71fa-e053-a2588e0ab27a.csv"
</code>```

The result of content(request) should be the data not a file path.

Here is a the code

library('httr')
merchant<-'testrest'
vcdate<-'Wed, 29 May 2019 10:09:48 GMT'
ho<-'apitest.cybersource.com'
URL<-'https://apitest.cybersource.com/reporting/v3/report-downloads?organizationId=testrest&reportDate=2018-10-27&reportName=TRRReport'
sign<-'keyid="08c94330-f618-42a3-b09d-e1e43be5efda", algorithm="HmacSHA256", headers="host (request-target) v-c-merchant-id", signature="7cr6mZMa1oENhJ5NclGsprmQxwGlo1j3VjqAR6xngxk="'
req<-GET(URL, add_headers(.headers=c('v-c-merchant-id'=merchant, 'v-c-date'=vcdate, 'Host'=ho, 'Signature'=sign)))
content(req)
```

Here is Cybersource test api where you can verify the data produced.

https://developer.cybersource.com/api/reference/api-reference.html

I am trying to download a report under the reporting tab

答:
Honestly I'm not exactly sure what's going on here, but I do think I was able to get something to work.

The API seems to like to return data in application/hal+json format which is not one that httr normally requests. You can say you'll accept anything with  accept("*") So you can do your request with:

```<code>req <- GET(URL, add_headers('v-c-merchant-id'=merchant,
  'v-c-date'=vcdate,
  'Host'=ho,
  'Signature'=sign), accept("*"))
</code>```

Now we are actually getting the data back that we want, but httr doesn't know how to automatically parse it. So we need to parse it ourselves. This seems to do the trick

```<code>readr::read_csv(rawToChar(content(req)), skip=1)
</code>```

There seems to be a header row which we skip with skip= and then we parse the rest as a CSV file with readr::read_csv.

Body:
I am using R to call on Cybersource API. When I use the GET request I obtain a successful response of 200. When I read the body of the the response rather than get the csv data  back I get a path to a csv file path. I wonder what I am doing wrong.

content(request) gives

 "/space/download_reports/output/dailyreports/reports/2018/10/27/testrest/TRRReport-7931d82d-cf4a-71fa-e053-a2588e0ab27a.csv"

The result of content(request) should be the data not a file path.

Here is a the code

library('httr')
merchant<-'testrest'
vcdate<-'Wed, 29 May 2019 10:09:48 GMT'
ho<-'apitest.cybersource.com'
URL<-'https://apitest.cybersource.com/reporting/v3/report-downloads?organizationId=testrest&reportDate=2018-10-27&reportName=TRRReport'
sign<-'keyid="08c94330-f618-42a3-b09d-e1e43be5efda", algorithm="HmacSHA256", headers="host (request-target) v-c-merchant-id", signature="7cr6mZMa1oENhJ5NclGsprmQxwGlo1j3VjqAR6xngxk="'
req<-GET(URL, add_headers(.headers=c('v-c-merchant-id'=merchant, 'v-c-date'=vcdate, 'Host'=ho, 'Signature'=sign)))
content(req)

Here is Cybersource test api where you can verify the data produced.

https://developer.cybersource.com/api/reference/api-reference.html

I am trying to download a report under the reporting tab

Body:
Honestly I'm not exactly sure what's going on here, but I do think I was able to get something to work.

The API seems to like to return data in application/hal+json format which is not one that httr normally requests. You can say you'll accept anything with  accept("*") So you can do your request with:

req <- GET(URL, add_headers('v-c-merchant-id'=merchant,
  'v-c-date'=vcdate,
  'Host'=ho,
  'Signature'=sign), accept("*"))

Now we are actually getting the data back that we want, but httr doesn't know how to automatically parse it. So we need to parse it ourselves. This seems to do the trick

readr::read_csv(rawToChar(content(req)), skip=1)

There seems to be a header row which we skip with skip= and then we parse the rest as a CSV file with readr::read_csv.


问:
check for duplicate lists Java 8
Given n lists, I want to find out if any two lists have exactly same elements. Below is code in Java 7.

```<code>public static <T> boolean hasduplicateList(List<List<T>> lists) {
    for (List<T> outerList : lists) {
        int count = 0;
        Set<T> outerSet = new HashSet<>(outerList);
        for (List<T> innerList : lists) {
            Set<T> innerSet = new HashSet<>(innerList);
            if (outerSet.equals(innerSet)) {
                count++;
            }
            if (count == 2) {
                return true;
            }
        }
    }
    return false;
}
</code>```

Is there a better way to achieve same specially using Java8?

答:
I inspired from @Eran 's answer for an integer array and It worked.
Code is :</p>

```<code>int a = {1,2,3,4,5};
boolean isAnyDuplicate = Arrays.stream(a).distinct().count() < a.length;
System.out.println("First is" + isAnyDuplicate);
int b = {1,2,2,4,5};
isAnyDuplicate = Arrays.stream(b).distinct().count() < b.length;
System.out.println("Second is" + isAnyDuplicate);
</code>```

Title: check for duplicate lists Java 8

Body:
Given n lists, I want to find out if any two lists have exactly same elements. Below is code in Java 7.

public static <T> boolean hasduplicateList(List<List<T>> lists) {
    for (List<T> outerList : lists) {
        int count = 0;
        Set<T> outerSet = new HashSet<>(outerList);
        for (List<T> innerList : lists) {
            Set<T> innerSet = new HashSet<>(innerList);
            if (outerSet.equals(innerSet)) {
                count++;
            }
            if (count == 2) {
                return true;
            }
        }
    }
    return false;
}

Is there a better way to achieve same specially using Java8?

Body:
I inspired from @Eran 's answer for an integer array and It worked.
Code is :

int a = {1,2,3,4,5};
boolean isAnyDuplicate = Arrays.stream(a).distinct().count() < a.length;
System.out.println("First is" + isAnyDuplicate);
int b = {1,2,2,4,5};
isAnyDuplicate = Arrays.stream(b).distinct().count() < b.length;
System.out.println("Second is" + isAnyDuplicate);


问:
How to calculate the difference between consecutive sets of two columns in a column range using dplyr
I would like to calculate the difference between consecutive columns in a range of columns using dplyr.

For example, using the iris data set I would want to be able to specify the range Sepal.Width:Petal.Width and have a dataframe that contained the original iris data and the differences between the consecutive columns from Sepal.Width:Petal.Width:

```<code>  Sepal.Length Sepal.Width Petal.Length Petal.Width Species diff1 diff2
1          5.1         3.5          1.4         0.2  setosa   2.1   1.2
2          4.9         3.0          1.4         0.2  setosa   1.6   1.2
3          4.7         3.2          1.3         0.2  setosa   1.9   1.1
4          4.6         3.1          1.5         0.2  setosa   1.6   1.3
5          5.0         3.6          1.4         0.2  setosa   2.2   1.2
6          5.4         3.9          1.7         0.4  setosa   2.2   1.3
</code>```

Someone posted a solution loops and lapply (Calculate the difference between consecutive, grouped columns in a data.table) but I'm specifically looking for a dplyr solution.

答:
Here is an option with tidyverse.  We select the range of columns, remove the first and last column in to a list of data.frames, then use reduce to get the difference between set of equal dimension datasets, and rename the columns

```<code>library(dplyr)
library(purrr)
library(stringr)
out <- iris %>%
      select(Sepal.Width:Petal.Width) %>%
      {list(.[-length(.)], .[-1])} %>%
      reduce(`-`) %>%
      rename_all(~ str_c("diff", seq_along(.))) %>%
      bind_cols(iris, .)

head(out)
#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species diff1 diff2
#1          5.1         3.5          1.4         0.2  setosa   2.1   1.2
#2          4.9         3.0          1.4         0.2  setosa   1.6   1.2
#3          4.7         3.2          1.3         0.2  setosa   1.9   1.1
#4          4.6         3.1          1.5         0.2  setosa   1.6   1.3
#5          5.0         3.6          1.4         0.2  setosa   2.2   1.2
#6          5.4         3.9          1.7         0.4  setosa   2.2   1.3
</code>```

Or another approach is to loop through index of columns select the columns, reduce it to a single column with - and bind with the original dataset

```<code>map_dfc(3:4, ~ iris %>%
                select(.x-1, .x) %>%
                transmute(diff = reduce(., `-`))) %>%
     bind_cols(iris, .)
</code>```

Body:
I would like to calculate the difference between consecutive columns in a range of columns using dplyr.

For example, using the iris data set I would want to be able to specify the range Sepal.Width:Petal.Width and have a dataframe that contained the original iris data and the differences between the consecutive columns from Sepal.Width:Petal.Width:

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species diff1 diff2
1          5.1         3.5          1.4         0.2  setosa   2.1   1.2
2          4.9         3.0          1.4         0.2  setosa   1.6   1.2
3          4.7         3.2          1.3         0.2  setosa   1.9   1.1
4          4.6         3.1          1.5         0.2  setosa   1.6   1.3
5          5.0         3.6          1.4         0.2  setosa   2.2   1.2
6          5.4         3.9          1.7         0.4  setosa   2.2   1.3

Someone posted a solution loops and lapply (Calculate the difference between consecutive, grouped columns in a data.table) but I'm specifically looking for a dplyr solution.

Body:
Here is an option with tidyverse.  We select the range of columns, remove the first and last column in to a list of data.frames, then use reduce to get the difference between set of equal dimension datasets, and rename the columns

library(dplyr)
library(purrr)
library(stringr)
out <- iris %>%
      select(Sepal.Width:Petal.Width) %>%
      {list(.[-length(.)], .[-1])} %>%
      reduce(`-`) %>%
      rename_all(~ str_c("diff", seq_along(.))) %>%
      bind_cols(iris, .)

head(out)
#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species diff1 diff2
#1          5.1         3.5          1.4         0.2  setosa   2.1   1.2
#2          4.9         3.0          1.4         0.2  setosa   1.6   1.2
#3          4.7         3.2          1.3         0.2  setosa   1.9   1.1
#4          4.6         3.1          1.5         0.2  setosa   1.6   1.3
#5          5.0         3.6          1.4         0.2  setosa   2.2   1.2
#6          5.4         3.9          1.7         0.4  setosa   2.2   1.3

Or another approach is to loop through index of columns select the columns, reduce it to a single column with - and bind with the original dataset

map_dfc(3:4, ~ iris %>%
                select(.x-1, .x) %>%
                transmute(diff = reduce(., `-`))) %>%
     bind_cols(iris, .)


问:
Capturing folder path from Windows Explorer
I would like to add to a Delphi application a way for the user to call Windows Explorer (possibly using something like ShellExecute, perhaps).

However, and this is where I need some help, please, the application would need to capture ^H^H^H^H^H^H read the folder path that the user navigates to while within Windows Explorer.

Is it possible to obtain this information from Windows Explorer?

[edit: If not possible, or unrealistic, my fallback plan is to provide a separate "Browse for folder" button, to allow the user to select the folder first, then they can launch the Window explorer afterwards].

Thanks for any advice.
PhilW.

答:
For letting a user browse to and select a folder, I use TOrtusShellBrowseFolder.

Ortus Shell Components


问:
jQuery UI Datepicker onchange event issue
I have a JS code in which when you change a field it calls a search routine. The problem is that I can't find any jQuery events that will fire when the Datepicker updates the input field.

For some reason, a change event is not called when Datepicker updates the field. When the calendar pops up it changes the focus so I can't use that either. Any ideas?

答:
My soluthion:</p>

```<code>var $dateInput = $('#dateInput');

$dateInput.datepicker({
    onSelect: function(f,d,i){
        if(d !== i.lastVal){
            $dateInput.trigger("change");
        }
    }
}).data('datepicker');

$dateInput.on("change", function () {
   //your code
});
</code>```

Body:
My soluthion:

var $dateInput = $('#dateInput');

$dateInput.datepicker({
    onSelect: function(f,d,i){
        if(d !== i.lastVal){
            $dateInput.trigger("change");
        }
    }
}).data('datepicker');

$dateInput.on("change", function () {
   //your code
});


问:
Why can't I use execl() to run a bash script?
I'm trying to run a bash script from a website button on a raspberry pi, where the script is located in home/pi/. The code snippet below shows my current solution. Whenever the website button is pressed, it calls this block of code in a c file.

```<code>else if(strcmp(argv[1],"SelfTest") == 0)
    {
        char *command = "/bin/bash";
        char name[40];
        strcpy(name, "home/pi/SelfTest.sh");
        execl(command, command, name, NULL);
        return 0;
    }
</code>```

I'm running this on a Raspberry Pi 3+, the script I'm running has 777 permissions and is owned by pi:www-data, if that helps.

I tested to see if the IF block actually got called by just having it create an empty directory called 'TEST'. The bottom snippet of code shows how I approached that. This seems to work without issue (as soon as I press the button on the website, I 'ls' home/pi/ and a new folder called 'TEST' is there). Unfortunately, when I run the top snippet of code(to run SelfTest.sh), the script doesn't run (the script itself is supposed to record the output to a log file with a timestamp, and pressing the button does not update the timestamp. The timestamp only updates when I run the script from within the terminal)

```<code>else if(strcmp(argv[1],"SelfTest") == 0)
    {
        char *command = "/bin/mkdir";
        char name[40];
        strcpy(name, "/home/pi/TEST");
        execl(command, command, name, NULL);
        return 0;
    }
</code>```

What should be happening every time I press the website button is that it should run SelfTest.sh. I should be able to verify this by reading the logfile, but it never gets updated when I press the website button.

Please let me know if you need any extra information!

答:
Unless if you are running this from /, this line is missing a slash before home:

```<code>strcpy(name, "home/pi/SelfTest.sh");
</code>```

Also, execl will never return. You may want to look up information on the fork() and exec() pattern.

Body:
I'm trying to run a bash script from a website button on a raspberry pi, where the script is located in home/pi/. The code snippet below shows my current solution. Whenever the website button is pressed, it calls this block of code in a c file.

else if(strcmp(argv[1],"SelfTest") == 0)
    {
        char *command = "/bin/bash";
        char name[40];
        strcpy(name, "home/pi/SelfTest.sh");
        execl(command, command, name, NULL);
        return 0;
    }

I'm running this on a Raspberry Pi 3+, the script I'm running has 777 permissions and is owned by pi:www-data, if that helps.

I tested to see if the IF block actually got called by just having it create an empty directory called 'TEST'. The bottom snippet of code shows how I approached that. This seems to work without issue (as soon as I press the button on the website, I 'ls' home/pi/ and a new folder called 'TEST' is there). Unfortunately, when I run the top snippet of code(to run SelfTest.sh), the script doesn't run (the script itself is supposed to record the output to a log file with a timestamp, and pressing the button does not update the timestamp. The timestamp only updates when I run the script from within the terminal)

else if(strcmp(argv[1],"SelfTest") == 0)
    {
        char *command = "/bin/mkdir";
        char name[40];
        strcpy(name, "/home/pi/TEST");
        execl(command, command, name, NULL);
        return 0;
    }

What should be happening every time I press the website button is that it should run SelfTest.sh. I should be able to verify this by reading the logfile, but it never gets updated when I press the website button.

Please let me know if you need any extra information!

Body:
Unless if you are running this from /, this line is missing a slash before home:

strcpy(name, "home/pi/SelfTest.sh");

Also, execl will never return. You may want to look up information on the fork() and exec() pattern.


问:
Can this Kotlin casting code be simplified?
We have some code to a third party SDK that returns an "Any?".  And we have to cast it (if it casts and parse it).  Because our casts are generic, I have not been able to figure out how to simplify this without writing 5 casts.  This seems much easier in Swift. Is there a better way of doing these casts?

```<code>private fun parseOrganizations(payload: Any?): List<UserOrganization> {
        val organizations = mutableListOf<UserOrganization>()
        payload?.let { userData ->
            if (userData is Map<*, *>) {
                val orgJsonList = userData["organizations"]
                if (orgJsonList is List<*>) {
                    for (jsonMap in orgJsonList) {
                        if (jsonMap is Map<*, *>) {
                            val id = jsonMap["id"] as? String
                            val name = jsonMap["name"] as? String
                            val role = jsonMap["role"] as? String
                            val isActive = jsonMap["isActive"] as? Boolean
                            val isVerified = jsonMap["isVerified"] as? Boolean
                            if (id != null && name != null && role != null && isActive != null && isVerified != null) {
                                val org = UserOrganization(id, name, role, isActive, isVerified)
                                organizations.add(org)
                            }
                        }
                    }
                }
            }
        }
        return organizations
    }
</code>```

Thanks guys.

答:
You can avoid a lot of nested if just changing it to ?.let and for to map . Code in this case will be flat and readable

```<code>fun parseOrganizations(payload: Any?) {
    payload
        ?.let { it as? Map<*, *> }
        ?.let { it["organizations"] as? List<*> }
        ?.mapNotNull { if (it is Map<*, *>) UserOrganization.fromMap(it) else null }
        ?.map { organizations.add(it) }
}
</code>```

But we should deal with creating UserOrganization from Map contains organization's details. To be honest, I could not figure out a really elegant way. But it is better to create external function or something like this, to encapsulate fallback logic:

```<code>class UserOrganization(
    val id: String,
    val name: String,
    val role: String,
    val isActive: Boolean,
    val isVerified: Boolean
){
    companion object {
        fun fromMap(org: Map<*,*>): UserOrganization? =
            if (org.keys.containsAll(listOf("id", "name", "role", "isActive", "isVerified"))) {
                UserOrganization(
                    id = org["id"] as? String ?: "Unknown Id",
                    name = org["name"] as? String ?: "Unknown name",
                    role = org["role"] as? String ?: "Unknown role",
                    isActive = org["isActive"] as? Boolean ?: false,
                    isVerified = org["isVerified"] as? Boolean ?: false
                )
            } else null
    }
}
</code>```

i can't bet that it works 100% correct, but I think I could show the idea.

Body:
We have some code to a third party SDK that returns an "Any?".  And we have to cast it (if it casts and parse it).  Because our casts are generic, I have not been able to figure out how to simplify this without writing 5 casts.  This seems much easier in Swift. Is there a better way of doing these casts?

private fun parseOrganizations(payload: Any?): List<UserOrganization> {
        val organizations = mutableListOf<UserOrganization>()
        payload?.let { userData ->
            if (userData is Map<*, *>) {
                val orgJsonList = userData["organizations"]
                if (orgJsonList is List<*>) {
                    for (jsonMap in orgJsonList) {
                        if (jsonMap is Map<*, *>) {
                            val id = jsonMap["id"] as? String
                            val name = jsonMap["name"] as? String
                            val role = jsonMap["role"] as? String
                            val isActive = jsonMap["isActive"] as? Boolean
                            val isVerified = jsonMap["isVerified"] as? Boolean
                            if (id != null && name != null && role != null && isActive != null && isVerified != null) {
                                val org = UserOrganization(id, name, role, isActive, isVerified)
                                organizations.add(org)
                            }
                        }
                    }
                }
            }
        }
        return organizations
    }

Thanks guys.

Body:
You can avoid a lot of nested if just changing it to ?.let and for to map . Code in this case will be flat and readable

fun parseOrganizations(payload: Any?) {
    payload
        ?.let { it as? Map<*, *> }
        ?.let { it["organizations"] as? List<*> }
        ?.mapNotNull { if (it is Map<*, *>) UserOrganization.fromMap(it) else null }
        ?.map { organizations.add(it) }
}

But we should deal with creating UserOrganization from Map contains organization's details. To be honest, I could not figure out a really elegant way. But it is better to create external function or something like this, to encapsulate fallback logic:

class UserOrganization(
    val id: String,
    val name: String,
    val role: String,
    val isActive: Boolean,
    val isVerified: Boolean
){
    companion object {
        fun fromMap(org: Map<*,*>): UserOrganization? =
            if (org.keys.containsAll(listOf("id", "name", "role", "isActive", "isVerified"))) {
                UserOrganization(
                    id = org["id"] as? String ?: "Unknown Id",
                    name = org["name"] as? String ?: "Unknown name",
                    role = org["role"] as? String ?: "Unknown role",
                    isActive = org["isActive"] as? Boolean ?: false,
                    isVerified = org["isVerified"] as? Boolean ?: false
                )
            } else null
    }
}

i can't bet that it works 100% correct, but I think I could show the idea.


问:
Specific URL for OneSignal push notifications
I use OneSignal plugin at Wordpress to send push notifications.

Now push notifications use wordpress post's URL. How can I set specific URL for push notifications?

答:
To customize the URL for the notification, you can either send the notifications manually through the OneSignal dashboard, or you can customize the plugin code itself to change the behavior.

The latter option requires some PHP coding knowledge. You can find an overview of the steps required in the OneSignal documentation here.


问:
Is there an easy method to check is an NSRange passed to substringWithRange on NSString exists (so not to cause an error)?
Say I pass the NSRange of (location: 5, length: 50) on the NSString "foo", that range obviously doesn't exist.

Is there a way to say [string rangeExists:NSRange] for instance, or do we have to manually validate the input?

答:
You can do this :</p>

```<code>if(selectedNSRange.location != NSNotFound && NSMaxRange(selectedNSRange) <= self.text.length)
</code>```

Body:
You can do this :

if(selectedNSRange.location != NSNotFound && NSMaxRange(selectedNSRange) <= self.text.length)