问:
Unable to merge dex error in android studio 3.0
I am looking for the answer that can help me to solve this problem. I am trying to solve this problem for last 2 days.But still, I didn't get the answer that can solve my problem. I have tried so many solutions which are given here.But no solution worked for me.
Please help me to solve this problem.Any help will be appreciated.

The actual problem is:

```<code>Error:Execution failed for task
':app:transformDexArchiveWithExternalLibsDexMergerForGlobalServerDebug'.
 java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
</code>```

this is occurring every time when I run my existing project on android studio 3.0

I have tried so many solutions for this like:

1- To add mutidexenabled true in gradle

2- To change the version of dependencies

3- To change the compile keyword with the implementation

4- To clean and rebuild the project

5- Delete the Gradle file(this was so difficult because when you again
  restarted the project no Gradle file will be auto-regenerated)  etc.

I am looking for the solutions which are other than those which are mentioned above. Please help me out. Please...

code of gradle file is given below:

```<code>apply plugin: 'com.android.application'
buildscript {
    repositories {
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'io.fabric'

repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }

    flatDir {
        dirs 'libs'
    }
}
repositories {
    maven { url 'http://clojars.org/repo' }
}

android {
    signingConfigs {
        config {
            keyAlias 'example'
            keyPassword 'example'
            storeFile file('/Users/standarduser/Documents/Android_Projects/example.jks')
            storePassword '@@@@@@@@'
        }
    }
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId 'com.example.example'
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 9  // both Latest
        versionName "2.0.7"
        multiDexEnabled true
        useLibrary 'org.apache.http.legacy'
        vectorDrawables.useSupportLibrary = true
        signingConfig signingConfigs.config
    }
    dexOptions {
        incremental = true
        preDexLibraries = false
        javaMaxHeapSize "4g"
    }
    aaptOptions.cruncherEnabled = false
    aaptOptions.useNewCruncher = false
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
    android {
        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'
                }
    }

    lintOptions{
        abortOnError false
    }
}

dependencies {
    compile files('libs/httpcore-4.4.1.jar')
    compile('com.twitter.sdk.android:twitter:2.1.1@aar') { //1.6.1@aar
        transitive = true;
    }
    compile('com.github.afollestad.material-dialogs:core:0.8.5.2@aar') {
        transitive = true
    }
    compile('io.socket:socket.io-client:0.8.2') { // 0.6.3
        // excluding org.json which is provided by Android
        exclude group: 'org.json', module: 'json'
    }
    testCompile 'junit:junit:4.12'
    compile 'com.writingminds:FFmpegAndroid:0.3.2'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'io.nlopez.smartlocation:library:3.2.9'
    //   compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.gms:play-services-appinvite:9.8.0'
    //9.0.1
    compile 'com.google.android.gms:play-services-gcm:9.8.0'
    compile 'com.google.android.gms:play-services-location:9.8.0'
    compile 'com.google.android.gms:play-services-places:9.8.0'
    compile 'com.google.android.gms:play-services-maps:9.8.0'
    compile 'com.google.android.gms:play-services-ads:9.8.0'
    compile 'com.google.android.gms:play-services-auth:9.8.0'
    compile 'com.google.android.gms:play-services-plus:9.8.0'
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:design:25.0.1'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.google.code.gson:gson:2.4'
    compile 'org.apache.httpcomponents:httpmime:4.3.5'
//    implementation 'org.apache.httpcomponents:httpmime:4.3.6'
//    implementation 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.facebook.android:facebook-android-sdk:4.23.0'
    compile 'com.pusher:pusher-java-client:1.1.2'
    compile 'com.android.support:recyclerview-v7:25.0.1'
    compile 'com.android.support:cardview-v7:25.0.1'
    compile 'com.daimajia.swipelayout:library:1.2.0@aar'
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.6'
    compile 'com.amazonaws:aws-android-sdk-mobileanalytics:2.2.9'
    compile 'com.commit451:PhotoView:1.2.4'
    compile 'commons-lang:commons-lang:2.3'
    compile 'com.karumi:dexter:2.3.1'
    compile 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
    implementation 'com.android.support:multidex:1.0.2'
    compile 'org.ocpsoft.prettytime:prettytime:3.2.7.Final'
    compile 'com.koushikdutta.async:androidasync:2.+'
    compile 'com.soundcloud.android:android-crop:1.0.1@aar'
    compile 'net.danlew:android.joda:2.9.4.1'
    compile 'com.albinmathew:photo-crop-library:1.0.3'
    compile 'com.amazonaws:aws-android-sdk-core:2.2.+'
    compile 'com.amazonaws:aws-android-sdk-s3:2.2.+'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.wowza.gocoder.sdk.android:com.wowza.gocoder.sdk:1.0b7@aar'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.4@aar') {
        transitive = true;
    }
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    //    compile 'com.cocosw:bottomsheet:1.+@aar'
    compile project(':libbambuser7')
    compile 'com.squareup.okhttp:okhttp:2.0.0'
}

apply plugin: 'com.google.gms.google-services'
</code>```

答:
Add this in your build.gradle

```<code>android {
    defaultConfig {
       multiDexEnabled true
    }
}
</code>```

First sync gradle then

From the Build menu -> press the Clean Project button.

When task completed, press the Rebuild Project button from the Build menu.

compile is now deprecated so it's better to use implementation or api

hope this helps you.

Body:
I am looking for the answer that can help me to solve this problem. I am trying to solve this problem for last 2 days.But still, I didn't get the answer that can solve my problem. I have tried so many solutions which are given here.But no solution worked for me.
Please help me to solve this problem.Any help will be appreciated.

The actual problem is:

Error:Execution failed for task
':app:transformDexArchiveWithExternalLibsDexMergerForGlobalServerDebug'.
 java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

this is occurring every time when I run my existing project on android studio 3.0

I have tried so many solutions for this like:

1- To add mutidexenabled true in gradle

2- To change the version of dependencies

3- To change the compile keyword with the implementation

4- To clean and rebuild the project

5- Delete the Gradle file(this was so difficult because when you again
  restarted the project no Gradle file will be auto-regenerated)  etc.

I am looking for the solutions which are other than those which are mentioned above. Please help me out. Please...

code of gradle file is given below:

apply plugin: 'com.android.application'
buildscript {
    repositories {
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'io.fabric'

repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }

    flatDir {
        dirs 'libs'
    }
}
repositories {
    maven { url 'http://clojars.org/repo' }
}

android {
    signingConfigs {
        config {
            keyAlias 'example'
            keyPassword 'example'
            storeFile file('/Users/standarduser/Documents/Android_Projects/example.jks')
            storePassword '@@@@@@@@'
        }
    }
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId 'com.example.example'
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 9  // both Latest
        versionName "2.0.7"
        multiDexEnabled true
        useLibrary 'org.apache.http.legacy'
        vectorDrawables.useSupportLibrary = true
        signingConfig signingConfigs.config
    }
    dexOptions {
        incremental = true
        preDexLibraries = false
        javaMaxHeapSize "4g"
    }
    aaptOptions.cruncherEnabled = false
    aaptOptions.useNewCruncher = false
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
    android {
        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'
                }
    }

    lintOptions{
        abortOnError false
    }
}

dependencies {
    compile files('libs/httpcore-4.4.1.jar')
    compile('com.twitter.sdk.android:twitter:2.1.1@aar') { //1.6.1@aar
        transitive = true;
    }
    compile('com.github.afollestad.material-dialogs:core:0.8.5.2@aar') {
        transitive = true
    }
    compile('io.socket:socket.io-client:0.8.2') { // 0.6.3
        // excluding org.json which is provided by Android
        exclude group: 'org.json', module: 'json'
    }
    testCompile 'junit:junit:4.12'
    compile 'com.writingminds:FFmpegAndroid:0.3.2'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'io.nlopez.smartlocation:library:3.2.9'
    //   compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.gms:play-services-appinvite:9.8.0'
    //9.0.1
    compile 'com.google.android.gms:play-services-gcm:9.8.0'
    compile 'com.google.android.gms:play-services-location:9.8.0'
    compile 'com.google.android.gms:play-services-places:9.8.0'
    compile 'com.google.android.gms:play-services-maps:9.8.0'
    compile 'com.google.android.gms:play-services-ads:9.8.0'
    compile 'com.google.android.gms:play-services-auth:9.8.0'
    compile 'com.google.android.gms:play-services-plus:9.8.0'
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:25.3.0'
    compile 'com.android.support:design:25.0.1'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.google.code.gson:gson:2.4'
    compile 'org.apache.httpcomponents:httpmime:4.3.5'
//    implementation 'org.apache.httpcomponents:httpmime:4.3.6'
//    implementation 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.facebook.android:facebook-android-sdk:4.23.0'
    compile 'com.pusher:pusher-java-client:1.1.2'
    compile 'com.android.support:recyclerview-v7:25.0.1'
    compile 'com.android.support:cardview-v7:25.0.1'
    compile 'com.daimajia.swipelayout:library:1.2.0@aar'
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.6'
    compile 'com.amazonaws:aws-android-sdk-mobileanalytics:2.2.9'
    compile 'com.commit451:PhotoView:1.2.4'
    compile 'commons-lang:commons-lang:2.3'
    compile 'com.karumi:dexter:2.3.1'
    compile 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
    implementation 'com.android.support:multidex:1.0.2'
    compile 'org.ocpsoft.prettytime:prettytime:3.2.7.Final'
    compile 'com.koushikdutta.async:androidasync:2.+'
    compile 'com.soundcloud.android:android-crop:1.0.1@aar'
    compile 'net.danlew:android.joda:2.9.4.1'
    compile 'com.albinmathew:photo-crop-library:1.0.3'
    compile 'com.amazonaws:aws-android-sdk-core:2.2.+'
    compile 'com.amazonaws:aws-android-sdk-s3:2.2.+'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.wowza.gocoder.sdk.android:com.wowza.gocoder.sdk:1.0b7@aar'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.4@aar') {
        transitive = true;
    }
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    //    compile 'com.cocosw:bottomsheet:1.+@aar'
    compile project(':libbambuser7')
    compile 'com.squareup.okhttp:okhttp:2.0.0'
}

apply plugin: 'com.google.gms.google-services'

Body:
Add this in your build.gradle

android {
    defaultConfig {
       multiDexEnabled true
    }
}

First sync gradle then

From the Build menu -> press the Clean Project button.

When task completed, press the Rebuild Project button from the Build menu.

compile is now deprecated so it's better to use implementation or api

hope this helps you.


来源: stackexchange

问:
Sum values grouped by key in list of dict
I have a list of dicts and now I am trying to find the total jobs for each remote identifier.

In this case I am expecting  for the id 64 -> 11 jobs and 68 -> 0 jobs

```<code>[{
    'jobs': {
        'count': 4
    },
    'remote_identifier': {
        'id': '64'
    }
}, {
    'jobs': {
        'count': 0
    },
    'remote_identifier': {
        'id': '68'
    }
}, {
    'jobs': {
        'count': 7
    },
    'remote_identifier': {
        'id': '64'
    }
}]
</code>```

I already tried something like this, but I don't know how to adapt it to my needs, since that only counts the number of occurrences.

```<code>from collections import Counter
print Counter(item['remote_identifier']['id'] for item in items )
</code>```

答:
The simplest way is by using the itertools module, which provides the function groupby.

```<code>import itertools as it

def get_id(entry):
    return entry['remote_identifier']['id']

data.sort(key=get_id)
for key, group in it.groupby(data, get_id):
    print(key, sum(entry['jobs']['count'] for entry in group))
</code>```

Note that groupby assumes that the data is already sorted by the key you are using to group the elements in the data.

ContentLicense: CC BY-SA 3.0

Body:
I have a list of dicts and now I am trying to find the total jobs for each remote identifier.

In this case I am expecting  for the id 64 -> 11 jobs and 68 -> 0 jobs

[{
    'jobs': {
        'count': 4
    },
    'remote_identifier': {
        'id': '64'
    }
}, {
    'jobs': {
        'count': 0
    },
    'remote_identifier': {
        'id': '68'
    }
}, {
    'jobs': {
        'count': 7
    },
    'remote_identifier': {
        'id': '64'
    }
}]

I already tried something like this, but I don't know how to adapt it to my needs, since that only counts the number of occurrences.

from collections import Counter
print Counter(item['remote_identifier']['id'] for item in items )

Body:
The simplest way is by using the itertools module, which provides the function groupby.

import itertools as it

def get_id(entry):
    return entry['remote_identifier']['id']

data.sort(key=get_id)
for key, group in it.groupby(data, get_id):
    print(key, sum(entry['jobs']['count'] for entry in group))

Note that groupby assumes that the data is already sorted by the key you are using to group the elements in the data.


问:
Mongo DB privileges to insert data in a specific database?
I'm fighting to get my MongoDB container to work with authentication.

I created a database, and a user on that database with the dbAdmin role. But it seems this role is not enough to be able to insert data to the database, because when I run a script which populates my DB, I get this kind of error message:

```<code>error: not authorized on mydb to execute command { insert: "attachs", documents: 59, writeConcern: { getLastError: 1, w: 1 }, ordered: false }
</code>```

So I guess I need to add some other privileges for my user, but I can't figure out which are missing.

答:
To add to the above answer, for an existing user, you can use the db.grantRolesToUser() command to assign it readWrite role. E.g.

```<code>use test
db.grantRolesToUser("user1", [ "readWrite"] )
</code>```

Above grants user1 the readWrite role on the test database. I wrote a step by step tutorial on how to grant privileges to roles and roles to users recently. It might be useful.

Body:
I'm fighting to get my MongoDB container to work with authentication.

I created a database, and a user on that database with the dbAdmin role. But it seems this role is not enough to be able to insert data to the database, because when I run a script which populates my DB, I get this kind of error message:

error: not authorized on mydb to execute command { insert: "attachs", documents: 59, writeConcern: { getLastError: 1, w: 1 }, ordered: false }

So I guess I need to add some other privileges for my user, but I can't figure out which are missing.

Body:
To add to the above answer, for an existing user, you can use the db.grantRolesToUser() command to assign it readWrite role. E.g.

use test
db.grantRolesToUser("user1", [ "readWrite"] )

Above grants user1 the readWrite role on the test database. I wrote a step by step tutorial on how to grant privileges to roles and roles to users recently. It might be useful.


问:
How to fix context.password coming null in /Token request
Class: Startup

```<code>public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            //enable cors origin requests
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var myProvider = new ClinicServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(30),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
        }
    }
</code>```

Class: ClinicServerProvider

```<code> public class ClinicServerProvider : OAuthAuthorizationServerProvider
    {
        private readonly BoilerplateDbContext _context;

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            UnitOfWork uow = new UnitOfWork(_context);
            string epass = Crypto.EncryptString(context.Password);
            var user = uow.UserRepository.Get(x => x.Password == epass && x.UserName == context.UserName && x.IsActive==true).FirstOrDefault();
// Other custom code here.

}
}
</code>```

In the above method..
I am getting context.Password coming null always..

Is anybody knows what is the reason?

答:
On method GrantResourceOwnerCredentials once you add claims after validating the username password you need to add this claim:</p>

```<code>identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
</code>```

Body:
Class: Startup

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            //enable cors origin requests
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var myProvider = new ClinicServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(30),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
        }
    }

Class: ClinicServerProvider

 public class ClinicServerProvider : OAuthAuthorizationServerProvider
    {
        private readonly BoilerplateDbContext _context;

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            UnitOfWork uow = new UnitOfWork(_context);
            string epass = Crypto.EncryptString(context.Password);
            var user = uow.UserRepository.Get(x => x.Password == epass && x.UserName == context.UserName && x.IsActive==true).FirstOrDefault();
// Other custom code here.

}
}

In the above method..
I am getting context.Password coming null always..

Is anybody knows what is the reason?

Body:
On method GrantResourceOwnerCredentials once you add claims after validating the username password you need to add this claim:

identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));


问:
Empty String Validation Exception - DynamoDB
I have scoured the internet on how to fix this with little success...

I am parsing a CSV and putting the data into a table using DynamoDB.
Anytime there is a blank entry, I receive the error:

```<code>One or more parameter values were invalid: An AttributeValue may not contain an empty string
</code>```

For example:

```<code>Header: "Name","Age","Birth date"
Entry:  Brandon,22  <------ THROWS ERROR
</code>```

The problem is, I will never know if there are blanks or not in the CSV. But I still need to parse it even if there is.

I have attempted to re-assign the value of the empty string to something like "N/A" in an effort to subvert this error to no avail. Any suggestions?

EDIT: Code to add context.

```<code>var file = process.argv[2];
console.log("File: " + file);

var csv = require("fast-csv");

csv.fromPath(file, {
        headers: true,
        ignoreEmpty: true
    })
    .on("data", function(data) {
        // Uncomment to see CSV data
        // console.log(data);

        params = {
            TableName: tableName,
            Item: {
                RefID: {
                    S: data["Ref-ID"]
                },
                //lots more items
            }
        };

        //Validation loops to make sure the items are defined
        for (var key in params.Item) {
            for (var items in params.Item[key]) {
                var value = params.Item[key][items];
                if (value === undefined || value === "") {
                    value = "N/A";
            }
        }

        dynamodb.putItem(params, function(err, info) {
            if (err) {
                console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
            }
            else {
                console.log("Added item:", JSON.stringify(data, null, 2));
            }
        });
        // }

    })
    .on("end", function() {
        console.log("done");
    });
</code>```

答:
These functions work like a charm, just have to execute storageSerialize on your object before storing and storageDeserialize when you get an item.

You might want to get your object in the same state as in input.

Note: the code above is in Typescript, but you can easily adapt it

```<code>private storageSerialize(data: any) {
    Object.keys(data).forEach(function (key) {
        let val = data[key];
        if (val == null) {
            data[key] = "PLACEHOLDER_NULL"
        }
        if (val == "") {
            data[key] = "PLACEHOLDER_EMPTYSTRING"
        }
    });
    return data;
}

private storageDeserialize(data: any) {
    if (data !== undefined) {
        Object.keys(data).forEach(function (key) {
            let val = data[key];
            if (val == "PLACEHOLDER_NULL") {
                data[key] = null
            }
            if (val == "PLACEHOLDER_EMPTYSTRING") {
                data[key] = ""
            }
        });
    }
    return data;
}
</code>```

Body:
I have scoured the internet on how to fix this with little success...

I am parsing a CSV and putting the data into a table using DynamoDB.
Anytime there is a blank entry, I receive the error:

One or more parameter values were invalid: An AttributeValue may not contain an empty string

For example:

Header: "Name","Age","Birth date"
Entry:  Brandon,22  <------ THROWS ERROR

The problem is, I will never know if there are blanks or not in the CSV. But I still need to parse it even if there is.

I have attempted to re-assign the value of the empty string to something like "N/A" in an effort to subvert this error to no avail. Any suggestions?

EDIT: Code to add context.

var file = process.argv[2];
console.log("File: " + file);

var csv = require("fast-csv");

csv.fromPath(file, {
        headers: true,
        ignoreEmpty: true
    })
    .on("data", function(data) {
        // Uncomment to see CSV data
        // console.log(data);

        params = {
            TableName: tableName,
            Item: {
                RefID: {
                    S: data["Ref-ID"]
                },
                //lots more items
            }
        };

        //Validation loops to make sure the items are defined
        for (var key in params.Item) {
            for (var items in params.Item[key]) {
                var value = params.Item[key][items];
                if (value === undefined || value === "") {
                    value = "N/A";
            }
        }

        dynamodb.putItem(params, function(err, info) {
            if (err) {
                console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
            }
            else {
                console.log("Added item:", JSON.stringify(data, null, 2));
            }
        });
        // }

    })
    .on("end", function() {
        console.log("done");
    });

Body:
These functions work like a charm, just have to execute storageSerialize on your object before storing and storageDeserialize when you get an item.

You might want to get your object in the same state as in input.

Note: the code above is in Typescript, but you can easily adapt it

private storageSerialize(data: any) {
    Object.keys(data).forEach(function (key) {
        let val = data[key];
        if (val == null) {
            data[key] = "PLACEHOLDER_NULL"
        }
        if (val == "") {
            data[key] = "PLACEHOLDER_EMPTYSTRING"
        }
    });
    return data;
}

private storageDeserialize(data: any) {
    if (data !== undefined) {
        Object.keys(data).forEach(function (key) {
            let val = data[key];
            if (val == "PLACEHOLDER_NULL") {
                data[key] = null
            }
            if (val == "PLACEHOLDER_EMPTYSTRING") {
                data[key] = ""
            }
        });
    }
    return data;
}


问:
is there an automated way to attach many images each corresponding to one object?
i have paperclip and imagemagick and a db of 1000 objects.

is there an automated way to attach 1000 images each corresponding to one object?

答: You can write your own rake task.</p>

ContentLicense: CC BY-SA 2.5

Body: You can write your own rake task.


问:
How can I change the audio input from one device to another in web application using MVC?
We are building a web application in which a user can have video chat with other users. We would like to give them an option to switch audio input between PC's internal microphone to other input device. I tried searching on the internet about the same but didn't find any lead. </p>

答:
Assuming you're using opentok (because you used the opentok tag).

You can use the OT.getDevices API to list the available audio input devices. Then you can pass the device when you publish. Something like:

```<code>let publisher;
function publish(audioDeviceId) {
  if (publisher) {
    publisher.destroy();
  }
  publisher = OT.initPublisher(null, {
    audioSource: audioDeviceId
  });
}

publish();

OT.getDevices((err, devices) => {
  if (!err) {
    let select = document.querySelector('select');
    devices.filter(device => device.kind === 'audioInput').forEach(device => {
      let option = document.createElement('option');
      option.value = device.deviceId;
      option.innerHTML = device.label;
      select.appendChild(option);
    });
    select.addEventListener('change', () => {
      publish(event.target.value);
    });
  }
});
</code>```

You can see a working demo at https://jsbin.com/qibaba

Body:
Assuming you're using opentok (because you used the opentok tag).

You can use the OT.getDevices API to list the available audio input devices. Then you can pass the device when you publish. Something like:

let publisher;
function publish(audioDeviceId) {
  if (publisher) {
    publisher.destroy();
  }
  publisher = OT.initPublisher(null, {
    audioSource: audioDeviceId
  });
}

publish();

OT.getDevices((err, devices) => {
  if (!err) {
    let select = document.querySelector('select');
    devices.filter(device => device.kind === 'audioInput').forEach(device => {
      let option = document.createElement('option');
      option.value = device.deviceId;
      option.innerHTML = device.label;
      select.appendChild(option);
    });
    select.addEventListener('change', () => {
      publish(event.target.value);
    });
  }
});

You can see a working demo at https://jsbin.com/qibaba


问:
Select an input after its inserted using `Ember.run`
Updated — The problem with my solution below was with if statement around Ember.run. Removing it solved the problem, but my approach was also incorrect. Instead of scheduling the focus for after rendering, I should make a custom component as acorncom suggested.

Original Question:

I'm building a list of text inputs based on an array on my model. On newline I'd like to insert a new text field and then select it. I'm trying to do this with Ember.run.scheduleOnce, but the function I provide is never called.

I've reopened the textfield to expose a data-index attribute binding, and in my template am rendering:

```<code>{{#each model.entries as |entry index|}}
  {{input value=entry.text class='field--entry' data-index=index insert-newline=(action 'insertEntry' index)}}
{{/each}}
</code>```

In my controller:

```<code>actions: {
  insertEntry(index){
    // This works fine and a new textfield is added.
    this.get('model.entries').addObject({text: 'Example'});

    if (index){
      Ember.run.scheduleOnce('afterRender', this, function(){
        // This doesn't seem to work at all.
        console.log("This is never logged");
        $(".field--entry[data-index='" + index + 1 + "']").focus();
      });
    }
  }
}
</code>```

答:
There was a syntactic mistake in your template and I fixed it. I suspect that in your case the action was never called somehow. Can you check the twiddle I prepared for you? What it does is simply adding a new input and giving focus to it. I just changed the selection logic for jquery focusing to

```<code>Ember.$(`.field--entry:eq(${index+1})`).focus();
</code>```

and it simply works as expected.

Body:
Updated — The problem with my solution below was with if statement around Ember.run. Removing it solved the problem, but my approach was also incorrect. Instead of scheduling the focus for after rendering, I should make a custom component as acorncom suggested.

Original Question:

I'm building a list of text inputs based on an array on my model. On newline I'd like to insert a new text field and then select it. I'm trying to do this with Ember.run.scheduleOnce, but the function I provide is never called.

I've reopened the textfield to expose a data-index attribute binding, and in my template am rendering:

{{#each model.entries as |entry index|}}
  {{input value=entry.text class='field--entry' data-index=index insert-newline=(action 'insertEntry' index)}}
{{/each}}

In my controller:

actions: {
  insertEntry(index){
    // This works fine and a new textfield is added.
    this.get('model.entries').addObject({text: 'Example'});

    if (index){
      Ember.run.scheduleOnce('afterRender', this, function(){
        // This doesn't seem to work at all.
        console.log("This is never logged");
        $(".field--entry[data-index='" + index + 1 + "']").focus();
      });
    }
  }
}

Body:
There was a syntactic mistake in your template and I fixed it. I suspect that in your case the action was never called somehow. Can you check the twiddle I prepared for you? What it does is simply adding a new input and giving focus to it. I just changed the selection logic for jquery focusing to

Ember.$(`.field--entry:eq(${index+1})`).focus();

and it simply works as expected.


问:
Bash combining two for loops
Im trying to create a dynamic cronjob which executes a PHP script which needs a DB argument for specific directorys.

The Output should look like this:

```<code>/usr/bin/php /var/www/html/test.php db_test
</code>```

I got following:

```<code>    #!/bin/bash
    DIR="/var/www/html/*"
    PHP="/usr/bin/php"
    ACCOUNTS=$(ls -d $DIR)
    DBPREFIX="db_"
    DB=$( find /var/www/html/ -mindepth 1 -maxdepth 1 -type d | awk -F'/' '{print $5}' )

    for CUSTOMER in $ACCOUNTS
    do
            echo $PHP $CUSTOMER $DBPREFIX$DB
    done
</code>```

This outputs following:

```<code>/usr/bin/php /var/www/html/test.php db_test test2 test3 test4
</code>```

The Problem is that the DBPREFIX and DB vars need also to go trough a loop so that i get for every single db a complete command.

How am I able to do so?

答:
You seem to be looking for something like

```<code>for dir in /var/www/html/*/; do
    base=${dir#/var/www/html/}
    db=${base%/}
    echo php "$db" "db_$db"   # or maybe php "${dir%/}" "db_$db"?
done
</code>```

You could probably use something like find -printf "..." to accomplish much the same thing, but the -printf option to find is a GNU extension.

Title: Bash combining two for loops

Body:
Im trying to create a dynamic cronjob which executes a PHP script which needs a DB argument for specific directorys.

The Output should look like this:

/usr/bin/php /var/www/html/test.php db_test

I got following:

    #!/bin/bash
    DIR="/var/www/html/*"
    PHP="/usr/bin/php"
    ACCOUNTS=$(ls -d $DIR)
    DBPREFIX="db_"
    DB=$( find /var/www/html/ -mindepth 1 -maxdepth 1 -type d | awk -F'/' '{print $5}' )

    for CUSTOMER in $ACCOUNTS
    do
            echo $PHP $CUSTOMER $DBPREFIX$DB
    done

This outputs following:

/usr/bin/php /var/www/html/test.php db_test test2 test3 test4

The Problem is that the DBPREFIX and DB vars need also to go trough a loop so that i get for every single db a complete command.

How am I able to do so?

Body:
You seem to be looking for something like

for dir in /var/www/html/*/; do
    base=${dir#/var/www/html/}
    db=${base%/}
    echo php "$db" "db_$db"   # or maybe php "${dir%/}" "db_$db"?
done

You could probably use something like find -printf "..." to accomplish much the same thing, but the -printf option to find is a GNU extension.


问:
Why are previous array values being carried over in new loop?
I have the following code to populate checkbox fields in a gravity form. I have an array of field_ids I'm looping through with a foreach loop. $arr = array(5, 6, 7, 8, 9); I then have a second foreach loop with a query which is pulling data from the database.

The code is working however, each subsequent field_id is showing the results for that field_id and the previous ones. e.g field_id=6 is showing a list of checkbox fields for field_id=5 and field_id=6. field_id= 7 is showing a list of checkbox fields for field_id=5, field_id=6 and field_id=7 etc.

```<code>function populate_checkboxes( $form ){

    foreach( $form['fields'] as &$field )  {
        $arr = array(5, 6, 7, 8, 9);

        foreach($arr as $field_id){
          global $wpdb;
          $query = $wpdb->get_results( "SELECT sefer FROM bulk_import where field_id_select_items = {$field_id}" );
          foreach($query as $sefer){

            if ( $field->id != $field_id ) {continue;}
            $choices[] = array( 'text' => 'Select All', 'value' => 'Select_all' );
            $inputs[] = array( 'label' => 'Select All', 'id' => '1');
            //get all $sefer values
            $posts = get_posts(array(
            'post_type'=> array('learning_item'),   'suppress_filters' => 0, 'posts_per_page' => -1, 'order' => 'asc',
            'meta_query' => array(
                array( 'key' => 'taken',   'value' => '0'),
                array('key' => 'torah', 'value' => $sefer -> sefer)
            ),
            ));

            $input_id = 2;
            foreach( $posts as $post ) {
                //skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs)
                if ( $input_id % 10 == 0 ) {$input_id++;}
                $choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
                $inputs[] = array( 'label' => $post->post_title, 'id' => "{$field_id}.{$input_id}" );

                $input_id++;
            }

            $field->choices = $choices;
            $field->inputs = $inputs;

          }
            //reset query here?
             wp_reset_query();
        }

    }
    return $form;}
</code>```

Do I need to set a variable to empty somewhere in the array? Why is there being a carry through of data? How do I show only values connected to the specific field_id?

答:
At the beginning of each loop you need to reset the arrays where your building up the values.  It could be something like...

```<code>  foreach($query as $sefer){
        $choices = array();
        $inputs = array();

        if ( $field->id != $field_id ) {continue;}
</code>```

Unless you reset them, they still have the values from the previous loop.

Body:
I have the following code to populate checkbox fields in a gravity form. I have an array of field_ids I'm looping through with a foreach loop. $arr = array(5, 6, 7, 8, 9); I then have a second foreach loop with a query which is pulling data from the database.

The code is working however, each subsequent field_id is showing the results for that field_id and the previous ones. e.g field_id=6 is showing a list of checkbox fields for field_id=5 and field_id=6. field_id= 7 is showing a list of checkbox fields for field_id=5, field_id=6 and field_id=7 etc.

function populate_checkboxes( $form ){

    foreach( $form['fields'] as &$field )  {
        $arr = array(5, 6, 7, 8, 9);

        foreach($arr as $field_id){
          global $wpdb;
          $query = $wpdb->get_results( "SELECT sefer FROM bulk_import where field_id_select_items = {$field_id}" );
          foreach($query as $sefer){

            if ( $field->id != $field_id ) {continue;}
            $choices[] = array( 'text' => 'Select All', 'value' => 'Select_all' );
            $inputs[] = array( 'label' => 'Select All', 'id' => '1');
            //get all $sefer values
            $posts = get_posts(array(
            'post_type'=> array('learning_item'),   'suppress_filters' => 0, 'posts_per_page' => -1, 'order' => 'asc',
            'meta_query' => array(
                array( 'key' => 'taken',   'value' => '0'),
                array('key' => 'torah', 'value' => $sefer -> sefer)
            ),
            ));

            $input_id = 2;
            foreach( $posts as $post ) {
                //skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs)
                if ( $input_id % 10 == 0 ) {$input_id++;}
                $choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
                $inputs[] = array( 'label' => $post->post_title, 'id' => "{$field_id}.{$input_id}" );

                $input_id++;
            }

            $field->choices = $choices;
            $field->inputs = $inputs;

          }
            //reset query here?
             wp_reset_query();
        }

    }
    return $form;}

Do I need to set a variable to empty somewhere in the array? Why is there being a carry through of data? How do I show only values connected to the specific field_id?

Body:
At the beginning of each loop you need to reset the arrays where your building up the values.  It could be something like...

  foreach($query as $sefer){
        $choices = array();
        $inputs = array();

        if ( $field->id != $field_id ) {continue;}

Unless you reset them, they still have the values from the previous loop.


问:
float is not displaying the right format . looking for xxxxxx.xx
```<code>float fRealEsate = 360000.00 * 0.04;
 Toast.makeText(v.getContext(), "Real Estate Brokerage Fee: "
                     + fRealEsate, Toast.LENGTH_SHORT).show();
</code>```

I need it to display 15600.00 but its displaying 15600.0

答:
Use NumberFormat.

```<code>String sRealEstate = NumberFormat.getCurrencyInstance().format(fRealEstate);
</code>```

And use the formatted string version in your Toast rather than the float directly.

Body:
float fRealEsate = 360000.00 * 0.04;
 Toast.makeText(v.getContext(), "Real Estate Brokerage Fee: "
                     + fRealEsate, Toast.LENGTH_SHORT).show();

I need it to display 15600.00 but its displaying 15600.0

Body:
Use NumberFormat.

String sRealEstate = NumberFormat.getCurrencyInstance().format(fRealEstate);

And use the formatted string version in your Toast rather than the float directly.


问:
Flexbox media query overflowing divs
I got a problem that I need to solve. I am coding an admin panel. I am using flexbox and I have 3 divs next to each other. Code looks like this:

```<code><div class="content-boxes">
    <div class="content-box">
      <span>Something</span>
      <img src="image.png">
      <p>
        Number<br>
      </p>
    </div>

    <div class="content-box">
      <span>Something</span>
      <img src="image.png">
      <p>
        Number<br>
      </p>
    </div>

    <div class="content-box">
      <span>Something</span>
      <img src="image.png">
      <p>
        Number<br>
      </p>
    </div>
  </div>
</code>```

And CSS code (SASS):

```<code>.content-boxes{
  position: relative;
  @include flexbox();
  flex-flow: row wrap;
  width: 100%;
  height: 18%;
  justify-content: space-around;
  margin: 1vw 1vw 1vw 1vw;
  .content-box{
    @include flexbox();
    flex-flow: row wrap;
    width:23%;
    height:100%;
    background-color: $oc-red-8;
    justify-content: space-between;
    flex: 1;
    span{
      padding: 0.2vw;
      font-size: 3vh;
      color: $oc-gray-2;
      overflow: hidden;
      font-family: CaviarDreams;
      width: 100%;
    }
    p{
      padding: 1vw;
      font-size: 4vh;
      color: $oc-gray-2;
      overflow: hidden;
      font-family: CaviarDreams;
      text-align: right;
      align-self: center;
      margin-left: auto;
    }
    img{
      height: 50%;
      align-self: flex-start;
      margin-left: 1vw;
    }
  }
}
</code>```

My problem is that when I use media query and wants the boxes to be width: 100%; the other divs as flex are overflowing this one.

Media query code:

```<code>@media screen and (max-width: 650px){
  .content-boxes{
    .content-box{
       width: 100%;
    }
  }
}
</code>```

I wants all my divs under each other with width: 100%;

I hope I made myself clear, any suggestions ?

答:
You simply need to change the direction of the flex and make it column instead of row :</p>

```<code>@media screen and (max-width: 650px){
  .content-boxes{
    flex-direction:column;
  }
}
</code>```

Title: Flexbox media query overflowing divs

Body:
I got a problem that I need to solve. I am coding an admin panel. I am using flexbox and I have 3 divs next to each other. Code looks like this:

      Something

        Number

      Something

        Number

      Something

        Number

And CSS code (SASS):

.content-boxes{
  position: relative;
  @include flexbox();
  flex-flow: row wrap;
  width: 100%;
  height: 18%;
  justify-content: space-around;
  margin: 1vw 1vw 1vw 1vw;
  .content-box{
    @include flexbox();
    flex-flow: row wrap;
    width:23%;
    height:100%;
    background-color: $oc-red-8;
    justify-content: space-between;
    flex: 1;
    span{
      padding: 0.2vw;
      font-size: 3vh;
      color: $oc-gray-2;
      overflow: hidden;
      font-family: CaviarDreams;
      width: 100%;
    }
    p{
      padding: 1vw;
      font-size: 4vh;
      color: $oc-gray-2;
      overflow: hidden;
      font-family: CaviarDreams;
      text-align: right;
      align-self: center;
      margin-left: auto;
    }
    img{
      height: 50%;
      align-self: flex-start;
      margin-left: 1vw;
    }
  }
}

My problem is that when I use media query and wants the boxes to be width: 100%; the other divs as flex are overflowing this one.

Media query code:

@media screen and (max-width: 650px){
  .content-boxes{
    .content-box{
       width: 100%;
    }
  }
}

I wants all my divs under each other with width: 100%;

I hope I made myself clear, any suggestions ?

Body:
You simply need to change the direction of the flex and make it column instead of row :

@media screen and (max-width: 650px){
  .content-boxes{
    flex-direction:column;
  }
}


问:
How to remove all grid lines except left Y axis and bottom X axis using Charts ios?
In my app I'm using the iOS-Charts framework, and I figured out how to remove the grid (vertical and horizontal) by using:

```<code>barChartView.leftAxis.drawGridLinesEnabled = false
barChartView.rightAxis.drawGridLinesEnabled = false
</code>```

However, I still want to have left side Y axis and bottom X axis.

Any kind of help is highly appreciated.

答:
To Enable x and y axis alone </p>

```<code> yourView.leftAxis.drawZeroLineEnabled = true

yourView.rightAxis.drawZeroLineEnabled=true
</code>```

Body:
In my app I'm using the iOS-Charts framework, and I figured out how to remove the grid (vertical and horizontal) by using:

barChartView.leftAxis.drawGridLinesEnabled = false
barChartView.rightAxis.drawGridLinesEnabled = false

However, I still want to have left side Y axis and bottom X axis.

Any kind of help is highly appreciated.

Body:
To Enable x and y axis alone

 yourView.leftAxis.drawZeroLineEnabled = true

yourView.rightAxis.drawZeroLineEnabled=true


问:
Rails - Devise, Email Case Insensitivity
I'm using Devise with login credentials: email/password - no usernames

I just noticed that the login process is case sensitive for emails. so if you register with bob@apPle.com, and then try to log in with Bob@apple.com you get an error. Very confusing.

How can I make devise log people in with their email/password, and the email being case insensitive?

答:
I also had some solution which making work with email is case-insensitive for all Devise controllers (functionality):

```<code>class ApplicationController < ActionController::Base
...
...
  prepend_before_filter :email_to_downcase, :only => [:create, :update]
...
...
  private
...
...
  def email_to_downcase
    if params[:user] && params[:user][:email]
      params[:user][:email] = params[:user][:email].downcase
    end
  end
...
...
end
</code>```

I know it is not the best solution: it involves another controllers of another models and executes code which is not necessary for them. But it was just makeshift and it works (at least for me ;) ).

Kevin and Andres, thanks for your answers. It is really good solutions and useful. I wanted to vote them up, but I haven't enough reputation yet. So, I just tell 'thanks' to you. ;)

Lets wait for Devise 1.2

Body:
I also had some solution which making work with email is case-insensitive for all Devise controllers (functionality):

class ApplicationController < ActionController::Base
...
...
  prepend_before_filter :email_to_downcase, :only => [:create, :update]
...
...
  private
...
...
  def email_to_downcase
    if params[:user] && params[:user][:email]
      params[:user][:email] = params[:user][:email].downcase
    end
  end
...
...
end

I know it is not the best solution: it involves another controllers of another models and executes code which is not necessary for them. But it was just makeshift and it works (at least for me ;) ).

Kevin and Andres, thanks for your answers. It is really good solutions and useful. I wanted to vote them up, but I haven't enough reputation yet. So, I just tell 'thanks' to you. ;)

Lets wait for Devise 1.2


问:
Pandas - Fill column depending on date in dictionary
I am trying to fill a dataframe column with the value of two other columns depending on a date i have in a dictionary. It looks like this:

```<code># the input date
input_date = pd.to_datetime('04.12.2017 12:00:00', format='%d.%m.%Y %H:%M:%S')

# the dict
dict = {'A': pd.to_datetime('06.12.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'B': pd.to_datetime('08.11.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'C': pd.to_datetime('15.10.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),

# the df
d = {'result':[None,None,None],
     'id_1':[1,2,3], 'id_2':[10,20,30],
     'dict_key':['A', 'B', 'A']}
df = pd.DataFrame(d)
</code>```

My criteria is: If the input date is after the date in the dictonary, take id_1, else take id_2

The result would like this:

```<code>    dict_key    id_1    id_2    result
0   A           1       10      10
1   B           2       20      2
2   A           3       30      30
</code>```

答:
```<code>In [20]: df['result'] = np.where(df.dict_key.map(dct) >= input_date, df['id_2'], df['id_1'])

In [21]: df
Out[21]:
  dict_key  id_1  id_2  result
0        A     1    10      10
1        B     2    20       2
2        A     3    30      30
</code>```

where dct is a dictionary that is called dict in your question. We should try to avoid overwriting standard keywords (like list,dict, etc.).

Body:
I am trying to fill a dataframe column with the value of two other columns depending on a date i have in a dictionary. It looks like this:

# the input date
input_date = pd.to_datetime('04.12.2017 12:00:00', format='%d.%m.%Y %H:%M:%S')

# the dict
dict = {'A': pd.to_datetime('06.12.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'B': pd.to_datetime('08.11.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'C': pd.to_datetime('15.10.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),

# the df
d = {'result':[None,None,None],
     'id_1':[1,2,3], 'id_2':[10,20,30],
     'dict_key':['A', 'B', 'A']}
df = pd.DataFrame(d)

My criteria is: If the input date is after the date in the dictonary, take id_1, else take id_2

The result would like this:

    dict_key    id_1    id_2    result
0   A           1       10      10
1   B           2       20      2
2   A           3       30      30

Body:
In [20]: df['result'] = np.where(df.dict_key.map(dct) >= input_date, df['id_2'], df['id_1'])

In [21]: df
Out[21]:
  dict_key  id_1  id_2  result
0        A     1    10      10
1        B     2    20       2
2        A     3    30      30

where dct is a dictionary that is called dict in your question. We should try to avoid overwriting standard keywords (like list,dict, etc.).


问:
Why is django 2 available under python 2?
According to Django 2.0 release notes Django 2.0 onwards will only support python 3, making the 1.11.X the last release series to support python 2.

See quote from the release notes page:

Django 2.0 supports Python 3.4, 3.5, and 3.6. We highly recommend and only officially support the latest release of each series.

The Django 1.11.x series is the last to support Python 2.7.

However when running pip2 install Django, django version 2 is being installed (which then fails because it assumes functionality not available in python 2):

```<code>(venv-crap) mbp15:server nir$ pip2 install django
Collecting django
  Downloading Django-2.0.tar.gz (8.0MB)
    100% |████████████████████████████████| 8.0MB 177kB/s
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/PATH/django/setup.py", line 32, in <module>
        version = __import__('django').get_version()
      File "django/__init__.py", line 1, in <module>
        from django.utils.version import get_version
      File "django/utils/version.py", line 61, in <module>
        @functools.lru_cache()
    AttributeError: 'module' object has no attribute 'lru_cache'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/PATH/django/
</code>```

I know I can manually specify requirement version below 2, making pip install a version valid for python 2, however that will complicate the installation process if I want to support both python2 and python3, and would have assumed pip will know to install only versions compatible with the python it's running from.

My questions, therefore, as the following:

Why is pip attempting to install Django2 with python2 instead of automatically picking the last compatible version? Isn't that part of pips capabilities?

Is there a way to make a single requirements.txt that will install Django<2.0 when running from python2 and Django>=2.0 when running with python3?

答:
Why is pip attempting to install Django2 with python2 instead of automatically picking the last compatible version? Isn't that part of pips capabilities?

As Alasdair pointed out in the comments already, this is a known bug in Django: bug #28878.

Is there a way to make a single requirements.txt that will install Django<2.0 when running from python2 and Django>=2.0 when running with python3?

You can use the environment markers (see PEP 508):

```<code># requirements.txt
django>=1.11,<2.0; python_version<"3.4"
django>=2.0; python_version>="3.4"
</code>```

This will install one and skip another django dependency, depending on what python you are using:

```<code>$ pip2.7 install -r requirements.txt
Ignoring django: markers 'python_version >= "3.4"' don't match your environment
Collecting django<2.0 (from -r requirements.txt (line 1))
  Downloading Django-1.11.8-py2.py3-none-any.whl (6.9MB)
...

$ pip3.6 install -r requirements.txt
Ignoring django: markers 'python_version < "3.4"' don't match your environment
Collecting django>=2.0 (from -r requirements.txt (line 2))
  Using cached Django-2.0-py3-none-any.whl
...
</code>```

Body:
According to Django 2.0 release notes Django 2.0 onwards will only support python 3, making the 1.11.X the last release series to support python 2.

See quote from the release notes page:

Django 2.0 supports Python 3.4, 3.5, and 3.6. We highly recommend and only officially support the latest release of each series.

The Django 1.11.x series is the last to support Python 2.7.

However when running pip2 install Django, django version 2 is being installed (which then fails because it assumes functionality not available in python 2):

(venv-crap) mbp15:server nir$ pip2 install django
Collecting django
  Downloading Django-2.0.tar.gz (8.0MB)
    100% |████████████████████████████████| 8.0MB 177kB/s
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/PATH/django/setup.py", line 32, in <module>
        version = __import__('django').get_version()
      File "django/__init__.py", line 1, in <module>
        from django.utils.version import get_version
      File "django/utils/version.py", line 61, in <module>
        @functools.lru_cache()
    AttributeError: 'module' object has no attribute 'lru_cache'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/PATH/django/

I know I can manually specify requirement version below 2, making pip install a version valid for python 2, however that will complicate the installation process if I want to support both python2 and python3, and would have assumed pip will know to install only versions compatible with the python it's running from.

My questions, therefore, as the following:

Why is pip attempting to install Django2 with python2 instead of automatically picking the last compatible version? Isn't that part of pips capabilities?

Is there a way to make a single requirements.txt that will install Django<2.0 when running from python2 and Django>=2.0 when running with python3?

Body:
Why is pip attempting to install Django2 with python2 instead of automatically picking the last compatible version? Isn't that part of pips capabilities?

As Alasdair pointed out in the comments already, this is a known bug in Django: bug #28878.

Is there a way to make a single requirements.txt that will install Django<2.0 when running from python2 and Django>=2.0 when running with python3?

You can use the environment markers (see PEP 508):

# requirements.txt
django>=1.11,<2.0; python_version<"3.4"
django>=2.0; python_version>="3.4"

This will install one and skip another django dependency, depending on what python you are using:

$ pip2.7 install -r requirements.txt
Ignoring django: markers 'python_version >= "3.4"' don't match your environment
Collecting django<2.0 (from -r requirements.txt (line 1))
  Downloading Django-1.11.8-py2.py3-none-any.whl (6.9MB)
...

$ pip3.6 install -r requirements.txt
Ignoring django: markers 'python_version < "3.4"' don't match your environment
Collecting django>=2.0 (from -r requirements.txt (line 2))
  Using cached Django-2.0-py3-none-any.whl
...


问:
Add if condition inside a CURSOR
I need to check relevant condition with SELECT statement. simply I need this.

```<code>if systemdate is 'Monday' then
   select statement1(which contains cursor)
else
   select statement 2(which contains cursor)
</code>```

Here is my code:

```<code>CURSOR PR_CASHDEPOSITEMAIL IS
    SELECT      B.STR_DEALER_NAME AS DEALERNAME,
                B.STR_BC_BRANCH_CODE AS ASSINGBRANCH,
                A.STRDDH_DEALERCODE AS ICAMDEALERCODE,
                B.STR_DEALER_CODE AS DEALERCODE,
                TO_DATE(A.DTDDH_DPDATE,'DD/MM/YYYY')AS RECEIPTDATE,
                A.NUMDDH_BALANCEAMOUNT AS RECEIPTAMOUNT,
                A.STRDDH_DPSLNO AS DEPOSITNUMBER
    FROM        GLINFO.TBLDEALERDEPOSITEHEADER A ,
                ADL.REF_DEALER_MASTER B ,
                CORPINFO.TBLBRANCHES C
    WHERE       A.NUMDDH_BALANCEAMOUNT >0
    AND         A.STRDDH_DEALERCODE=B.STR_COMP_DEALER_CODE
    AND         B.STR_BC_BRANCH_CODE=C.BRN_CODE
    AND         B.str_bc_branch_code =strBranch
    ORDER BY    B.STR_BC_BRANCH_CODE, B.STR_DEALER_NAME, RECEIPTDATE, DEPOSITNUMBER;

BEGIN

--rest of code
</code>```

I need to add previously mentioned condition to this select statement.

答:
Cursor with a parameter can help here. Cursor declaration:

```<code>CURSOR PR_CASHDEPOSITEMAIL (p_day varchar2) -- <-- parameter declaration
  IS
    SELECT <...>
    FROM   <...>
    WHERE  <...>
      and to_date(some_date_column, 'Day') = p_day; -- <-- parameter use in query
</code>```

Use of cursor:

```<code>...
begin
  open PR_CASHDEPOSITEMAIL('Monday'); -- <-- passing value to the cursor
  ...
</code>```

Title: Add if condition inside a CURSOR

Body:
I need to check relevant condition with SELECT statement. simply I need this.

if systemdate is 'Monday' then
   select statement1(which contains cursor)
else
   select statement 2(which contains cursor)

Here is my code:

CURSOR PR_CASHDEPOSITEMAIL IS
    SELECT      B.STR_DEALER_NAME AS DEALERNAME,
                B.STR_BC_BRANCH_CODE AS ASSINGBRANCH,
                A.STRDDH_DEALERCODE AS ICAMDEALERCODE,
                B.STR_DEALER_CODE AS DEALERCODE,
                TO_DATE(A.DTDDH_DPDATE,'DD/MM/YYYY')AS RECEIPTDATE,
                A.NUMDDH_BALANCEAMOUNT AS RECEIPTAMOUNT,
                A.STRDDH_DPSLNO AS DEPOSITNUMBER
    FROM        GLINFO.TBLDEALERDEPOSITEHEADER A ,
                ADL.REF_DEALER_MASTER B ,
                CORPINFO.TBLBRANCHES C
    WHERE       A.NUMDDH_BALANCEAMOUNT >0
    AND         A.STRDDH_DEALERCODE=B.STR_COMP_DEALER_CODE
    AND         B.STR_BC_BRANCH_CODE=C.BRN_CODE
    AND         B.str_bc_branch_code =strBranch
    ORDER BY    B.STR_BC_BRANCH_CODE, B.STR_DEALER_NAME, RECEIPTDATE, DEPOSITNUMBER;

BEGIN

--rest of code

I need to add previously mentioned condition to this select statement.

Body:
Cursor with a parameter can help here. Cursor declaration:

CURSOR PR_CASHDEPOSITEMAIL (p_day varchar2) -- <-- parameter declaration
  IS
    SELECT <...>
    FROM   <...>
    WHERE  <...>
      and to_date(some_date_column, 'Day') = p_day; -- <-- parameter use in query

Use of cursor:

...
begin
  open PR_CASHDEPOSITEMAIL('Monday'); -- <-- passing value to the cursor
  ...


问:
Out of Memory Error - Java Heap Space while writing to Excel
I have a data of almost 100,000 records and I am trying to write the data to .xlsx file using XSSFWorkbook through Java code. I am able to fetch all the data from database to an ArrayList. By iterating the ArryList, I am writing the data to .xlsx file cell by cell.
As it reaches to 8000 rows, java code throws Out of Memory Heap Space Error.

I have read somewhere that SXSSFWorkbook will be lighter when compared to XSSFWorkbook, so I tried using SXSSFWorkbook. But still I am facing the same problem.

So is there anything that I am missing with the Workbooks or with my Java Code??

Initially, when I have 60,000 records data, I had used .xls file. The same java code is able to generate the .xls file with HSSFWorkbook.

Increasing the Java Heap Space is not at all an option as my data will be increased tremendously in future.

Any help will be greatly appreciated.

Small piece of code, the way I am writing the data to Excel.

```<code>int rowNum = sheet.getLastRowNum();

Row lastRow = null ;

Cell cell = null;

ReportingHelperVo reportingHelperVo = null;

for (ReportingVo reportingVo : reportingVos) {

rowNum++;

lastRow = sheet.createRow(rowNum);

reportingHelperVo = reportingVo.reportingHelperVo;

cell = lastRow.createCell(0);

cell.setCellValue(reportingHelperVo.getLocation());

cell.setCellStyle(style);

cell = lastRow.createCell(1);

cell.setCellValue(reportingHelperVo.getCity());

cell.setCellStyle(style);

cell = lastRow.createCell(2);

cell.setCellValue(reportingHelperVo.getCountry());

cell.setCellStyle(style);

}
</code>```

答:
Hi Use latest Apache POI JAR//And Use SXSSF for streaming or downloading </p>

```<code> SXSSFWorkbook workbook = new SXSSFWorkbook(100);
            workbook.setCompressTempFiles(true);
            Sheet sh = workbook.createSheet();
            ((SXSSFSheet) sh).setRandomAccessWindowSize(100);
</code>```

<p>//write your logic</p>

```<code>   response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;
       filename="+filename+".xlsx");
            workbook.write(response.getOutputStream());
            workbook.close();
            workbook.dispose();
</code>```

Body:
I have a data of almost 100,000 records and I am trying to write the data to .xlsx file using XSSFWorkbook through Java code. I am able to fetch all the data from database to an ArrayList. By iterating the ArryList, I am writing the data to .xlsx file cell by cell.
As it reaches to 8000 rows, java code throws Out of Memory Heap Space Error.

I have read somewhere that SXSSFWorkbook will be lighter when compared to XSSFWorkbook, so I tried using SXSSFWorkbook. But still I am facing the same problem.

So is there anything that I am missing with the Workbooks or with my Java Code??

Initially, when I have 60,000 records data, I had used .xls file. The same java code is able to generate the .xls file with HSSFWorkbook.

Increasing the Java Heap Space is not at all an option as my data will be increased tremendously in future.

Any help will be greatly appreciated.

Small piece of code, the way I am writing the data to Excel.

int rowNum = sheet.getLastRowNum();

Row lastRow = null ;

Cell cell = null;

ReportingHelperVo reportingHelperVo = null;

for (ReportingVo reportingVo : reportingVos) {

rowNum++;

lastRow = sheet.createRow(rowNum);

reportingHelperVo = reportingVo.reportingHelperVo;

cell = lastRow.createCell(0);

cell.setCellValue(reportingHelperVo.getLocation());

cell.setCellStyle(style);

cell = lastRow.createCell(1);

cell.setCellValue(reportingHelperVo.getCity());

cell.setCellStyle(style);

cell = lastRow.createCell(2);

cell.setCellValue(reportingHelperVo.getCountry());

cell.setCellStyle(style);

}

Body:
Hi Use latest Apache POI JAR//And Use SXSSF for streaming or downloading

 SXSSFWorkbook workbook = new SXSSFWorkbook(100);
            workbook.setCompressTempFiles(true);
            Sheet sh = workbook.createSheet();
            ((SXSSFSheet) sh).setRandomAccessWindowSize(100);

//write your logic

   response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;
       filename="+filename+".xlsx");
            workbook.write(response.getOutputStream());
            workbook.close();
            workbook.dispose();


问:
no resources 'android:keyboardNavigationCluster'
i am facing this issue while compiling my project today.
i tried following things too
changed buildToolsVersion '26.0.1' compileSdkVersion 26
updated myandroid studio` version

but its not working
thanks in advance

答: finally i   fixed this by changing few code in my code as per new buildToolsVersion'26.0.1' .</p>


问:
Trouble installing Django: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-rcF9a5/Django/
I'm trying to install Django via command prompt. I used pip install Django but got this message:

```<code>Collecting Django
  Using cached `Django-2.0.tar.gz`
</code>```

Complete output from command python setup.py egg_info:

```<code>Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/tmp/pip-build-rcF9a5/Django/setup.py", line 32, in <module>
    version = __import__('django').get_version()
  File "django/__init__.py", line 1, in <module>
    from django.utils.version import get_version
  File "django/utils/version.py", line 61, in <module>
    @functools.lru_cache()
AttributeError: 'module' object has no attribute 'lru_cache'
</code>```

```<code>Command **`"python setup.py egg_info"`** failed with error code 1 in **/tmp/pip-build-rcF9a5/Django/**
</code>```

How do I fix this?

答: To use Django 2.0 python 3 should be used. One way to do this is using a virtual environment. Create a python 3 virtual environment ( python3 -m venv myvenv ) and install Django 2.0 in it. Make sure to use pip from python 3 instead of 2.

Body:
I'm trying to install Django via command prompt. I used pip install Django but got this message:

Collecting Django
  Using cached `Django-2.0.tar.gz`

Complete output from command python setup.py egg_info:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/tmp/pip-build-rcF9a5/Django/setup.py", line 32, in <module>
    version = __import__('django').get_version()
  File "django/__init__.py", line 1, in <module>
    from django.utils.version import get_version
  File "django/utils/version.py", line 61, in <module>
    @functools.lru_cache()
AttributeError: 'module' object has no attribute 'lru_cache'

Command **`"python setup.py egg_info"`** failed with error code 1 in **/tmp/pip-build-rcF9a5/Django/**

How do I fix this?


问:
Why are the referenced array's values not changed?
I'm trying to multiply the each component of an array with a scalar, and to do this, have tried the followings;

1-)

```<code>@foo = (1, 2, 3, 5, 6);
vectorScalarMultiply(\@foo);
print @foo, "\n";

sub vectorScalarMultiply
{
    my $l_vectorRef = $_[0];
    for (my $var = 0; $var < scalar(@temp); $var++) {
        $l_vectorRef->[$var] = $l_vectorRef->[$var] * 5;
    }
}
</code>```

1's Output;

12356

2-)

```<code>@foo = (1, 2, 3, 5, 6);
vectorScalarMultiply(\@foo);
print @foo, "\n";
sub vectorScalarMultiply
{

    my $l_vectorRef = $_[0];
    map { $l_vectorRef->[$_] * 5 } { $l_vectorRef->[$_] };
}
</code>```

2's Output;

123456

3-)

```<code>@foo = (1, 2, 3, 5, 6);
@temp = @{$l_vectorRef};
vectorScalarMultiply(\@foo);
print @foo, "\n";
$l_vectorRef = map { $temp[$_] * 5; } @temp;
</code>```

3's Output;

12356

And I haven't been able to figure out what is the problem, and why are they not working, so my main question is that what is the problem with these code ?Secondly, how can we solve it ?

答:
Because you forgot use strict; use warnings; so didn't notice that @temp is undefined so your loop length is 0.

Because you forgot use strict; use warnings; so didn't notice that map { $l_vectorRef->[$_] * 5 } { $l_vectorRef->[$_] }; expects the { $l_vectorRef->[$_] } to be a list. You also didn't assign the result of the map anywhere.

Because you forgot use strict; use warnings; so didn't notice that you never defined $l_vectorRef (but if you did, then the map would overwrite the reference and not replace the original array)

Body:
I'm trying to multiply the each component of an array with a scalar, and to do this, have tried the followings;

1-)

@foo = (1, 2, 3, 5, 6);
vectorScalarMultiply(\@foo);
print @foo, "\n";

sub vectorScalarMultiply
{
    my $l_vectorRef = $_[0];
    for (my $var = 0; $var < scalar(@temp); $var++) {
        $l_vectorRef->[$var] = $l_vectorRef->[$var] * 5;
    }
}

1's Output;

12356

2-)

@foo = (1, 2, 3, 5, 6);
vectorScalarMultiply(\@foo);
print @foo, "\n";
sub vectorScalarMultiply
{

    my $l_vectorRef = $_[0];
    map { $l_vectorRef->[$_] * 5 } { $l_vectorRef->[$_] };
}

2's Output;

123456

3-)

@foo = (1, 2, 3, 5, 6);
@temp = @{$l_vectorRef};
vectorScalarMultiply(\@foo);
print @foo, "\n";
$l_vectorRef = map { $temp[$_] * 5; } @temp;

3's Output;

12356

And I haven't been able to figure out what is the problem, and why are they not working, so my main question is that what is the problem with these code ?Secondly, how can we solve it ?


问:
How to extract a vector in a tibble column to multiple columns in the same tibble?
The following code produces a vector of length 6 in the last column, from that column I would like to extract 6 new columns in my tibble.

```<code>require(tidyverse)
require(purrrlyr)
# this function will return a vector of the same length (6) for each group
fun=function(X,Y){
   mycut<-cut(X,breaks=seq(50,350,by=50),right=FALSE)
   v<-tapply(Y,mycut,sum)
   return(v)
}
# use the previous function to count gears per class of hp
mtcars %>%
    group_by(cyl)  %>%
    by_slice(~fun(.x$hp,.x$gear)) %>%
    rename(cut=.out)
</code>```

Here I have a vector in my column cut

```<code># tibble [3 x 2]
     cyl       cut
  <fctr>    <list>
1      4 <dbl [6]>
2      6 <dbl [6]>
3      8 <dbl [6]>
</code>```

What command do I need to pass from this vector to a table like?

```<code>cyl  [50,100) [100,150) [150,200) [200,250) [250,300) [300,350)
   4     36         9        NA        NA        NA        NA
   ...
</code>```

unnest does not work. Do I have to work with by_row or is there a more straightforward answer?

答:
We need to get the names of the 'cut' variable as new column and then do a spread to reshape to 'wide' format after unnesting the list elements

```<code>mtcars %>%
   group_by(cyl)  %>%
   by_slice(~fun(.x$hp,.x$gear)) %>%
   rename(cut=.out) %>%
   mutate(Names = map(cut, ~factor(names(.x), levels = names(.x)))) %>%
   unnest %>%
   spread(Names, cut)
# A tibble: 3 x 7
#    cyl `[50,100)` `[100,150)` `[150,200)` `[200,250)` `[250,300)` `[300,350)`
#*  <dbl>      <dbl>       <dbl>       <dbl>       <dbl>       <dbl>       <dbl>
#1     4         36           9          NA          NA          NA          NA
#2     6         NA          22           5          NA          NA          NA
#3     8         NA          NA          21          15           5           5
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The following code produces a vector of length 6 in the last column, from that column I would like to extract 6 new columns in my tibble.

require(tidyverse)
require(purrrlyr)
# this function will return a vector of the same length (6) for each group
fun=function(X,Y){
   mycut<-cut(X,breaks=seq(50,350,by=50),right=FALSE)
   v<-tapply(Y,mycut,sum)
   return(v)
}
# use the previous function to count gears per class of hp
mtcars %>%
    group_by(cyl)  %>%
    by_slice(~fun(.x$hp,.x$gear)) %>%
    rename(cut=.out)

Here I have a vector in my column cut

# tibble [3 x 2]
     cyl       cut
  <fctr>    <list>
1      4 <dbl [6]>
2      6 <dbl [6]>
3      8 <dbl [6]>

What command do I need to pass from this vector to a table like?

cyl  [50,100) [100,150) [150,200) [200,250) [250,300) [300,350)
   4     36         9        NA        NA        NA        NA
   ...

unnest does not work. Do I have to work with by_row or is there a more straightforward answer?

Body:
We need to get the names of the 'cut' variable as new column and then do a spread to reshape to 'wide' format after unnesting the list elements

mtcars %>%
   group_by(cyl)  %>%
   by_slice(~fun(.x$hp,.x$gear)) %>%
   rename(cut=.out) %>%
   mutate(Names = map(cut, ~factor(names(.x), levels = names(.x)))) %>%
   unnest %>%
   spread(Names, cut)
# A tibble: 3 x 7
#    cyl `[50,100)` `[100,150)` `[150,200)` `[200,250)` `[250,300)` `[300,350)`
#*  <dbl>      <dbl>       <dbl>       <dbl>       <dbl>       <dbl>       <dbl>
#1     4         36           9          NA          NA          NA          NA
#2     6         NA          22           5          NA          NA          NA
#3     8         NA          NA          21          15           5           5


问:
Copying a folder to docker container
I was trying to copy a folder from my local host to a docker container in the interactive mode using the following docker command:

docker run -it -v /folder/folder/workspace/folder/folder/*:/tool-1.0/Projects/DemoProject/ --name container imagename

The contents of the folder in the container are getting removed when I run the above command.

Is there any other way to copy the folder into a container?

答:
When you use the -v option you are mouting a volume from the host onto the container folder location. This will effectively "override" files that exist in the container.

You still can use this option, but mount the host folder onto a non-ecisting subdirectory in the container:

```<code>docker run -it -v /folder/folder/workspace/folder/folder:/tool-1.0/Projects/DemoProject/folder --name container imagename
</code>```

Alternatively, don't use the volume option and just start the container and the copy the files from the host into the started container using:

```<code>docker run -it --name container imagename
docker cp /folder/folder/workspace/folder/folder/* container:/tool-1.0/Projects/DemoProject
</code>```

Title: Copying a folder to docker container

Body:
When you use the -v option you are mouting a volume from the host onto the container folder location. This will effectively "override" files that exist in the container.

You still can use this option, but mount the host folder onto a non-ecisting subdirectory in the container:

docker run -it -v /folder/folder/workspace/folder/folder:/tool-1.0/Projects/DemoProject/folder --name container imagename

Alternatively, don't use the volume option and just start the container and the copy the files from the host into the started container using:

docker run -it --name container imagename
docker cp /folder/folder/workspace/folder/folder/* container:/tool-1.0/Projects/DemoProject


问:
Favicon Not Showing Up (w/ cloudflare)
I am using 000webhost as a Host, then after I uploaded files, the only thing happen is the contents show but not the favicon. I am using CloudFlare too secure my website I've purge everything.

the site is https://ravenshangar.tk/ (Not showing Favicon)
the 000webhost site is https://ravenshangar.000webhostapp.com/ (Showing Favicon)

Showing Favicon (000webhost)

Not Showing Favicon (CloudFlare)

答:
First you need to include favicon inside head tag : </p>

```<code><link rel="shortcut icon" href="favicon.ico">
</code>```

Title: Favicon Not Showing Up (w/ cloudflare)

Body:
First you need to include favicon inside head tag :

<link rel="shortcut icon" href="favicon.ico">


问:
Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"
I have a Dockerfile that is supposed to build an Ubuntu image. But whenever I run

```<code>docker build -t ubuntu-test:latest ./Dockerfile
</code>```

it shows the following error on the console

unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile

I'm on Mac OsX. I tried to sudo as well. Nothing works.

答:
I face the same issue. I am using docker version:17.09.0-ce.

I follow below steps:

Create Dockerfile and added commands for creating docker image

Go to directory where we have created Dockfile

execute below command $ sudo docker build -t ubuntu-test:latest .

It resolved issue and image created successsfully.

Note: build command depend on docker version as well as which build option we are using. :)

Body:
I have a Dockerfile that is supposed to build an Ubuntu image. But whenever I run

docker build -t ubuntu-test:latest ./Dockerfile

it shows the following error on the console

unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile

I'm on Mac OsX. I tried to sudo as well. Nothing works.


问:
WPF Databinding combobox in a datagrid
I'm pretty new to WPF and MVVM, so I might be missing some basic understanding.

I am trying to build a list of feed that can be ordered. Every order demands the name, an amount and a unit.

The units should be placed in a combobox, and that's the problem. Depending on the method, the combobox doesn't appear, or is just plain empty.

The following is the XAML.

```<code><UserControl x:Class="TestProject.View.FruitFoodList"
         DataContext="{Binding Test, Source={StaticResource Locator}}">
<Grid>
    <DataGrid ItemsSource="{Binding DummyFruitList}" IsReadOnly="True" Name="dgFeedList" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Feed" Binding="{Binding Name}" Width="*"/>
            <DataGridTemplateColumn Header="Amount">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <!-- Code for amount here -->
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridComboBoxColumn Header="Unit">
                <!--Combobox for units here-->
            </DataGridComboBoxColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>
</code>```

Here's the viewmodel:

```<code>public class DummyViewModel : ViewModelBase
{
    private List<DummyProduct> _dummyFruit = new List<DummyProduct>();

    public List<DummyProduct> DummyFruitList
    {
        get { return _dummyFruit; }
        set { _dummyFruit = value; }
    }

    public List<Unit> DummyUnitList = new List<Unit> {
        new Unit { Name = "kg"},
        new Unit { Name = "piece(s)" },
        new Unit { Name = "box(es)" }
    };

    public DummyViewModel()
    {
        string[] lines = File.ReadAllLines("../../DummyFruit.txt", Encoding.UTF7);
        foreach (string product in lines)
        {
            DummyProduct dummyProduct = new DummyProduct(product);
            dummyProduct.Units = DummyUnitList;
            DummyFruitList.Add(dummyProduct);
        }
    }
}
</code>```

And DummyProduct:

```<code>public class DummyProduct
{
    public DummyProduct(string product)
    {
        Name = product;
    }

    public string Name { get; set; }
    public List<Unit> Units;
}
</code>```

The units might not be the same for every product.
I have, without luck, tried the following solutions:
Binding WPF ComboBox to a Custom List
Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

The above solutions didn't show a combobox at all for me.
But again, I might be doing it wrong.

Making a stackpanel with a combobox in a datagridtemplate has so far been the only solution that got a combobox to appear, but the bindings makes no sense here.

答:
XAML for your DataGrid Combobox Column

```<code><DataGridComboBoxColumn Header="Unit" DisplayMemberPath="Name"  SelectedValuePath="Id" SelectedValueBinding="{Binding UnitId, UpdateSourceTrigger=PropertyChanged}"   MinWidth="280" Width="Auto" IsReadOnly="False">
    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.DummyUnitList, UpdateSourceTrigger=PropertyChanged}"/>
            <Setter Property="Width" Value="280" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.DummyUnitList, UpdateSourceTrigger=PropertyChanged}"/>
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</code>```

SelectedValueBinding="{Binding UnitId, UpdateSourceTrigger=PropertyChanged}" where UnitId is an element of you DataGrid ItemsSource, this is your selected value to store in your data base (or read from it)

DisplayMemberPath="Name"  SelectedValuePath="Id" where Id and Name are properties of Unit class

DummyUnitList should be ObservableCollection<> instead of List<>

```<code>public ObservableCollection<Unit> DummyUnitList
{
    get => _dummyUnitList ;
    set { _dummyUnitList = value; OnPropertyChanged(nameof(DummyUnitList)); }
}
</code>```

Title: WPF Databinding combobox in a datagrid

Body:
I'm pretty new to WPF and MVVM, so I might be missing some basic understanding.

I am trying to build a list of feed that can be ordered. Every order demands the name, an amount and a unit.

The units should be placed in a combobox, and that's the problem. Depending on the method, the combobox doesn't appear, or is just plain empty.

The following is the XAML.

<UserControl x:Class="TestProject.View.FruitFoodList"
         DataContext="{Binding Test, Source={StaticResource Locator}}">
<Grid>
    <DataGrid ItemsSource="{Binding DummyFruitList}" IsReadOnly="True" Name="dgFeedList" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Feed" Binding="{Binding Name}" Width="*"/>
            <DataGridTemplateColumn Header="Amount">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>

                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridComboBoxColumn Header="Unit">

            </DataGridComboBoxColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

Here's the viewmodel:

public class DummyViewModel : ViewModelBase
{
    private List<DummyProduct> _dummyFruit = new List<DummyProduct>();

    public List<DummyProduct> DummyFruitList
    {
        get { return _dummyFruit; }
        set { _dummyFruit = value; }
    }

    public List<Unit> DummyUnitList = new List<Unit> {
        new Unit { Name = "kg"},
        new Unit { Name = "piece(s)" },
        new Unit { Name = "box(es)" }
    };

    public DummyViewModel()
    {
        string[] lines = File.ReadAllLines("../../DummyFruit.txt", Encoding.UTF7);
        foreach (string product in lines)
        {
            DummyProduct dummyProduct = new DummyProduct(product);
            dummyProduct.Units = DummyUnitList;
            DummyFruitList.Add(dummyProduct);
        }
    }
}

And DummyProduct:

public class DummyProduct
{
    public DummyProduct(string product)
    {
        Name = product;
    }

    public string Name { get; set; }
    public List<Unit> Units;
}

The units might not be the same for every product.
I have, without luck, tried the following solutions:
Binding WPF ComboBox to a Custom List
Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

The above solutions didn't show a combobox at all for me.
But again, I might be doing it wrong.

Making a stackpanel with a combobox in a datagridtemplate has so far been the only solution that got a combobox to appear, but the bindings makes no sense here.

Body:
XAML for your DataGrid Combobox Column

<DataGridComboBoxColumn Header="Unit" DisplayMemberPath="Name"  SelectedValuePath="Id" SelectedValueBinding="{Binding UnitId, UpdateSourceTrigger=PropertyChanged}"   MinWidth="280" Width="Auto" IsReadOnly="False">
    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.DummyUnitList, UpdateSourceTrigger=PropertyChanged}"/>
            <Setter Property="Width" Value="280" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.DummyUnitList, UpdateSourceTrigger=PropertyChanged}"/>
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

SelectedValueBinding="{Binding UnitId, UpdateSourceTrigger=PropertyChanged}" where UnitId is an element of you DataGrid ItemsSource, this is your selected value to store in your data base (or read from it)

DisplayMemberPath="Name"  SelectedValuePath="Id" where Id and Name are properties of Unit class

DummyUnitList should be ObservableCollection<> instead of List<>

public ObservableCollection<Unit> DummyUnitList
{
    get => _dummyUnitList ;
    set { _dummyUnitList = value; OnPropertyChanged(nameof(DummyUnitList)); }
}


问:
How to save generic object to an array in swift
I have on class

```<code>class SomeClass<T>: AsyncOperation, NetworkOperationProtocol {

    /// The resource model object that conforms to Parsable Response
    public typealias Resource = T
}
</code>```

I want to save instance of this class to an array, and want retrieve it later.
How can I achieve this?

答:
If your class implements protocol with associatedtype, it's impossible to put it into array because such protocols have Self-requirement - they need to know concrete type for associatedtype.

However, you can use technique called type-erasure to store type without associated type information. So, for example, you can create a protocol without associatedtype, like so

```<code>protocol Operation {
   func perform()
}

class SomeClass<T> : AsyncOperation, NetworkOperationProtocol, Operation
</code>```

And then define an array of such operations:

```<code>let operations : [Operation] = []
operations.append(SomeClass.init())
</code>```

Body:
I have on class

class SomeClass<T>: AsyncOperation, NetworkOperationProtocol {

    /// The resource model object that conforms to Parsable Response
    public typealias Resource = T
}

I want to save instance of this class to an array, and want retrieve it later.
How can I achieve this?

Body:
If your class implements protocol with associatedtype, it's impossible to put it into array because such protocols have Self-requirement - they need to know concrete type for associatedtype.

However, you can use technique called type-erasure to store type without associated type information. So, for example, you can create a protocol without associatedtype, like so

protocol Operation {
   func perform()
}

class SomeClass<T> : AsyncOperation, NetworkOperationProtocol, Operation

And then define an array of such operations:

let operations : [Operation] = []
operations.append(SomeClass.init())


问:
Redirect from one scene to another Unity 3D script
I have 2 scenes and I want to redirect from one to another on the button click. I used AssetBundle for that.
Here is the code for exporting of assets:

```<code>public class ExportAssetBundles
{
    [MenuItem("Assets/Build AssetBundle")]
    static void ExportResource()
    {
        string folderName = "AssetBundles";
        string filePath = Path.Combine(Application.streamingAssetsPath, folderName);

        BuildPipeline.BuildAssetBundles(filePath, BuildAssetBundleOptions.None, BuildTarget.NoTarget);
    }
}
</code>```

And here is the code for loading:

```<code>public class RedirectToMenu : MonoBehaviour {
    void Start () {
        Button btn = GetComponent<Button>);
        btn.onClick.AddListener(OnClick);
    }

    public void OnClick(){
        Debug.Log("You have clicked the button!");
        LoadAsset("MenuFinal");
    }

    IEnumerator LoadAsset(string assetBundleName)//, string objectNameToLoad)
    {
        string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "AssetBundles");
        filePath = System.IO.Path.Combine(filePath, assetBundleName);

        var assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(filePath);
        yield return assetBundleCreateRequest;

        AssetBundle asseBundle = assetBundleCreateRequest.assetBundle;
    }
}
</code>```

So when I run my scene in Unity I get such error in console:

```<code>ArgumentException: The output path "D:/userdata/Documents/Scene1/Assets/StreamingAssets\AssetBundles" doesn't exist(at ExportAssetBundles.ExportResource () (at Assets/ExportAssetBundles.cs:16)
</code>```

I have put my scenes into Assets folder:

Also, I have added them to Build settings:

So how can I fix this error and make the redirection work? Is that a code problem or some file locations problem?

答:
Use SceneManager.LoadScene()</p>

```<code>public static void LoadScene(int sceneBuildIndex,
                   SceneManagement.LoadSceneMode mode = LoadSceneMode.Single);
public static void LoadScene(string sceneName,
                   SceneManagement.LoadSceneMode mode = LoadSceneMode.Single);
</code>```

Body:
I have 2 scenes and I want to redirect from one to another on the button click. I used AssetBundle for that.
Here is the code for exporting of assets:

public class ExportAssetBundles
{
    [MenuItem("Assets/Build AssetBundle")]
    static void ExportResource()
    {
        string folderName = "AssetBundles";
        string filePath = Path.Combine(Application.streamingAssetsPath, folderName);

        BuildPipeline.BuildAssetBundles(filePath, BuildAssetBundleOptions.None, BuildTarget.NoTarget);
    }
}

And here is the code for loading:

public class RedirectToMenu : MonoBehaviour {
    void Start () {
        Button btn = GetComponent<Button>);
        btn.onClick.AddListener(OnClick);
    }

    public void OnClick(){
        Debug.Log("You have clicked the button!");
        LoadAsset("MenuFinal");
    }

    IEnumerator LoadAsset(string assetBundleName)//, string objectNameToLoad)
    {
        string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "AssetBundles");
        filePath = System.IO.Path.Combine(filePath, assetBundleName);

        var assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(filePath);
        yield return assetBundleCreateRequest;

        AssetBundle asseBundle = assetBundleCreateRequest.assetBundle;
    }
}

So when I run my scene in Unity I get such error in console:

ArgumentException: The output path "D:/userdata/Documents/Scene1/Assets/StreamingAssets\AssetBundles" doesn't exist(at ExportAssetBundles.ExportResource () (at Assets/ExportAssetBundles.cs:16)

I have put my scenes into Assets folder:

Also, I have added them to Build settings:

So how can I fix this error and make the redirection work? Is that a code problem or some file locations problem?

Body:
Use SceneManager.LoadScene()

public static void LoadScene(int sceneBuildIndex,
                   SceneManagement.LoadSceneMode mode = LoadSceneMode.Single);
public static void LoadScene(string sceneName,
                   SceneManagement.LoadSceneMode mode = LoadSceneMode.Single);


问:
QSlider increase handle size
I need badly to increase size of handle for my slider, but no css options can do this(styleSheet()).
The default example from Qt docs didn't help me as well.

I have a slider like this:

I wish to increase the height of its handle, as shown on explanation image below, but I can't guess how to do it. Probably the only way is to subclass QAbstractSlider?

Here is the stylesheet from my code:

```<code>                "QSlider::groove:horizontal {"
                "border: 1px solid #999999;"
                "height: 32px;" /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */
                "background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #B1B1B1, stop:1 #c4c4c4);"
                "margin: 2px 0; }"
            "QSlider::handle:horizontal {"
                "background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f);"
                "border: 1px solid #5c5c5c;"
                "width: 40px;"
                "margin: -20px 0;" /* handle is placed by default on the contents rect of the groove. Expand outside the groove */
                "border-radius: 3px;}"
            );
</code>```

答:
I copied your exact code into a form in Qt Designer. The slider handle looks large enough.

However, when adding a layout, the whole slider's size isn't large enough to show the complete handle. I simply added this:

```<code>QSlider {
    height: 80px;
}
</code>```

And get this result:

Title: QSlider increase handle size

Body:
I need badly to increase size of handle for my slider, but no css options can do this(styleSheet()).
The default example from Qt docs didn't help me as well.

I have a slider like this:

I wish to increase the height of its handle, as shown on explanation image below, but I can't guess how to do it. Probably the only way is to subclass QAbstractSlider?

Here is the stylesheet from my code:

                "QSlider::groove:horizontal {"
                "border: 1px solid #999999;"
                "height: 32px;" /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */
                "background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #B1B1B1, stop:1 #c4c4c4);"
                "margin: 2px 0; }"
            "QSlider::handle:horizontal {"
                "background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f);"
                "border: 1px solid #5c5c5c;"
                "width: 40px;"
                "margin: -20px 0;" /* handle is placed by default on the contents rect of the groove. Expand outside the groove */
                "border-radius: 3px;}"
            );

Body:
I copied your exact code into a form in Qt Designer. The slider handle looks large enough.

However, when adding a layout, the whole slider's size isn't large enough to show the complete handle. I simply added this:

QSlider {
    height: 80px;
}

And get this result:


问:
Get user id and name from comment on Fan Page Wall
Since Facebook API update to v2.11, I cannot get User Id and Name from comments on FanPage Wall Post. Anyone can help/explain?

Usually I used this :
https://graph.facebook.com/[POST_ID_PAGE]/comments?order=reverse_chronological&access_token=[YOUR_ACCESS_TOKEN]

```<code>And the result just like :
{
"data": [
{
"created_time": values_date_TMZ,
"from": {
"name": USER_NAME,
"id": USER_ID
},
"message": THE_COMMENT,
"id": THE_COMMENT_ID
}
}
</code>```

答:
You need a Page Token now, to get user names - check out the changelog:

https://developers.facebook.com/docs/graph-api/changelog/version2.11#gapi

I assume you are using an App Token at the moment.

Edit: Of course it has to be a Page Token of the Page with the comment. And of course you need to manage the Page - else you would not even get a Page Token.

Body:
Since Facebook API update to v2.11, I cannot get User Id and Name from comments on FanPage Wall Post. Anyone can help/explain?

Usually I used this :
https://graph.facebook.com/[POST_ID_PAGE]/comments?order=reverse_chronological&access_token=[YOUR_ACCESS_TOKEN]

And the result just like :
{
"data": [
{
"created_time": values_date_TMZ,
"from": {
"name": USER_NAME,
"id": USER_ID
},
"message": THE_COMMENT,
"id": THE_COMMENT_ID
}
}


问:
How will _Exit behave in a C++ program?
C99 offers the _Exit function, which exits "immediately", although it does may close file descriptors. Unix/POSIX extends this behavior by mandating the closing of all fd's without flushing (and offers the synonym _exit).

Will these functions call destructors for static objects when called from a C++ program? Does the C++ standard make any guarantees about _Exit?

(Inspired by this question; I suddenly wondered what happens in the typical fork-exec-_exit idiom in C++.)

答:
It simply doesn't exist in standard C++, so there are no guarantees.

It is planned for inclusion in C++0x.  That specifies (§18.5):

The function _Exit(int status) has
  additional behavior in this
  International Standard:

— The program is terminated without
  executing destructors for objects of
  automatic, thread, or static storage
  duration and without calling functions
  passed to atexit() (3.6.3).

Followup:

ISO approved C++0x on August 12, 2011.

Title: How will _Exit behave in a C++ program?