问:
invokedynamic requires --min-sdk-version >= 26
Today downloaded the studio 3.0 beta 2.0 version, after that tried to open an existing project in it and faced some difficulties, most of them I could solve with the help of Google and Stack Overflow, but this one I can not.

```<code>Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
> com.android.build.api.transform.TransformException: org.gradle.tooling.BuildException: com.android.dx.cf.code.SimException: invalid opcode ba (invokedynamic requires --min-sdk-version >= 26)
</code>```

Also posting my app gradle

```<code>apply plugin: 'com.android.application'
   android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

defaultConfig {
    applicationId "com.intersoft.snappy"
    minSdkVersion 19
    targetSdkVersion 22
    multiDexEnabled true
    versionCode 1
    versionName "1.0"
}
buildTypeMatching 'dev', 'debug'
buildTypeMatching 'qa', 'debug'
buildTypeMatching 'rc', 'release'
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
sourceSets { main { assets.srcDirs = ['src/main/assets', 'src/main/assets/']
} }
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
}
}
repositories {
mavenCentral()
mavenLocal()
jcenter()
maven { url "https://plugins.gradle.org/m2/" }
maven { url "https://s3.amazonaws.com/repo.commonsware.com" }
maven { url "https://jitpack.io" }
maven { url 'https://dl.bintray.com/ashokslsk/CheckableView' }
maven { url "https://maven.google.com" }

}
android {
useLibrary 'org.apache.http.legacy'
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.0.1'
implementation 'com.github.mrengineer13:snackbar:1.2.0'
implementation 'com.android.support:recyclerview-v7:26.0.1'
implementation 'com.android.support:cardview-v7:26.0.1'
implementation 'com.android.support:design:26.0.1'
implementation 'com.android.support:percent:26.0.1'
implementation 'dev.dworks.libs:volleyplus:+'
implementation 'com.google.guava:guava:21.0'
implementation 'com.facebook.fresco:fresco:1.0.1'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.wdullaer:materialdatetimepicker:3.1.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.github.stfalcon:frescoimageviewer:0.4.0'
implementation 'com.github.piotrek1543:CustomSpinner:0.1'
implementation 'com.android.support:multidex:1.0.2'
implementation 'com.github.satyan:sugar:1.4'
implementation 'com.hedgehog.ratingbar:app:1.1.2'
implementation project(':sandriosCamera')
implementation('org.apache.httpcomponents:httpmime:4.2.6') {
    exclude module: 'httpclient'
}
implementation 'com.googlecode.json-simple:json-simple:1.1'
}

afterEvaluate {
tasks.matching {
    it.name.startsWith('dex')
}.each { dx ->
    if (dx.additionalParameters == null) {
        dx.additionalParameters = ['--multi-dex']
    } else {
        dx.additionalParameters += '--multi-dex'
    }
}
}
subprojects {
project.plugins.whenPluginAdded { plugin ->
    if ("com.android.build.gradle.AppPlugin".equals(plugin.class.name)) {
        project.android.dexOptions.preDexLibraries = false
    } else if
("com.android.build.gradle.LibraryPlugin".equals(plugin.class.name)) {
        project.android.dexOptions.preDexLibraries = false
    }
}
}

buildscript {
repositories {
    mavenCentral()
}

dependencies {
    classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1'
}
}

apply plugin: 'com.jakewharton.hugo'
</code>```

also my another module gradle

```<code>apply plugin: 'com.android.library'
apply plugin: 'com.jfrog.bintray'
apply plugin: 'com.github.dcendents.android-maven'

buildscript {
repositories {
    jcenter()
    jcenter()
    maven { url "https://maven.google.com" }
}
dependencies {
    classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7'
    classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
}
}

group = 'com.sandrios.android'
version = '1.0.8'

ext {
PUBLISH_GROUP_ID = 'com.sandrios.android'
PUBLISH_ARTIFACT_ID = 'sandriosCamera'
PUBLISH_VERSION = '1.0.8'
PUBLISH_CODE = 9
}

android {
compileSdkVersion 26
buildToolsVersion "26.0.1"

defaultConfig {
    minSdkVersion 19
    targetSdkVersion 25
    versionCode PUBLISH_CODE
    versionName PUBLISH_VERSION
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
lintOptions {
    abortOnError false
}
}

task generateSourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier 'sources'
}

task generateJavadocs(type: Javadoc) {
failOnError false
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath()
        .join(File.pathSeparator))
}

task generateJavadocsJar(type: Jar) {
from generateJavadocs.destinationDir
classifier 'javadoc'
}

generateJavadocsJar.dependsOn generateJavadocs

artifacts {
archives generateSourcesJar
archives generateJavadocsJar
}

install {
repositories.mavenInstaller {
    pom.project {
        name PUBLISH_GROUP_ID
        description 'Simple integration of universal camera in android for easy image and video capture.'
        url 'https://github.com/sandrios/sandriosCamera'
        inceptionYear '2016'

        packaging 'aar'
        version PUBLISH_VERSION

        scm {
            connection 'https://github.com/sandrios/sandriosCamera.git'
            url 'https://github.com/sandrios/sandriosCamera'

        }
        developers {
            developer {
                name 'arpitgandhi9'
            }
        }
    }
}
}

bintray {
Properties properties = new Properties()

properties.load(project.rootProject.file('local.properties').newDataInputStream())
user = properties.getProperty('bintray.user')
key = properties.getProperty('bintray.apikey')
configurations = ['archives']
pkg {
    repo = 'android'
    name = 'sandriosCamera'
    userOrg = 'sandriosstudios'
    desc = 'Android solution to simplify work with different camera apis.'
    licenses = ['MIT']
    labels = ['android', 'camera', 'photo', 'video']
    websiteUrl = 'https://github.com/sandrios/sandriosCamera'
    issueTrackerUrl = 'https://github.com/sandrios/sandriosCamera/issues'
    vcsUrl = 'https://github.com/sandrios/sandriosCamera.git'
    version {
        name = PUBLISH_VERSION
        vcsTag = PUBLISH_VERSION
        desc = 'Minor fixes.'
        released = new Date()
    }
}
}

repositories {
jcenter()
}

dependencies {
implementation 'com.android.support:support-v4:26.0.0'
implementation 'com.android.support:appcompat-v7:26.0.0'
implementation 'com.android.support:recyclerview-v7:26.0.0'
implementation 'com.github.bumptech.glide:glide:3.6.1'
implementation 'com.yalantis:ucrop:2.2.0'
implementation 'gun0912.ted:tedpermission:1.0.2'
}
</code>```

and also project level gradle

```<code>// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-beta2'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
    maven {
        url "https://maven.google.com"
    }
}
}
</code>```

please help me to get rid of this error

答:
I was having the same issue. I had recently deleted my .gradle cache folder, and reinstalled Android Studio and the SDK. Eventually when trying to git bisect the problem, it went away. I can only speculate as to why this happened, but I suspect that downloading older versions of the build tools and SDK, and building (and presumably caching) versions of our code with those older tools caused it to be built in a way that didn't cause issues.

This points to some sort of bug in the way that the newer (API 26?) build tools are building the source code, and so my recommendation if you're seeing this problem and the other solutions don't work, is to lower your target SDK version to 25 or lower, install the necessary build tools, and try compiling your code with those, before reverting to build tools 26 or higher.

Body:
Today downloaded the studio 3.0 beta 2.0 version, after that tried to open an existing project in it and faced some difficulties, most of them I could solve with the help of Google and Stack Overflow, but this one I can not.

Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
> com.android.build.api.transform.TransformException: org.gradle.tooling.BuildException: com.android.dx.cf.code.SimException: invalid opcode ba (invokedynamic requires --min-sdk-version >= 26)

Also posting my app gradle

apply plugin: 'com.android.application'
   android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

defaultConfig {
    applicationId "com.intersoft.snappy"
    minSdkVersion 19
    targetSdkVersion 22
    multiDexEnabled true
    versionCode 1
    versionName "1.0"
}
buildTypeMatching 'dev', 'debug'
buildTypeMatching 'qa', 'debug'
buildTypeMatching 'rc', 'release'
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
sourceSets { main { assets.srcDirs = ['src/main/assets', 'src/main/assets/']
} }
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
}
}
repositories {
mavenCentral()
mavenLocal()
jcenter()
maven { url "https://plugins.gradle.org/m2/" }
maven { url "https://s3.amazonaws.com/repo.commonsware.com" }
maven { url "https://jitpack.io" }
maven { url 'https://dl.bintray.com/ashokslsk/CheckableView' }
maven { url "https://maven.google.com" }

}
android {
useLibrary 'org.apache.http.legacy'
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.0.1'
implementation 'com.github.mrengineer13:snackbar:1.2.0'
implementation 'com.android.support:recyclerview-v7:26.0.1'
implementation 'com.android.support:cardview-v7:26.0.1'
implementation 'com.android.support:design:26.0.1'
implementation 'com.android.support:percent:26.0.1'
implementation 'dev.dworks.libs:volleyplus:+'
implementation 'com.google.guava:guava:21.0'
implementation 'com.facebook.fresco:fresco:1.0.1'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.wdullaer:materialdatetimepicker:3.1.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.github.stfalcon:frescoimageviewer:0.4.0'
implementation 'com.github.piotrek1543:CustomSpinner:0.1'
implementation 'com.android.support:multidex:1.0.2'
implementation 'com.github.satyan:sugar:1.4'
implementation 'com.hedgehog.ratingbar:app:1.1.2'
implementation project(':sandriosCamera')
implementation('org.apache.httpcomponents:httpmime:4.2.6') {
    exclude module: 'httpclient'
}
implementation 'com.googlecode.json-simple:json-simple:1.1'
}

afterEvaluate {
tasks.matching {
    it.name.startsWith('dex')
}.each { dx ->
    if (dx.additionalParameters == null) {
        dx.additionalParameters = ['--multi-dex']
    } else {
        dx.additionalParameters += '--multi-dex'
    }
}
}
subprojects {
project.plugins.whenPluginAdded { plugin ->
    if ("com.android.build.gradle.AppPlugin".equals(plugin.class.name)) {
        project.android.dexOptions.preDexLibraries = false
    } else if
("com.android.build.gradle.LibraryPlugin".equals(plugin.class.name)) {
        project.android.dexOptions.preDexLibraries = false
    }
}
}

buildscript {
repositories {
    mavenCentral()
}

dependencies {
    classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1'
}
}

apply plugin: 'com.jakewharton.hugo'

also my another module gradle

apply plugin: 'com.android.library'
apply plugin: 'com.jfrog.bintray'
apply plugin: 'com.github.dcendents.android-maven'

buildscript {
repositories {
    jcenter()
    jcenter()
    maven { url "https://maven.google.com" }
}
dependencies {
    classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7'
    classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
}
}

group = 'com.sandrios.android'
version = '1.0.8'

ext {
PUBLISH_GROUP_ID = 'com.sandrios.android'
PUBLISH_ARTIFACT_ID = 'sandriosCamera'
PUBLISH_VERSION = '1.0.8'
PUBLISH_CODE = 9
}

android {
compileSdkVersion 26
buildToolsVersion "26.0.1"

defaultConfig {
    minSdkVersion 19
    targetSdkVersion 25
    versionCode PUBLISH_CODE
    versionName PUBLISH_VERSION
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
lintOptions {
    abortOnError false
}
}

task generateSourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier 'sources'
}

task generateJavadocs(type: Javadoc) {
failOnError false
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath()
        .join(File.pathSeparator))
}

task generateJavadocsJar(type: Jar) {
from generateJavadocs.destinationDir
classifier 'javadoc'
}

generateJavadocsJar.dependsOn generateJavadocs

artifacts {
archives generateSourcesJar
archives generateJavadocsJar
}

install {
repositories.mavenInstaller {
    pom.project {
        name PUBLISH_GROUP_ID
        description 'Simple integration of universal camera in android for easy image and video capture.'
        url 'https://github.com/sandrios/sandriosCamera'
        inceptionYear '2016'

        packaging 'aar'
        version PUBLISH_VERSION

        scm {
            connection 'https://github.com/sandrios/sandriosCamera.git'
            url 'https://github.com/sandrios/sandriosCamera'

        }
        developers {
            developer {
                name 'arpitgandhi9'
            }
        }
    }
}
}

bintray {
Properties properties = new Properties()

properties.load(project.rootProject.file('local.properties').newDataInputStream())
user = properties.getProperty('bintray.user')
key = properties.getProperty('bintray.apikey')
configurations = ['archives']
pkg {
    repo = 'android'
    name = 'sandriosCamera'
    userOrg = 'sandriosstudios'
    desc = 'Android solution to simplify work with different camera apis.'
    licenses = ['MIT']
    labels = ['android', 'camera', 'photo', 'video']
    websiteUrl = 'https://github.com/sandrios/sandriosCamera'
    issueTrackerUrl = 'https://github.com/sandrios/sandriosCamera/issues'
    vcsUrl = 'https://github.com/sandrios/sandriosCamera.git'
    version {
        name = PUBLISH_VERSION
        vcsTag = PUBLISH_VERSION
        desc = 'Minor fixes.'
        released = new Date()
    }
}
}

repositories {
jcenter()
}

dependencies {
implementation 'com.android.support:support-v4:26.0.0'
implementation 'com.android.support:appcompat-v7:26.0.0'
implementation 'com.android.support:recyclerview-v7:26.0.0'
implementation 'com.github.bumptech.glide:glide:3.6.1'
implementation 'com.yalantis:ucrop:2.2.0'
implementation 'gun0912.ted:tedpermission:1.0.2'
}

and also project level gradle

// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-beta2'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
    maven {
        url "https://maven.google.com"
    }
}
}

please help me to get rid of this error


来源: stackexchange

问:
Use a different matplotlibrc for savefig
I am using Jupyter Notebook, with a matplotlibrc style that's consistent with its theme set using jupyterthemes.  That plotting style however does not look good if I want to export it to PNG to use it within my other documents.

How do I specify a different matplotlibrc when I do a savefig?

答:
Perusing matplotlib/__init__.py reveals a number of functions used for managing rcParams. To update rcParams from a file, use matplotlib.rc_file:

```<code>import matplotlib as mpl
import matplotlib.pyplot as plt

mpl.rc_file('/tmp/matplotlibrc')
plt.plot([0,1], [0,10])
plt.savefig('/tmp/out.png')
</code>```

with /tmp/matplotlibrc containing

```<code>lines.linewidth   : 10     # line width in points
lines.linestyle   : --     # dashed line
</code>```

yields

PS. In hindsight, having found rc_file, googling shows it is documented here.

ContentLicense: CC BY-SA 3.0

Body:
Perusing matplotlib/__init__.py reveals a number of functions used for managing rcParams. To update rcParams from a file, use matplotlib.rc_file:

import matplotlib as mpl
import matplotlib.pyplot as plt

mpl.rc_file('/tmp/matplotlibrc')
plt.plot([0,1], [0,10])
plt.savefig('/tmp/out.png')

with /tmp/matplotlibrc containing

lines.linewidth   : 10     # line width in points
lines.linestyle   : --     # dashed line

yields

PS. In hindsight, having found rc_file, googling shows it is documented here.


问:
Finding the mode of a list
Given a list of items, recall that the mode of the list is the item that occurs most often.

I would like to know how to create a function that can find the mode of a list but that displays a message if the list does not have a mode (e.g., all the items in the list only appear once). I want to make this function without importing any functions. I'm trying to make my own function from scratch.

答:
For a number to be a mode, it must occur more number of times than at least one other number in the list, and it must not be the only number in the list. So, I refactored @mathwizurd's answer (to use the difference method) as follows:

```<code>def mode(array):
    '''
    returns a set containing valid modes
    returns a message if no valid mode exists
      - when all numbers occur the same number of times
      - when only one number occurs in the list
      - when no number occurs in the list
    '''
    most = max(map(array.count, array)) if array else None
    mset = set(filter(lambda x: array.count(x) == most, array))
    return mset if set(array) - mset else "list does not have a mode!"
</code>```

These tests pass successfully:

```<code>mode([]) == None
mode([1]) == None
mode([1, 1]) == None
mode([1, 1, 2, 2]) == None
</code>```

Title: Finding the mode of a list

Body:
For a number to be a mode, it must occur more number of times than at least one other number in the list, and it must not be the only number in the list. So, I refactored @mathwizurd's answer (to use the difference method) as follows:

def mode(array):
    '''
    returns a set containing valid modes
    returns a message if no valid mode exists
      - when all numbers occur the same number of times
      - when only one number occurs in the list
      - when no number occurs in the list
    '''
    most = max(map(array.count, array)) if array else None
    mset = set(filter(lambda x: array.count(x) == most, array))
    return mset if set(array) - mset else "list does not have a mode!"

These tests pass successfully:

mode([]) == None
mode([1]) == None
mode([1, 1]) == None
mode([1, 1, 2, 2]) == None


问:
Spark - Reduce List of key-value pair in Scala
I have a list of key-value pairs in a spark streaming context. How can I aggregate using reduce by the key in case of a list of key-value pairs?
Example: </p>

```<code>[("key1",2),("key2",3)]
[("key1",4),("key3",2)]
[("key2",4),("key3",2)]
</code>```

<p>The expected aggregated output: </p>

```<code>("key1", 6)
("key2", 7)
("key3", 4)
</code>```

答:
Flatten it first with flatMap then reduceByKey:

```<code>val rdd = sc.parallelize(Seq(Seq(("key1",2),("key2",3)), Seq(("key1",4),("key3",2)), Seq(("key2",4),("key3",2))))

rdd.flatMap(identity).reduceByKey(_+_).collect
// res2: Array[(String, Int)] = Array((key1,6), (key2,7), (key3,4))
</code>```

Body:
I have a list of key-value pairs in a spark streaming context. How can I aggregate using reduce by the key in case of a list of key-value pairs?
Example:

[("key1",2),("key2",3)]
[("key1",4),("key3",2)]
[("key2",4),("key3",2)]

The expected aggregated output:

("key1", 6)
("key2", 7)
("key3", 4)

Body:
Flatten it first with flatMap then reduceByKey:

val rdd = sc.parallelize(Seq(Seq(("key1",2),("key2",3)), Seq(("key1",4),("key3",2)), Seq(("key2",4),("key3",2))))

rdd.flatMap(identity).reduceByKey(_+_).collect
// res2: Array[(String, Int)] = Array((key1,6), (key2,7), (key3,4))


问:
Create a cocoa button that accepts keyboard input
Hey everyone, thanks for all your help so far, I've learned a whole lot in a short amount of time.

What I've done so far is to create a small calculator program and it works nicely.  To complete this version of it, what I'd like to do is make my "keys" on the calculator interface accept input from my keyboard presses.  So, for example, if I want to add 2 and 4, instead of clicking my "2" and "4" buttons, I can just press them on my numeric keypad instead.

I know it has something to do with giving my buttons focus but I can't figure out how to make them respond to keydown events.

I'm looking around on the apple developer documentation as well, so if I find the answers before you guys can then I'll try what I find out, and if it doesn't work I'll post with my progress.

Again, thanks everyone for your help!

答: If you're using interface builder, just set the "Key Equivalent" field to be your number.

ContentLicense: CC BY-SA 2.5


问:
Parallel processing in perl to write array entries to db
I have a program written in perl (Perl Version 5.10.1 running under Linux) that generates an array. Each entry of the array is another array. Each of these last arrays contains a set of 7 values that I need to write to a database. Currently I run a loop over the array of arrays and write the info to the database. As these writes are independent of each other I was thinking that I could run several processes in parallel.

Below is the basic loop I currently use that I would like to split into parallel processes. I need to do this in parallel as the initial array of arrays contains around 100,000 entries, which takes about 30 minutes to add the entries to the database.

```<code>for my $icell (0 .. scalar @Sheet_Cells_Data-1){
    my $Cell_Data_INTER1=$Sheet_Cells_Data[$icell];
    my @Cell_Data=@$Cell_Data_INTER1;
    $insert_to_db->execute($Cell_Data[0],$Cell_Data[1],$Cell_Data[2],$Cell_Data[3],$Cell_Data[4],$Cell_Data[5],$Cell_Data[6]);
}
</code>```

So, would this be possible and if so how would I go about achieving it.

Any help much appreciated

Chazg76

答:
One way to achieve this parallel processing is using fork.
Something like below

Let's say we will make 5 parallel process to do the insert work. Here is the code:

```<code>my $max_proc   = 5;
my $batch_size = scalar @Sheet_Cells_Data / $max_proc;
my $start_point = 0;

for (1 .. $max_proc) {
    if (fork()) {
        #In Parent
        $start_point += $batch_size;
    } else {
        #In Child
        my $end_point = $start_point + $batch_size -1;
        for my $i ($start_point .. $end_point){
           #Do you insert work here
        }

        exit;
    }
}
</code>```

Few points to take care:

```<code>1. Wait for all the child process to finish before parent process ends.
2. You might have to initialize new database connection in each child and close them before child process ends.
</code>```

Body:
I have a program written in perl (Perl Version 5.10.1 running under Linux) that generates an array. Each entry of the array is another array. Each of these last arrays contains a set of 7 values that I need to write to a database. Currently I run a loop over the array of arrays and write the info to the database. As these writes are independent of each other I was thinking that I could run several processes in parallel.

Below is the basic loop I currently use that I would like to split into parallel processes. I need to do this in parallel as the initial array of arrays contains around 100,000 entries, which takes about 30 minutes to add the entries to the database.

for my $icell (0 .. scalar @Sheet_Cells_Data-1){
    my $Cell_Data_INTER1=$Sheet_Cells_Data[$icell];
    my @Cell_Data=@$Cell_Data_INTER1;
    $insert_to_db->execute($Cell_Data[0],$Cell_Data[1],$Cell_Data[2],$Cell_Data[3],$Cell_Data[4],$Cell_Data[5],$Cell_Data[6]);
}

So, would this be possible and if so how would I go about achieving it.

Any help much appreciated

Chazg76

Body:
One way to achieve this parallel processing is using fork.
Something like below

Let's say we will make 5 parallel process to do the insert work. Here is the code:

my $max_proc   = 5;
my $batch_size = scalar @Sheet_Cells_Data / $max_proc;
my $start_point = 0;

for (1 .. $max_proc) {
    if (fork()) {
        #In Parent
        $start_point += $batch_size;
    } else {
        #In Child
        my $end_point = $start_point + $batch_size -1;
        for my $i ($start_point .. $end_point){
           #Do you insert work here
        }

        exit;
    }
}

Few points to take care:

1. Wait for all the child process to finish before parent process ends.
2. You might have to initialize new database connection in each child and close them before child process ends.


问:
Is there a way to elegantly "swap" rows in all foreign key and many to many fields in django?
I have a class let's call it Entity it's a container for a label and a type and then I have many other models like Store, Purchase... And they have a relationship like so:

```<code>class Store(Model):
 store_name = TextField()
 entities = ManyToManyField(Entity)

class Purchase(Model):
 datetime = DatetimeField(auto=True)
 entity = ForeignKeyField(Entity)
</code>```

In this case, say that I have an entity that I end up wanting to "swap" for instance, at some time I had "CocaCola" and then I have "Coca Cola", the user decides hey these two are the same, let's "merge them", effectively what I need to do is delete CocaCola or Coca Cola and swap all the keys out

so....

```<code>for p in Purchase.objects.filter(entity=cocacola_entity):
 p.entity = coca_cola_entity
 p.save()
for s in Purchase.objects.filter(entities=cocacola_entity):
 s.entities.remove(cocacola_entity)
 s.entities.add(coca_cola_entity)
 s.save()
cocacola_entity.delete()
</code>```

Is there a better way to handle this in a global context? I.e. "Django magically fetch me EVERYTHING with this row as a foreign key and swap it with the other one)

答:
You can use update() to update the foreign key:

```<code>Purchase.objects.filter(entity=cocacola_entity).update(entity=coca_cola_entity)
</code>```

You can also pass multiple items to add(), and then clear the other relation in case of a many-to-many field:

```<code>coca_cola_entity.store_set.add(*cocacola_entity.store_set.all())
cocacola_entity.store_set.clear()
</code>```

Body:
I have a class let's call it Entity it's a container for a label and a type and then I have many other models like Store, Purchase... And they have a relationship like so:

class Store(Model):
 store_name = TextField()
 entities = ManyToManyField(Entity)

class Purchase(Model):
 datetime = DatetimeField(auto=True)
 entity = ForeignKeyField(Entity)

In this case, say that I have an entity that I end up wanting to "swap" for instance, at some time I had "CocaCola" and then I have "Coca Cola", the user decides hey these two are the same, let's "merge them", effectively what I need to do is delete CocaCola or Coca Cola and swap all the keys out

so....

for p in Purchase.objects.filter(entity=cocacola_entity):
 p.entity = coca_cola_entity
 p.save()
for s in Purchase.objects.filter(entities=cocacola_entity):
 s.entities.remove(cocacola_entity)
 s.entities.add(coca_cola_entity)
 s.save()
cocacola_entity.delete()

Is there a better way to handle this in a global context? I.e. "Django magically fetch me EVERYTHING with this row as a foreign key and swap it with the other one)

Body:
You can use update() to update the foreign key:

Purchase.objects.filter(entity=cocacola_entity).update(entity=coca_cola_entity)

You can also pass multiple items to add(), and then clear the other relation in case of a many-to-many field:

coca_cola_entity.store_set.add(*cocacola_entity.store_set.all())
cocacola_entity.store_set.clear()


问:
Why character # is null on argv
I was working with argv to store characters from the command line. And I just noted that if I input # I got a null instead of character #.  Why is this happening?

```<code>#include <stdio.h>

int main(int argc,char *argv[])
{
    printf("%c",argv[1][0]);
}
</code>```

The code above works fine with any character, except # which returns Segmentation fault (core dumped) .

答:
The # character denotes the start of a comment to the shell, so it never gets to your program.  As a result, argv only has one element, i.e. argv[0], so accessing argv[1] is reading off the end of the array.  This invokes undefined behavior, which in this case manifests in a crash.

In order for the shell to pass this special character to your program, you need to quote it:

```<code>./myprogram "#"
</code>```

Title: Why character # is null on argv

Body:
I was working with argv to store characters from the command line. And I just noted that if I input # I got a null instead of character #.  Why is this happening?

#include <stdio.h>

int main(int argc,char *argv[])
{
    printf("%c",argv[1][0]);
}

The code above works fine with any character, except # which returns Segmentation fault (core dumped) .

Body:
The # character denotes the start of a comment to the shell, so it never gets to your program.  As a result, argv only has one element, i.e. argv[0], so accessing argv[1] is reading off the end of the array.  This invokes undefined behavior, which in this case manifests in a crash.

In order for the shell to pass this special character to your program, you need to quote it:

./myprogram "#"


问:
How to integrate Fuelux repeater in Aurelia?
I try to integrate Fuelux repeater in Aurelia app.  The problem is that the columns are not rendering :

答:
SOLVED. The problem was "columns" are defined in the Aurelia class. But in the ajax callback, "this" is undefined, the solution was to bind :</p>

```<code>defineRepeater() {
    let __this = this;
    // initialize the repeater
    ($('#myRepeater') as any).repeater({
        //init stuff
        dataSource: __this.customDataSource.bind(__this);
    });
}

customDataSource(options: any, callback) {
    let __this = this;
    ...
    columns: __this.columns
    ...
}
</code>```

Body:
SOLVED. The problem was "columns" are defined in the Aurelia class. But in the ajax callback, "this" is undefined, the solution was to bind :

defineRepeater() {
    let __this = this;
    // initialize the repeater
    ($('#myRepeater') as any).repeater({
        //init stuff
        dataSource: __this.customDataSource.bind(__this);
    });
}

customDataSource(options: any, callback) {
    let __this = this;
    ...
    columns: __this.columns
    ...
}


问:
How to import server list between pgadmin 4?
How to import/export server lists between pgadmin 4.2  between  computer (in Windows)?

I found some links for pgadmin 3 regarding registry. Would that be same for 4 too.

pgAdmin - Sharing DB Connection Definitions

答: According to https://stackoverflow.com/a/45823367/89346, configuration data seems to be available in C:\Users\{Your_User}\AppData\Roaming\pgAdmin. You may try to copy the pgAdmin directory across different machines

ContentLicense: CC BY-SA 4.0


问:
Override webservice addresses which is onanother dll at Web.Debug.config file
I work on a multi-layer solution, a web forms application. All the WebServices are under a project called WS. There are more than a hundred of them. And I call WS from Web Forms project.

I want to use the test services under the Debug configuration and live system under the Release conf.

app.config of WS library project is

```<code><applicationSettings>
  <WS.Properties.Settings>
    <setting name="settingName"
        serializeAs="String">
      <value>http://test.x.com/a.asmx</value>
    </setting>
  </WS.Properties.Settings>
</applicationSettings>
</code>```

So I added web.Config these lines

```<code><configSections>
  <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    ......

    <section name="WS.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </sectionGroup>
</configSections>

<applicationSettings>
  <WS.Properties.Settings>
    <setting name="settingName"
        serializeAs="String">
      <value>http://live.x.com/a.asmx</value>
    </setting>
  </WS.Properties.Settings>
</applicationSettings>
</code>```

Then it could launch live services.

in web.debug.config I've tried some transformation; however program still connects with the settings in web.debug (launches live services).

```<code><applicationSettings>
  <WS.Properties.Settings xdt:Transform="Replace" xdt:Locator="Match(name)">
    <setting name="settingName"
      serializeAs="String">
      <value>http://test.x.com/a.asmx</value>
    </setting>
 </WS.Properties.Settings>
</applicationSettings>
</code>```

How should I change the web.debug.config file in order to connect test services in debug configuration.

Thanks,

答:
This selection is only affects publish not debugging section. I've found it but I couldn't have time to share to answer.

It can be a better solution to use some preprocessor like

```<code>#if DEBUG
....
#endif
</code>```

Body:
I work on a multi-layer solution, a web forms application. All the WebServices are under a project called WS. There are more than a hundred of them. And I call WS from Web Forms project.

I want to use the test services under the Debug configuration and live system under the Release conf.

app.config of WS library project is

<applicationSettings>
  <WS.Properties.Settings>
    <setting name="settingName"
        serializeAs="String">
      <value>http://test.x.com/a.asmx</value>
    </setting>
  </WS.Properties.Settings>
</applicationSettings>

So I added web.Config these lines

<configSections>
  <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">

    ......

  </sectionGroup>
</configSections>

<applicationSettings>
  <WS.Properties.Settings>
    <setting name="settingName"
        serializeAs="String">
      <value>http://live.x.com/a.asmx</value>
    </setting>
  </WS.Properties.Settings>
</applicationSettings>

Then it could launch live services.

in web.debug.config I've tried some transformation; however program still connects with the settings in web.debug (launches live services).

<applicationSettings>
  <WS.Properties.Settings xdt:Transform="Replace" xdt:Locator="Match(name)">
    <setting name="settingName"
      serializeAs="String">
      <value>http://test.x.com/a.asmx</value>
    </setting>
 </WS.Properties.Settings>
</applicationSettings>

How should I change the web.debug.config file in order to connect test services in debug configuration.

Thanks,

Body:
This selection is only affects publish not debugging section. I've found it but I couldn't have time to share to answer.

It can be a better solution to use some preprocessor like

#if DEBUG
....
#endif


问:
Store data between controllers as uique
I have a controller which, I have expected, will contain unique data, gather as follow:

```<code>        setInterval(function() {

            dataStorage.setData('maxTime',maxTime);
            dataStorage.setData('currentTime',currentTime);
            dataStorage.setData('previousTime',previousTime);

            var dMaxTime = dataStorage.getData('maxTime');
            var dCurrentTime = dataStorage.getData('currentTime');
            var dPreviousTime = dataStorage.getData('previousTime');

            $log.debug("Max time  " + dMaxTime);
            $log.debug("Current time " + dCurrentTime);
            $log.debug("Previous time " + dPreviousTime)

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

which uses simple factory to capture data between controllers

```<code>myApp.factory('dataStorage', [function() {

    var dataInfo = [];

    return {

        setData: function (key, data) {
            dataInfo[key] = data;
        },
        getData: function (key) {
            return dataInfo[key];
        }

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

but when I go back and forth to the view which has first code above it stores the same variables again but with different (updated values) and then displays them in the log as how many times that view with controller was hit.

Is there any way to prevent that and to have stored only most recent captured data?

答:
When the controller is destroyed, you need to clear your interval, otherwise it continues to run.</p>

```<code>app.controller('SomeCtrl', ['$scope', function($scope) {

  var interval = setInterval(function() {
    console.log('whatever')
  }, 2000);

  $scope.$on('$destroy', function() {
    clearInterval(interval);
  });

}]);
</code>```

Title: Store data between controllers as uique

Body:
I have a controller which, I have expected, will contain unique data, gather as follow:

        setInterval(function() {

            dataStorage.setData('maxTime',maxTime);
            dataStorage.setData('currentTime',currentTime);
            dataStorage.setData('previousTime',previousTime);

            var dMaxTime = dataStorage.getData('maxTime');
            var dCurrentTime = dataStorage.getData('currentTime');
            var dPreviousTime = dataStorage.getData('previousTime');

            $log.debug("Max time  " + dMaxTime);
            $log.debug("Current time " + dCurrentTime);
            $log.debug("Previous time " + dPreviousTime)

        }, 2000);

which uses simple factory to capture data between controllers

myApp.factory('dataStorage', [function() {

    var dataInfo = [];

    return {

        setData: function (key, data) {
            dataInfo[key] = data;
        },
        getData: function (key) {
            return dataInfo[key];
        }

    };
}]);

but when I go back and forth to the view which has first code above it stores the same variables again but with different (updated values) and then displays them in the log as how many times that view with controller was hit.

Is there any way to prevent that and to have stored only most recent captured data?

Body:
When the controller is destroyed, you need to clear your interval, otherwise it continues to run.

app.controller('SomeCtrl', ['$scope', function($scope) {

  var interval = setInterval(function() {
    console.log('whatever')
  }, 2000);

  $scope.$on('$destroy', function() {
    clearInterval(interval);
  });

}]);


问:
Internal server error ajax submission
I have a function that triggers on a button click that passes the following argument: insertSongPlay(newSong.songID); when I console.log the newSong.songID I see a value of 90, which is desired.

This function is called here which runs an ajax call:

```<code>function insertSongPlay(songID)

{
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "/Album/InsertSongPlay/",
        data: JSON.stringify({ "songID": songID }),
        success: function(data)
        {

            console.log("submitted");
            console.log(songID);
            //TODO: Indicate Success
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
            console.log(errorThrown);
        }
    });
}
</code>```

Here is the corresponding ajax url found in my AlbumController:

```<code>public JsonResult InsertSongPlay(int songID)
{
    try
    {
        EntityDataAccess.InsertSongPlay(songID);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}
</code>```

Then in my EntityDataAccess.cs the following is run from the InsertSongPlay entity data access:

```<code>public static SongPlayDaily InsertSongPlay(int songID)
{
    using(var Context = GetContext())
    {
        var currentSongPlay = Context.SongPlayDailies.FirstOrDefault(x => x.SongID == songID && x.PlayDate == DateTime.Now.Date);
        if (currentSongPlay != null)
            currentSongPlay.NumberOfPlays++;
        else
        {
            currentSongPlay = new SongPlayDaily();
            currentSongPlay.SongID = songID;
            currentSongPlay.PlayDate = DateTime.Now.Date;
            currentSongPlay.NumberOfPlays = 1;
            Context.SongPlayDailies.Add(currentSongPlay);
        }
        Context.SaveChanges();
        return currentSongPlay;
    }
}
</code>```

However, my ajax call always throws an error and prints Internal Server Error to the console log. The Visual Studio debug mode indicates some sort of circular reference error. I'm not quite sure where I'm going wrong.

Thanks!

答:
in post action you should use complex type for receive data from client.

try this

```<code>[HttpPost]
public JsonResult InsertSongPlay(SongModel songModel)
{
    try
    {
        EntityDataAccess.InsertSongPlay(songModel.songID);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}

public class SongModel{
    public int songID {get;set}
}
</code>```

Title: Internal server error ajax submission

Body:
I have a function that triggers on a button click that passes the following argument: insertSongPlay(newSong.songID); when I console.log the newSong.songID I see a value of 90, which is desired.

This function is called here which runs an ajax call:

function insertSongPlay(songID)

{
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "/Album/InsertSongPlay/",
        data: JSON.stringify({ "songID": songID }),
        success: function(data)
        {

            console.log("submitted");
            console.log(songID);
            //TODO: Indicate Success
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
            console.log(errorThrown);
        }
    });
}

Here is the corresponding ajax url found in my AlbumController:

public JsonResult InsertSongPlay(int songID)
{
    try
    {
        EntityDataAccess.InsertSongPlay(songID);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}

Then in my EntityDataAccess.cs the following is run from the InsertSongPlay entity data access:

public static SongPlayDaily InsertSongPlay(int songID)
{
    using(var Context = GetContext())
    {
        var currentSongPlay = Context.SongPlayDailies.FirstOrDefault(x => x.SongID == songID && x.PlayDate == DateTime.Now.Date);
        if (currentSongPlay != null)
            currentSongPlay.NumberOfPlays++;
        else
        {
            currentSongPlay = new SongPlayDaily();
            currentSongPlay.SongID = songID;
            currentSongPlay.PlayDate = DateTime.Now.Date;
            currentSongPlay.NumberOfPlays = 1;
            Context.SongPlayDailies.Add(currentSongPlay);
        }
        Context.SaveChanges();
        return currentSongPlay;
    }
}

However, my ajax call always throws an error and prints Internal Server Error to the console log. The Visual Studio debug mode indicates some sort of circular reference error. I'm not quite sure where I'm going wrong.

Thanks!

Body:
in post action you should use complex type for receive data from client.

try this

[HttpPost]
public JsonResult InsertSongPlay(SongModel songModel)
{
    try
    {
        EntityDataAccess.InsertSongPlay(songModel.songID);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}

public class SongModel{
    public int songID {get;set}
}


问:
How to call a model method from rails view through a controller?
Please bear with me. I went through similar questions here but my requirement is quiet different.

I have a model called RideLaterRequest. In the app I am allowing the user to create a record on this model. And currently once the record is saved a notification is being sent to a android app. The logic is as follows:

ride_later_request.rb

```<code>class RideLaterRequest < ActiveRecord::Base

   after_save :send_notif #run send_notif method once the record is saved.

   def send_notif
      RideLaterRequestHandler.ride_later_request_created(self)
   end

end
</code>```

The above method actually calls another class method (the earlier developer defined a method in a separate class)

```<code>class RideLaterRequestHandler
    def self.ride_later_request_created(ride_later_request)
      #####................####
    end
end
</code>```

So once this method executes a notification is being sent to the android app.

Now I am trying to stop this automated system. And handle this flow manually by adding a button in view file.

First I stopped the automated notification by commenting after_save :send_notif in the ride_later_request.rb file. So now there are no notifications being sent once a new record is saved on that model.

In a view file I am displaying the records of RideLaterRequest model as follows:

admin_reports_controller.rb

```<code>class AdminReportsController < ApplicationController

  def trip_report
   @ride_later_request = RideLaterRequest.all
  end

end
</code>```

trip_report.html.erb

```<code><table>
   <tr>
      <th>Date</th>
      <th>Trip ID</th>
      <th>Send Notification</th>
   </tr>
   <% @ride_later_requests.each do |trip_report| %>
   <tr>
      <td><%= trip_report.planned_start_time.to_date%></td>
      <td><%= trip_report.id%></td>
      <td>
       <%= button_to "Send Notification", #In normal case I would have added a path to the controller method to Send notification here %>
      </td>
   </tr>
</table>
</code>```

As you can see I am trying add a button action where it sends the notification. The only thing I am trying to do here is, earlier the notifications were being sent once a new ride_later_request row was created. Now I am stopping that and trying to do it manually on a already saved record by adding a button. My question is is how can I call def send_notif model method that I have explained above in the beginning on this button that I am trying to give ?

I know this is app specific question but I have tried my best to make it rails specific by explaining it, I guess. Help is much appreciated.

答:
How about creating a send_notification action on your RideLaterRequestController and then (in routes.rb) setting up a send_nofication_ride_later_request path. Perhaps something like:

```<code>resources :ride_later_requests do
  member do
    post :send_nofication
  end
end
</code>```

Which yields:

```<code>send_nofication_ride_later_request POST   /ride_later_requests/:id/send_nofication(.:format)   ride_later_requests#send_nofication
                                   POST   /ride_later_requests(.:format)                       ride_later_requests#create
               ride_later_requests GET    /ride_later_requests(.:format)                       ride_later_requests#index
            new_ride_later_request GET    /ride_later_requests/new(.:format)                   ride_later_requests#new
           edit_ride_later_request GET    /ride_later_requests/:id/edit(.:format)              ride_later_requests#edit
                ride_later_request GET    /ride_later_requests/:id(.:format)                   ride_later_requests#show
                                   PATCH  /ride_later_requests/:id(.:format)                   ride_later_requests#update
                                   PUT    /ride_later_requests/:id(.:format)                   ride_later_requests#update
                                   DELETE /ride_later_requests/:id(.:format)                   ride_later_requests#destroy
</code>```

Then do something like:

```<code><%= link_to 'Send Notification', send_nofication_ride_later_request_path(trip_report), method: :post %>
</code>```

You can dress that link to look like a button.

Then, in your RideLaterRequestController, something like:

```<code>class RideLaterRequestController < ApplicationController

  ...

  def send_notification
    @ride_later_request = RideLaterRequest.find_by(id: params[:id])
    RideLaterRequestHandler.ride_later_request_created(@ride_later_request)
    # redirect, render, or whatever depending on whether you want this
    # to be AJAXy or regular HTML.
  end

  ...

end
</code>```

Body:
Please bear with me. I went through similar questions here but my requirement is quiet different.

I have a model called RideLaterRequest. In the app I am allowing the user to create a record on this model. And currently once the record is saved a notification is being sent to a android app. The logic is as follows:

ride_later_request.rb

class RideLaterRequest < ActiveRecord::Base

   after_save :send_notif #run send_notif method once the record is saved.

   def send_notif
      RideLaterRequestHandler.ride_later_request_created(self)
   end

end

The above method actually calls another class method (the earlier developer defined a method in a separate class)

class RideLaterRequestHandler
    def self.ride_later_request_created(ride_later_request)
      #####................####
    end
end

So once this method executes a notification is being sent to the android app.

Now I am trying to stop this automated system. And handle this flow manually by adding a button in view file.

First I stopped the automated notification by commenting after_save :send_notif in the ride_later_request.rb file. So now there are no notifications being sent once a new record is saved on that model.

In a view file I am displaying the records of RideLaterRequest model as follows:

admin_reports_controller.rb

class AdminReportsController < ApplicationController

  def trip_report
   @ride_later_request = RideLaterRequest.all
  end

end

trip_report.html.erb

      Date
      Trip ID
      Send Notification

   <% @ride_later_requests.each do |trip_report| %>

      <%= trip_report.planned_start_time.to_date%>
      <%= trip_report.id%>

       <%= button_to "Send Notification", #In normal case I would have added a path to the controller method to Send notification here %>

As you can see I am trying add a button action where it sends the notification. The only thing I am trying to do here is, earlier the notifications were being sent once a new ride_later_request row was created. Now I am stopping that and trying to do it manually on a already saved record by adding a button. My question is is how can I call def send_notif model method that I have explained above in the beginning on this button that I am trying to give ?

I know this is app specific question but I have tried my best to make it rails specific by explaining it, I guess. Help is much appreciated.

Body:
How about creating a send_notification action on your RideLaterRequestController and then (in routes.rb) setting up a send_nofication_ride_later_request path. Perhaps something like:

resources :ride_later_requests do
  member do
    post :send_nofication
  end
end

Which yields:

send_nofication_ride_later_request POST   /ride_later_requests/:id/send_nofication(.:format)   ride_later_requests#send_nofication
                                   POST   /ride_later_requests(.:format)                       ride_later_requests#create
               ride_later_requests GET    /ride_later_requests(.:format)                       ride_later_requests#index
            new_ride_later_request GET    /ride_later_requests/new(.:format)                   ride_later_requests#new
           edit_ride_later_request GET    /ride_later_requests/:id/edit(.:format)              ride_later_requests#edit
                ride_later_request GET    /ride_later_requests/:id(.:format)                   ride_later_requests#show
                                   PATCH  /ride_later_requests/:id(.:format)                   ride_later_requests#update
                                   PUT    /ride_later_requests/:id(.:format)                   ride_later_requests#update
                                   DELETE /ride_later_requests/:id(.:format)                   ride_later_requests#destroy

Then do something like:

<%= link_to 'Send Notification', send_nofication_ride_later_request_path(trip_report), method: :post %>

You can dress that link to look like a button.

Then, in your RideLaterRequestController, something like:

class RideLaterRequestController < ApplicationController

  ...

  def send_notification
    @ride_later_request = RideLaterRequest.find_by(id: params[:id])
    RideLaterRequestHandler.ride_later_request_created(@ride_later_request)
    # redirect, render, or whatever depending on whether you want this
    # to be AJAXy or regular HTML.
  end

  ...

end


问:
Bitbaking meta-mender-core error Apalis Imx6?
I want to install mender on my device Imx6, for that I added the layer meta-mender-core successfully, but when I try to bitbake vim for example I get:

```<code>rama@RR06:/oe-core/build$ bitbake vim
NOTE: Trying for parse version info from: gcc version 5.2.1 20151005 (Linaro GCC 5.2-2015.11-2)
NOTE: Trying for parse version info from: gcc version 5.2.1 20151005 (Linaro GCC 5.2-2015.11-2)
NOTE: Trying for parse version info from: gcc version 5.2.1 20151005 (Linaro GCC 5.2-2015.11-2)
Loading cache: 100% |#########################################################################################| ETA:  00:00:00
Loaded 983 entries from dependency cache.
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_2.1.1.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_2.0.0.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_2.0.1.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_git.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_1.0.0.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_2.0.2.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_2.1.0.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.3.0b1.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.2.1.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.1.1.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_git.bb
ERROR: ExpansionError during parsing /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_1.0.0.bb: Failure expanding variable GOPTESTBUILDFLAGS: SkipPackage: Unsupported CPU architecture: ${TUNE_ARCH}
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.1.0.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.0.0.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.2.0.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.0.1.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.1.2.bb

Summary: There was 1 ERROR message shown, returning a non-zero exit code.
</code>```

If I remove the meta-mender-core layer, vim bakes successfully.

I use Ubuntu 14.04, and the branch of mender is pyro

答:
I couldn't been sure*, but I think that the problem based on incompatible versions between poky and meta-mender-core.

This error tell's us that bitbake couldn't find definition of this variable GOPTESTBUILDFLAGS.

I'm assume that You are using pyro branch on poky or older, and there in go.bbclass definition of GOPTESTBUILDFLAGS in next release it's appear rocko go.bbclass. My proposal is to try update poky version to rocko branch.

With latest versions of poky, meta-mender-core and with meta-oe (here is vim recipe) I was able to 'bake' vim with this configuration layers.

*After changing to pyro branch (meta-mender-core) I couldn't find in any other files used GOPTESTBUILDFLAGS variable for reproduce this issue.

Body:
I want to install mender on my device Imx6, for that I added the layer meta-mender-core successfully, but when I try to bitbake vim for example I get:

rama@RR06:/oe-core/build$ bitbake vim
NOTE: Trying for parse version info from: gcc version 5.2.1 20151005 (Linaro GCC 5.2-2015.11-2)
NOTE: Trying for parse version info from: gcc version 5.2.1 20151005 (Linaro GCC 5.2-2015.11-2)
NOTE: Trying for parse version info from: gcc version 5.2.1 20151005 (Linaro GCC 5.2-2015.11-2)
Loading cache: 100% |#########################################################################################| ETA:  00:00:00
Loaded 983 entries from dependency cache.
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_2.1.1.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_2.0.0.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_2.0.1.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_git.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_1.0.0.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_2.0.2.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_2.1.0.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.3.0b1.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.2.1.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.1.1.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_git.bb
ERROR: ExpansionError during parsing /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender-artifact/mender-artifact_1.0.0.bb: Failure expanding variable GOPTESTBUILDFLAGS: SkipPackage: Unsupported CPU architecture: ${TUNE_ARCH}
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.1.0.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.0.0.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.2.0.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.0.1.bb
NOTE: Error during finalise of /home/rama/repositories/meta-mender/meta-mender-core/recipes-mender/mender/mender_1.1.2.bb

Summary: There was 1 ERROR message shown, returning a non-zero exit code.

If I remove the meta-mender-core layer, vim bakes successfully.

I use Ubuntu 14.04, and the branch of mender is pyro


问:
Can you help me fix code to show the occurrence of items in a list, for only the first five items?
I created this file as part of homework for a class and already got 100%. However, the instructor had originally wanted to also show frequencies for only the first 5 items in each column. Here is the code.

```<code>#PE 8
#11-2-17

def main():
    #import data
    winninglist=get_data()

    #find frequency for lotterynumber 1-69
    frequency=find_frequency(winninglist)

    #sort the frequency
    sortedlist=sorting(frequency)

    print("The 10 most common numbers and their corresponding frequencies are: ")
    print(sortedlist[:10])

    print("The 10 least common numbers and their corresponding frequencies are: ")
    print(sortedlist[-10:])

    #find the 10 most overdue numbers

    #find the frequency of 1-69 for the regular numbers, and 1-26 for powerball

def get_data():

    #read from the file
    infile=open('power.txt','r')
    lines=infile.readlines()
    infile.close()

    #initialize winninglist
    winninglist=[]

    #processraw data line by line, taking away new character lines, split using space, add to winninglist
    for i in range(len(lines)):
        lines[i]=lines[i].rstrip('\n')
        item=lines[i].split()
        winninglist+=item

    return winninglist

def find_frequency(winninglist):
    #frequency should be a list
    frequency=[0]*69

    #count the occurance of each number

    for i in range(69):
        for item in winninglist:
            if int(item)==(i+1):
               frequency[i]+=1

    #print(frequency)
    return frequency

def sorting(frequency):

    #record both the number and frequency
    pb_frequency=[]

    for i in range(len(frequency)):
        pb_frequency.append([i+1, frequency[i]])

    #print(pb_frequency)
    #now sort using bubble sorting
    for i in range(len(pb_frequency)):
        max=i
        for j in range(i+1, (len(pb_frequency))):
            if pb_frequency[j][1]>pb_frequency[max][1]:
                max=j

        #max has the index of the highest frequency number for this round
        #we make the exchange to bubble the largest one
        temp1=pb_frequency[i][0]
        temp2=pb_frequency[i][1]
        pb_frequency[i][0]=pb_frequency[max][0]
        pb_frequency[i][1]=pb_frequency[max][1]
        pb_frequency[max][0]=temp1
        pb_frequency[max][1]=temp2
    #print(pb_frequency)
    return pb_frequency

main()
</code>```

Here is the format of the txt file:

17 22 36 37 52 24

14 22 52 54 59 04

05 08 29 37 38 24

10 14 30 40 51 01

This is how the original file looks, and I thought it would be easy to do the rest. But, I have been struggling. I tried doing a split [0:5] and appending the results to determine the frequency after that, but could never make it work (kept getting one error after another). Could anyone help steer me in the right direction?

答:
I think I get your question now and think that your code needs only a minor change:

When you are appending list to your returning list (winninglist), slice the last index of the appending list.

Do the following:

change

```<code>winninglist+=item
</code>```

to

```<code>winninglist+=item[0:len(item)-1]
</code>```

Body:
I created this file as part of homework for a class and already got 100%. However, the instructor had originally wanted to also show frequencies for only the first 5 items in each column. Here is the code.

#PE 8
#11-2-17

def main():
    #import data
    winninglist=get_data()

    #find frequency for lotterynumber 1-69
    frequency=find_frequency(winninglist)

    #sort the frequency
    sortedlist=sorting(frequency)

    print("The 10 most common numbers and their corresponding frequencies are: ")
    print(sortedlist[:10])

    print("The 10 least common numbers and their corresponding frequencies are: ")
    print(sortedlist[-10:])

    #find the 10 most overdue numbers

    #find the frequency of 1-69 for the regular numbers, and 1-26 for powerball

def get_data():

    #read from the file
    infile=open('power.txt','r')
    lines=infile.readlines()
    infile.close()

    #initialize winninglist
    winninglist=[]

    #processraw data line by line, taking away new character lines, split using space, add to winninglist
    for i in range(len(lines)):
        lines[i]=lines[i].rstrip('\n')
        item=lines[i].split()
        winninglist+=item

    return winninglist

def find_frequency(winninglist):
    #frequency should be a list
    frequency=[0]*69

    #count the occurance of each number

    for i in range(69):
        for item in winninglist:
            if int(item)==(i+1):
               frequency[i]+=1

    #print(frequency)
    return frequency

def sorting(frequency):

    #record both the number and frequency
    pb_frequency=[]

    for i in range(len(frequency)):
        pb_frequency.append([i+1, frequency[i]])

    #print(pb_frequency)
    #now sort using bubble sorting
    for i in range(len(pb_frequency)):
        max=i
        for j in range(i+1, (len(pb_frequency))):
            if pb_frequency[j][1]>pb_frequency[max][1]:
                max=j

        #max has the index of the highest frequency number for this round
        #we make the exchange to bubble the largest one
        temp1=pb_frequency[i][0]
        temp2=pb_frequency[i][1]
        pb_frequency[i][0]=pb_frequency[max][0]
        pb_frequency[i][1]=pb_frequency[max][1]
        pb_frequency[max][0]=temp1
        pb_frequency[max][1]=temp2
    #print(pb_frequency)
    return pb_frequency

main()

Here is the format of the txt file:

17 22 36 37 52 24

14 22 52 54 59 04

05 08 29 37 38 24

10 14 30 40 51 01

This is how the original file looks, and I thought it would be easy to do the rest. But, I have been struggling. I tried doing a split [0:5] and appending the results to determine the frequency after that, but could never make it work (kept getting one error after another). Could anyone help steer me in the right direction?

Body:
I think I get your question now and think that your code needs only a minor change:

When you are appending list to your returning list (winninglist), slice the last index of the appending list.

Do the following:

change

winninglist+=item

to

winninglist+=item[0:len(item)-1]


问:
Failed to upload packages to PyPI: 410 Gone
After pypi.python.org has been migrated to pypi.org, I got an error when trying to upload a package to PyPI using the command as usual:

python2.7 setup.py sdist upload

The error message is:

Upload failed (410): Gone (This API has been deprecated and removed from legacy PyPI in favor of using the APIs available in the new PyPI.org implementation of PyPI (located at https://pypi.org/). For more information about migrating your use of this API to PyPI.org, please see https://packaging.python.org/guides/migrating-to-pypi-org/#uploading. For more information about the sunsetting of this API, please see https://mail.python.org/pipermail/distutils-sig/2017-June/030766.html)

I looked into the solution mentioned in the message and then googled a little bit. Unfortunately, the solutions I found were not working, including updating my local ~/.pypirc file. Like this:

```<code>[distutils]
index-servers =
    pypi

[pypi]
repository:https://pypi.python.org/pypi   or  repository:https://upload.pypi.org/legacy/
username:yourusername
password:yourpassword
</code>```

I still got the same error message. What should I do?

答:
If you are looking for legacy solution, try updating your ~/.pypirc file to this

```<code>[distutils]
index-servers =
    pypi

[pypi]
repository: https://upload.pypi.org/legacy/
username: username
password: password
</code>```

And running

python setup.py sdist upload -r pypi

Not sure if it will work right away. Since I did multiple things in order to get it working such as

Updating both python and python3 (I am still on 2.7.12 and 3.5.2 though)

Installing twine if your system does not have it yet

Updating pip, setuptools and twine per phd's suggestion

Also pip3 install -U pip setuptools twine might help

Body:
After pypi.python.org has been migrated to pypi.org, I got an error when trying to upload a package to PyPI using the command as usual:

python2.7 setup.py sdist upload

The error message is:

Upload failed (410): Gone (This API has been deprecated and removed from legacy PyPI in favor of using the APIs available in the new PyPI.org implementation of PyPI (located at https://pypi.org/). For more information about migrating your use of this API to PyPI.org, please see https://packaging.python.org/guides/migrating-to-pypi-org/#uploading. For more information about the sunsetting of this API, please see https://mail.python.org/pipermail/distutils-sig/2017-June/030766.html)

I looked into the solution mentioned in the message and then googled a little bit. Unfortunately, the solutions I found were not working, including updating my local ~/.pypirc file. Like this:

[distutils]
index-servers =
    pypi

[pypi]
repository:https://pypi.python.org/pypi   or  repository:https://upload.pypi.org/legacy/
username:yourusername
password:yourpassword

I still got the same error message. What should I do?

Body:
If you are looking for legacy solution, try updating your ~/.pypirc file to this

[distutils]
index-servers =
    pypi

[pypi]
repository: https://upload.pypi.org/legacy/
username: username
password: password

And running

python setup.py sdist upload -r pypi

Not sure if it will work right away. Since I did multiple things in order to get it working such as

Updating both python and python3 (I am still on 2.7.12 and 3.5.2 though)

Installing twine if your system does not have it yet

Updating pip, setuptools and twine per phd's suggestion

Also pip3 install -U pip setuptools twine might help


问:
Can someone explain this behavior in javascript?
Tested in Firefox:</p>

```<code>a = [] + 0;
b = 0;

alert(a); // 0
alert(b); // 0

alert(!a); // false
alert(!b); // true
</code>```

答:
[] + 0 is a string.

When you write a + b in Javascript, the engine will convert both a and b to primitives.

If at least one of the resulting primitives is a string, it will perform string concatenation; otherwise, it will perform numeric addition.

To convert an object (such as an array) to a primitive, the engine will call valueOf(), and, if its result is not a primitive, will call toString().

For arrays, valueOf() returns the original array (which is not a primitive) and toString() returns comma-separated string of the array's contents.

Therefore, [] + 0 becomes "" + 0, which is "0".

Non-empty strings are never falsy.

Body:
Tested in Firefox:

a = [] + 0;
b = 0;

alert(a); // 0
alert(b); // 0

alert(!a); // false
alert(!b); // true


问:
Django - Paginate with another GET request; not working with just pagination page number
I'm building a page with pagination and a filter form (2 GET requests).  If the URL includes both pagination and filter results, something like /questions/?page=2&all_questions=on, it works fine.  It also works if it just has filter results, something like /questions/?all_questions=on.

However if it only has the pagination page result, something like /questions/?page=1, no results are shown.

So I figured I need to do something with the views so that if there is only a page number in the URL, a default filter will be given.  I know I probably need to add something to the Try and Except section of pagination, but I'm stumped as to the actual code I need to write.

```<code>def questions_index(request):

    user = request.user
    form = QuestionFilterForm(request.GET or None)
    question_list = []
    if not form.is_bound:
        question_list = Question.objects.all().order_by('-date_created')
    if form.is_valid():
        if form.cleaned_data['all_questions'] | (form.cleaned_data['general_questions'] & form.cleaned_data['location_all_gta']) == True:
            question_list = Question.objects.all().order_by('-date_created')
        elif form.cleaned_data['location_all_gta'] == True:
            question_list += Question.objects.filter(question_type=1).order_by('-date_created')
        else:
            if form.cleaned_data['general_questions'] == True:
                question_list += Question.objects.filter(question_type=2).order_by('-date_created')
            if form.cleaned_data['location_toronto'] == True:
                question_list += Question.objects.filter(location='1').order_by('-date_created')

    paginator = Paginator(question_list, 15)

    # Pagination
    page = request.GET.get('page')
    try:
        questions = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        questions = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        questions = paginator.page(paginator.num_pages)

    ### I need to write something here...
    except (url has no filter result)
        give default filter

    return render(request, 'questions_index.html', {'questions': questions, 'user': user, 'form': form})
</code>```

答:
Your problem is at the beginning, not at the end. When you write:

```<code>if not form.is_bound:
    question_list = Question.objects.all().order_by('-date_created')
</code>```

This condition will only be met if request.GET is empty. The is_bound method will return True if you give any data to it, no matter if the keys of the dictionary are not form fields (docs). In the case you described, request.GET will contain the page key only.

A possible solution is to rewrite this part as:

```<code>if not form.is_bound or (len(request.GET) == 1 and 'page' in request.GET):
    question_list = Question.objects.all().order_by('-date_created')
</code>```

Body:
I'm building a page with pagination and a filter form (2 GET requests).  If the URL includes both pagination and filter results, something like /questions/?page=2&all_questions=on, it works fine.  It also works if it just has filter results, something like /questions/?all_questions=on.

However if it only has the pagination page result, something like /questions/?page=1, no results are shown.

So I figured I need to do something with the views so that if there is only a page number in the URL, a default filter will be given.  I know I probably need to add something to the Try and Except section of pagination, but I'm stumped as to the actual code I need to write.

def questions_index(request):

    user = request.user
    form = QuestionFilterForm(request.GET or None)
    question_list = []
    if not form.is_bound:
        question_list = Question.objects.all().order_by('-date_created')
    if form.is_valid():
        if form.cleaned_data['all_questions'] | (form.cleaned_data['general_questions'] & form.cleaned_data['location_all_gta']) == True:
            question_list = Question.objects.all().order_by('-date_created')
        elif form.cleaned_data['location_all_gta'] == True:
            question_list += Question.objects.filter(question_type=1).order_by('-date_created')
        else:
            if form.cleaned_data['general_questions'] == True:
                question_list += Question.objects.filter(question_type=2).order_by('-date_created')
            if form.cleaned_data['location_toronto'] == True:
                question_list += Question.objects.filter(location='1').order_by('-date_created')

    paginator = Paginator(question_list, 15)

    # Pagination
    page = request.GET.get('page')
    try:
        questions = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        questions = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        questions = paginator.page(paginator.num_pages)

    ### I need to write something here...
    except (url has no filter result)
        give default filter

    return render(request, 'questions_index.html', {'questions': questions, 'user': user, 'form': form})

Body:
Your problem is at the beginning, not at the end. When you write:

if not form.is_bound:
    question_list = Question.objects.all().order_by('-date_created')

This condition will only be met if request.GET is empty. The is_bound method will return True if you give any data to it, no matter if the keys of the dictionary are not form fields (docs). In the case you described, request.GET will contain the page key only.

A possible solution is to rewrite this part as:

if not form.is_bound or (len(request.GET) == 1 and 'page' in request.GET):
    question_list = Question.objects.all().order_by('-date_created')


答:
I broke down the steps, after we get the dd1, we can merge it back to your df1, you can replace NaN by using fillna(0)

```<code>Newdf=pd.wide_to_long(df1,stubnames=['StartDate','EndDate'],i=['Name','ID1'],j='nnumer')
Newdf.StartDate=pd.to_datetime(Newdf.StartDate)
Newdf.EndDate=pd.to_datetime(Newdf.EndDate)
Newdf['New']=Newdf[['StartDate','EndDate']].apply(lambda x : [pd.date_range(x['StartDate'], x['EndDate'],freq='MS').tolist()],1)['StartDate']
Newdf=Newdf.set_index(['StartDate','EndDate'],append=True).New.apply(pd.Series).stack()
Newdf=Newdf.to_frame('Date').reset_index()
df2.Date=pd.to_datetime(df2.Date)
dd=Newdf.merge(df2,on=['ID1','Date'])
dd[['Id1_num','id2_num']]=dd[['Id1_num','id2_num']].mask(dd[['Id1_num','id2_num']]<10)
dd1=dd.groupby(['ID1','nnumer','StartDate','EndDate'])['Id1_num','id2_num'].agg(['mean','count']).unstack(1).groupby(level='ID1').ffill().bfill().reset_index(['StartDate','EndDate'],drop=True).drop_duplicates()

dd1
Out[626]:
       Id1_num                     id2_num
          mean       count            mean       count
nnumer       1     2     1    2          1     2     1    2
ID1
111       11.5  14.0   2.0  2.0  11.333333  12.0   3.0  3.0
112       11.5  11.5   2.0  2.0  19.000000  19.0   1.0  2.0
113       17.0  17.0   2.0  1.0  14.000000  14.0   1.0  1.0
114       13.0  13.0   3.0  3.0  13.000000  13.0   2.0  2.0
115       13.0   NaN   1.0  0.0  19.000000   NaN   1.0  0.0
</code>```

Updated

```<code>dd1.columns=dd1.columns.map(''.join)
dd1
Out[650]:
     Id1_nummean1  Id1_nummean2  Id1_numcount1  Id1_numcount2  id2_nummean1  \
ID1
111          11.5          14.0            2.0            2.0     11.333333
112          11.5          11.5            2.0            2.0     19.000000
113          17.0          17.0            2.0            1.0     14.000000
114          13.0          13.0            3.0            3.0     13.000000
115          13.0           NaN            1.0            0.0     19.000000
     id2_nummean2  id2_numcount1  id2_numcount2
ID1
111          12.0            3.0            3.0
112          19.0            1.0            2.0
113          14.0            1.0            1.0
114          13.0            2.0            2.0
115           NaN            1.0            0.0
</code>```

Title: Joining 2 df through look up in Python using Pandas

Body:
I'm having a headache with performing a join on data frames through look up:

df1,

Name ID1    StartDate1  EndDate1    StartDate2  EndDate2
ab   111    1/1/2017    3/1/2017    2/1/2017    4/1/2017
bc   112    2/1/2017    3/1/2017    2/1/2017    4/1/2017
cd   113    1/1/2017    2/1/2017    2/1/2017    4/1/2017
df   114    2/1/2017    4/1/2017    2/1/2017    4/1/2017
fe   115    4/1/2017    5/1/2017    2/1/2017    4/1/2017

df2,

ID1 ID2 Date     Id1_num  id2_num
111 10  1/1/2017    10      11
111 10  2/1/2017            10
111 10  3/1/2017    13      13
111 10  4/1/2017    15      13
112 20  2/1/2017    11      19
112 20  3/1/2017    12
112 20  4/1/2017            19
113 20  1/1/2017    17       5
113 20  2/1/2017    17      14
114 30  2/1/2017    11      13
114 30  3/1/2017    10
114 30  4/1/2017    18      13
115 30  4/1/2017    7        5
115 30  5/1/2017    13      19

I want my result df3,

Name   ID1    ID2   StartDate1  EndDate1    StartDate2  EndDate2    ID1Date1Count   ID1Date1Average   ID1Date2Count    ID1Date2Average    ID2Date1Count    ID2Date1Average    ID2Date2Count    ID2Date2Average
ab     111    10    1/1/2017    3/1/2017    2/1/2017    4/1/2017    2               11.5              2                14                 3                11.33              3                12
bc     112    20    2/1/2017    3/1/2017    2/1/2017    4/1/2017    2               11.5              2                11.5               1                19                 2                19
cd     113    20    1/1/2017    2/1/2017    2/1/2017    4/1/2017    2               17                1                17                 1                14                 1                14
df     114    30    2/1/2017    4/1/2017    2/1/2017    4/1/2017    3               13                3                13                 2                13                 2                13
fe     115    30    4/1/2017    5/1/2017    2/1/2017    4/1/2017    1               19                0                0                  1                19                 0                0

Where
ID1Date1Count is the entries count from the date interval [StartDate1, EndDate1],
ID1Date2Count is the entries count from the date interval [StartDate2, EndDate2]
ID2Date1Count is the entries count from the date interval [StartDate1, EndDate1]
ID2Date2Count is the entries count from the date interval [StartDate2, EndDate2]
Along with their average.
The extra condition here is that we do not include num if num < 10.

Thanks a bunch!

Body:
I broke down the steps, after we get the dd1, we can merge it back to your df1, you can replace NaN by using fillna(0)

Newdf=pd.wide_to_long(df1,stubnames=['StartDate','EndDate'],i=['Name','ID1'],j='nnumer')
Newdf.StartDate=pd.to_datetime(Newdf.StartDate)
Newdf.EndDate=pd.to_datetime(Newdf.EndDate)
Newdf['New']=Newdf[['StartDate','EndDate']].apply(lambda x : [pd.date_range(x['StartDate'], x['EndDate'],freq='MS').tolist()],1)['StartDate']
Newdf=Newdf.set_index(['StartDate','EndDate'],append=True).New.apply(pd.Series).stack()
Newdf=Newdf.to_frame('Date').reset_index()
df2.Date=pd.to_datetime(df2.Date)
dd=Newdf.merge(df2,on=['ID1','Date'])
dd[['Id1_num','id2_num']]=dd[['Id1_num','id2_num']].mask(dd[['Id1_num','id2_num']]<10)
dd1=dd.groupby(['ID1','nnumer','StartDate','EndDate'])['Id1_num','id2_num'].agg(['mean','count']).unstack(1).groupby(level='ID1').ffill().bfill().reset_index(['StartDate','EndDate'],drop=True).drop_duplicates()

dd1
Out[626]:
       Id1_num                     id2_num
          mean       count            mean       count
nnumer       1     2     1    2          1     2     1    2
ID1
111       11.5  14.0   2.0  2.0  11.333333  12.0   3.0  3.0
112       11.5  11.5   2.0  2.0  19.000000  19.0   1.0  2.0
113       17.0  17.0   2.0  1.0  14.000000  14.0   1.0  1.0
114       13.0  13.0   3.0  3.0  13.000000  13.0   2.0  2.0
115       13.0   NaN   1.0  0.0  19.000000   NaN   1.0  0.0

Updated

dd1.columns=dd1.columns.map(''.join)
dd1
Out[650]:
     Id1_nummean1  Id1_nummean2  Id1_numcount1  Id1_numcount2  id2_nummean1  \
ID1
111          11.5          14.0            2.0            2.0     11.333333
112          11.5          11.5            2.0            2.0     19.000000
113          17.0          17.0            2.0            1.0     14.000000
114          13.0          13.0            3.0            3.0     13.000000
115          13.0           NaN            1.0            0.0     19.000000
     id2_nummean2  id2_numcount1  id2_numcount2
ID1
111          12.0            3.0            3.0
112          19.0            1.0            2.0
113          14.0            1.0            1.0
114          13.0            2.0            2.0
115           NaN            1.0            0.0