问:
MultiDex NoClassDefFound error
I have converted my application into MultiDex to bear with 64k dex limit. Now it looks like this:

```<code>public class App extends MultiDexApplication {

private AppWrapper instance;

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(base);
}

@Override
public void onCreate() {
    super.onCreate();

    if (instance == null) {
        instance = new AppWrapper(this);
    }
}
}
</code>```

I've pulled all the usual logic from App to AppWidget to make MultiDex work. And it works ok on other teammates' computers. But not with me. It keeps throwing java.lang.NoClassDefFoundError on application create:

```<code>I/dalvikvm﹕ Failed resolving     Lcom/playday/app/core/AppWrapper; interface 8940 'Lretrofit/ErrorHandler;'
W/dalvikvm﹕ Link of class     'Lcom/playday/app/core/AppWrapper;' failed
I/dalvikvm﹕ Failed resolving     Lcom/playday/app/core/AppWrapper; interface 8940 'Lretrofit/ErrorHandler;'
W/dalvikvm﹕ Link of class     'Lcom/playday/app/core/AppWrapper;' failed
E/dalvikvm﹕ Could not find class     'com.playday.app.core.AppWrapper', referenced from method com.playday.app.core.App.onCreate
W/dalvikvm﹕ VFY: unable to resolve     new-instance 7076 (Lcom/playday/app/core/AppWrapper;) in Lcom/playday/app/core/App;
D/dalvikvm﹕ VFY: replacing opcode     0x22 at 0x0007
I/dalvikvm﹕ Failed resolving     Lcom/playday/app/core/AppWrapper; interface 8940 'Lretrofit/ErrorHandler;'
W/dalvikvm﹕ Link of class     'Lcom/playday/app/core/AppWrapper;' failed
D/dalvikvm﹕ DexOpt: unable to opt     direct call 0xc21b at 0x09 in Lcom/playday/app/core/App;.onCreate
I/MultiDex﹕ VM with version 1.6.0     does not have multidex support
I/MultiDex﹕ install
I/MultiDex﹕ MultiDexExtractor.load(    /data/app/com.playdayteam.playday.debug-1.apk, false)
I/MultiDex﹕ Detected that     extraction must be performed.
I/MultiDex﹕ Trying to delete old     file /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.    debug-2.apk.classes2.dex of size 1484912
I/MultiDex﹕ Deleted old file     /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.debug-2    .apk.classes2.dex
I/MultiDex﹕ Trying to delete old     file /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.    debug-2.apk.classes2.zip of size 540964
I/MultiDex﹕ Deleted old file     /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.debug-2    .apk.classes2.zip
D/dalvikvm﹕ GC_CONCURRENT freed     186K, 11% free 3245K/3640K, paused 2ms+4ms, total 28ms
D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC     blocked 5ms
D/dalvikvm﹕ GC_CONCURRENT freed     156K, 8% free 3593K/3904K, paused 3ms+2ms, total 22ms
I/MultiDex﹕ Extraction is needed     for file /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.    playday.debug-1.apk.classes2.zip
I/MultiDex﹕ Extracting     /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.debug-1    .apk.classes576886388.zip
I/MultiDex﹕ Renaming to     /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.debug-1    .apk.classes2.zip
I/MultiDex﹕ Extraction success -     length /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.    debug-1.apk.classes2.zip: 540964
I/MultiDex﹕ load found 1 secondary     dex files
D/dalvikvm﹕ DexOpt: --- BEGIN 'com.    playdayteam.playday.debug-1.apk.classes2.zip' (bootstrap=0) ---
D/dalvikvm﹕ DexOpt: --- END 'com.    playdayteam.playday.debug-1.apk.classes2.zip' (success) ---
D/dalvikvm﹕ DEX prep '/data/data/com    .playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.debug-1.apk.classes2.    zip': unzip in 28ms, rewrite 387ms
I/MultiDex﹕ install done
I/MultiDex﹕ install
D/AndroidRuntime﹕ Shutting down VM
W/dalvikvm﹕ threadid=1: thread     exiting with uncaught exception (group=0x41c1d930)
E/AndroidRuntime﹕ FATAL EXCEPTION:     main
    java.lang.NoClassDefFoundError: com.playday.app.core.AppWrapper
            at com.playday.app.core.App.onCreate(App.java:22)
            at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1006)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4457)
            at android.app.ActivityThread.access$1300(ActivityThread.java:142)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1332)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5105)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)
</code>```

I have the same Android Studio, gradle, sdk, jdk versions, same code. I've even tried to format hard drive and reinstall OS to make sure that environment is the same. What can be the cause of this strange problem?

This is my build.gradle:

```<code>apply plugin: 'com.android.application'

repositories {
    maven { url 'http://dl.bintray.com/populov/maven' }
    mavenCentral()
    maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
}

android {
    compileSdkVersion project.api_level
    buildToolsVersion project.build_tools_version

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion project.api_level
    }

    sourceSets {
        instrumentTest.setRoot('src/test')
    }

    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/ASL2.0'
        exclude 'AndroidManifest.xml'
    }

    defaultConfig {
        versionName "0.3.2"
        versionCode 23
    }

    buildTypes {

        debug {
            debuggable true
            applicationIdSuffix ".debug"
        }

        beta {
            debuggable true
            signingConfig signingConfigs.release
            applicationIdSuffix ".beta"
        }

        release {
            signingConfig signingConfigs.release
            runProguard false
            proguardFile file('proguard-rules.txt')
            proguardFile getDefaultProguardFile('proguard-android-optimize.txt')
        }
    }

    dexOptions {
        incremental false
        preDexLibraries false
    }
}

dependencies {
    compile "com.android.support:support-v13:$project.support_lib_version"
    compile "com.android.support:support-v4:$project.support_lib_version"
    compile "com.android.support:appcompat-v7:$project.support_lib_version"
    compile 'com.google.android.gms:play-services:6.1.11'
    compile('de.keyboardsurfer.android.widget:crouton:1.8.5@aar') {
        exclude group: 'com.google.android', module: 'support-v4'
    }
    compile('com.octo.android.robospice:robospice:1.4.14'){
        exclude group: 'commons-io', module: 'commons-io'
    }
    compile('com.octo.android.robospice:robospice-retrofit:1.4.14'){
        exclude group: 'commons-io', module: 'commons-io'
    }
    compile 'com.squareup.retrofit:retrofit:1.6.1'
    compile 'com.google.code.gson:gson:2.3'
    compile 'com.viewpagerindicator:library:2.4.1@aar'
    compile 'com.squareup.picasso:picasso:2.3.3'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'

    compile 'com.etsy.android.grid:library:1.0.5'
    compile 'com.squareup:otto:1.3.4'
    compile 'com.darwinsys:hirondelle-date4j:1.5.1'
    compile 'com.github.chrisbanes.photoview:library:1.2.3'
    compile 'me.grantland:autofittextview:0.2.0'
    compile 'it.sephiroth.android.library.horizontallistview:library:1.2.1'
    compile 'org.ocpsoft.prettytime:prettytime:3.2.4.Final'
    compile 'com.google.guava:guava:18.0'
    compile 'com.github.castorflex.smoothprogressbar:library:0.5.2'
    compile 'com.makeramen:roundedimageview:1.3.0'
    compile 'org.lucasr.twowayview:twowayview:0.1.1'
    compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT'

    compile project(':libs:LoopingViewPager')
    compile project(':libs:PhotoView-2.2.1')
    compile files('libs/localytics.jar')
    compile files('libs/android-support-multidex.jar')

    compile 'net.hockeyapp.android:HockeySDK:3.0.2'
}

afterEvaluate {
    tasks.matching {
        it.name.startsWith('dex')
    }.each { dx ->
        if (dx.additionalParameters == null) {
            dx.additionalParameters = []
        }
        dx.additionalParameters += '--multi-dex' // enable multidex
        dx.additionalParameters += "--main-dex-list=$projectDir/multidex.keep".toString()
    }
}
</code>```

Update. My multidex.keep file:

```<code>android/support/multidex/BuildConfig.class
android/support/multidex/MultiDex$V14.class
android/support/multidex/MultiDex$V19.class
android/support/multidex/MultiDex$V4.class
android/support/multidex/MultiDex.class
android/support/multidex/MultiDexApplication.class
android/support/multidex/MultiDexExtractor$1.class
android/support/multidex/MultiDexExtractor.class
android/support/multidex/ZipUtil$CentralDirectory.class
android/support/multidex/ZipUtil.class
com/playday/app/models/notification/Badge.class
com/playday/app/models/User.class
com/playday/app/core/AppWrapper.class
com/playday/app/core/App.class
</code>```

答:
if everything looks OK, but this error appears,

try to disable instant run!!!

when I disabled it all the classes were loaded properly.

Title: MultiDex NoClassDefFound error

Body:
I have converted my application into MultiDex to bear with 64k dex limit. Now it looks like this:

public class App extends MultiDexApplication {

private AppWrapper instance;

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(base);
}

@Override
public void onCreate() {
    super.onCreate();

    if (instance == null) {
        instance = new AppWrapper(this);
    }
}
}

I've pulled all the usual logic from App to AppWidget to make MultiDex work. And it works ok on other teammates' computers. But not with me. It keeps throwing java.lang.NoClassDefFoundError on application create:

I/dalvikvm﹕ Failed resolving     Lcom/playday/app/core/AppWrapper; interface 8940 'Lretrofit/ErrorHandler;'
W/dalvikvm﹕ Link of class     'Lcom/playday/app/core/AppWrapper;' failed
I/dalvikvm﹕ Failed resolving     Lcom/playday/app/core/AppWrapper; interface 8940 'Lretrofit/ErrorHandler;'
W/dalvikvm﹕ Link of class     'Lcom/playday/app/core/AppWrapper;' failed
E/dalvikvm﹕ Could not find class     'com.playday.app.core.AppWrapper', referenced from method com.playday.app.core.App.onCreate
W/dalvikvm﹕ VFY: unable to resolve     new-instance 7076 (Lcom/playday/app/core/AppWrapper;) in Lcom/playday/app/core/App;
D/dalvikvm﹕ VFY: replacing opcode     0x22 at 0x0007
I/dalvikvm﹕ Failed resolving     Lcom/playday/app/core/AppWrapper; interface 8940 'Lretrofit/ErrorHandler;'
W/dalvikvm﹕ Link of class     'Lcom/playday/app/core/AppWrapper;' failed
D/dalvikvm﹕ DexOpt: unable to opt     direct call 0xc21b at 0x09 in Lcom/playday/app/core/App;.onCreate
I/MultiDex﹕ VM with version 1.6.0     does not have multidex support
I/MultiDex﹕ install
I/MultiDex﹕ MultiDexExtractor.load(    /data/app/com.playdayteam.playday.debug-1.apk, false)
I/MultiDex﹕ Detected that     extraction must be performed.
I/MultiDex﹕ Trying to delete old     file /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.    debug-2.apk.classes2.dex of size 1484912
I/MultiDex﹕ Deleted old file     /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.debug-2    .apk.classes2.dex
I/MultiDex﹕ Trying to delete old     file /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.    debug-2.apk.classes2.zip of size 540964
I/MultiDex﹕ Deleted old file     /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.debug-2    .apk.classes2.zip
D/dalvikvm﹕ GC_CONCURRENT freed     186K, 11% free 3245K/3640K, paused 2ms+4ms, total 28ms
D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC     blocked 5ms
D/dalvikvm﹕ GC_CONCURRENT freed     156K, 8% free 3593K/3904K, paused 3ms+2ms, total 22ms
I/MultiDex﹕ Extraction is needed     for file /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.    playday.debug-1.apk.classes2.zip
I/MultiDex﹕ Extracting     /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.debug-1    .apk.classes576886388.zip
I/MultiDex﹕ Renaming to     /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.debug-1    .apk.classes2.zip
I/MultiDex﹕ Extraction success -     length /data/data/com.playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.    debug-1.apk.classes2.zip: 540964
I/MultiDex﹕ load found 1 secondary     dex files
D/dalvikvm﹕ DexOpt: --- BEGIN 'com.    playdayteam.playday.debug-1.apk.classes2.zip' (bootstrap=0) ---
D/dalvikvm﹕ DexOpt: --- END 'com.    playdayteam.playday.debug-1.apk.classes2.zip' (success) ---
D/dalvikvm﹕ DEX prep '/data/data/com    .playdayteam.playday.debug/code_cache/secondary-dexes/com.playdayteam.playday.debug-1.apk.classes2.    zip': unzip in 28ms, rewrite 387ms
I/MultiDex﹕ install done
I/MultiDex﹕ install
D/AndroidRuntime﹕ Shutting down VM
W/dalvikvm﹕ threadid=1: thread     exiting with uncaught exception (group=0x41c1d930)
E/AndroidRuntime﹕ FATAL EXCEPTION:     main
    java.lang.NoClassDefFoundError: com.playday.app.core.AppWrapper
            at com.playday.app.core.App.onCreate(App.java:22)
            at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1006)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4457)
            at android.app.ActivityThread.access$1300(ActivityThread.java:142)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1332)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5105)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)

I have the same Android Studio, gradle, sdk, jdk versions, same code. I've even tried to format hard drive and reinstall OS to make sure that environment is the same. What can be the cause of this strange problem?

This is my build.gradle:

apply plugin: 'com.android.application'

repositories {
    maven { url 'http://dl.bintray.com/populov/maven' }
    mavenCentral()
    maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
}

android {
    compileSdkVersion project.api_level
    buildToolsVersion project.build_tools_version

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion project.api_level
    }

    sourceSets {
        instrumentTest.setRoot('src/test')
    }

    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/ASL2.0'
        exclude 'AndroidManifest.xml'
    }

    defaultConfig {
        versionName "0.3.2"
        versionCode 23
    }

    buildTypes {

        debug {
            debuggable true
            applicationIdSuffix ".debug"
        }

        beta {
            debuggable true
            signingConfig signingConfigs.release
            applicationIdSuffix ".beta"
        }

        release {
            signingConfig signingConfigs.release
            runProguard false
            proguardFile file('proguard-rules.txt')
            proguardFile getDefaultProguardFile('proguard-android-optimize.txt')
        }
    }

    dexOptions {
        incremental false
        preDexLibraries false
    }
}

dependencies {
    compile "com.android.support:support-v13:$project.support_lib_version"
    compile "com.android.support:support-v4:$project.support_lib_version"
    compile "com.android.support:appcompat-v7:$project.support_lib_version"
    compile 'com.google.android.gms:play-services:6.1.11'
    compile('de.keyboardsurfer.android.widget:crouton:1.8.5@aar') {
        exclude group: 'com.google.android', module: 'support-v4'
    }
    compile('com.octo.android.robospice:robospice:1.4.14'){
        exclude group: 'commons-io', module: 'commons-io'
    }
    compile('com.octo.android.robospice:robospice-retrofit:1.4.14'){
        exclude group: 'commons-io', module: 'commons-io'
    }
    compile 'com.squareup.retrofit:retrofit:1.6.1'
    compile 'com.google.code.gson:gson:2.3'
    compile 'com.viewpagerindicator:library:2.4.1@aar'
    compile 'com.squareup.picasso:picasso:2.3.3'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'

    compile 'com.etsy.android.grid:library:1.0.5'
    compile 'com.squareup:otto:1.3.4'
    compile 'com.darwinsys:hirondelle-date4j:1.5.1'
    compile 'com.github.chrisbanes.photoview:library:1.2.3'
    compile 'me.grantland:autofittextview:0.2.0'
    compile 'it.sephiroth.android.library.horizontallistview:library:1.2.1'
    compile 'org.ocpsoft.prettytime:prettytime:3.2.4.Final'
    compile 'com.google.guava:guava:18.0'
    compile 'com.github.castorflex.smoothprogressbar:library:0.5.2'
    compile 'com.makeramen:roundedimageview:1.3.0'
    compile 'org.lucasr.twowayview:twowayview:0.1.1'
    compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT'

    compile project(':libs:LoopingViewPager')
    compile project(':libs:PhotoView-2.2.1')
    compile files('libs/localytics.jar')
    compile files('libs/android-support-multidex.jar')

    compile 'net.hockeyapp.android:HockeySDK:3.0.2'
}

afterEvaluate {
    tasks.matching {
        it.name.startsWith('dex')
    }.each { dx ->
        if (dx.additionalParameters == null) {
            dx.additionalParameters = []
        }
        dx.additionalParameters += '--multi-dex' // enable multidex
        dx.additionalParameters += "--main-dex-list=$projectDir/multidex.keep".toString()
    }
}

Update. My multidex.keep file:

android/support/multidex/BuildConfig.class
android/support/multidex/MultiDex$V14.class
android/support/multidex/MultiDex$V19.class
android/support/multidex/MultiDex$V4.class
android/support/multidex/MultiDex.class
android/support/multidex/MultiDexApplication.class
android/support/multidex/MultiDexExtractor$1.class
android/support/multidex/MultiDexExtractor.class
android/support/multidex/ZipUtil$CentralDirectory.class
android/support/multidex/ZipUtil.class
com/playday/app/models/notification/Badge.class
com/playday/app/models/User.class
com/playday/app/core/AppWrapper.class
com/playday/app/core/App.class


来源: stackexchange

问:
Passing variables (that have space) using JavaScript window pop-up
Pop-up script:

```<code><script>
function myFunction2(url,url2) {

window.open('googleapi.php?id='+url+'&id2='+url2, "_blank", "toolbar=no,scrollbars=no,resizable=no,top=70,left=50,width=1200,height=500");
}

</script>
</code>```

PHP code:

```<code>echo "<td style='color: red;font-weight: bold;'>" . '<a style="color:
red;font-weight: bold;" href= javascript:myFunction2("'."tom
peter".'","'.$row['Account_Number'].'")>'.'Abnormal'.'</a>' . "</td>";
</code>```

Error - it's only considering "tom" - myFunction2("tom

I need to obtain myFunction2("tom peter","11234") - Can someone please help me?

答:
use this one, you will get result as you expect.</p>

```<code>echo "<td style='color: red;font-weight: bold;'>" . "<a style='color:
red;font-weight: bold;' href= javascript:myFunction2('".rawurlencode('tom peter')."','".$row['Account_Number']."')>"."Abnormal"."</a>" . "</td>";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Pop-up script:

PHP code:

echo "" . ''.'Abnormal'.'' . "	";

Error - it's only considering "tom" - myFunction2("tom

I need to obtain myFunction2("tom peter","11234") - Can someone please help me?

Body:
use this one, you will get result as you expect.

echo "<td style='color: red;font-weight: bold;'>" . "<a style='color:
red;font-weight: bold;' href= javascript:myFunction2('".rawurlencode('tom peter')."','".$row['Account_Number']."')>"."Abnormal"."</a>" . "</td>";


问:
Retrieve mysql value from php for radio buttons
As trivial as it can seems, I'm having problems retrieving values for radio buttons from MySql database through PHP. It's my first learning project so I'm trying my best

Question has already been asked but I found no useful answer.

The php code does a simple "Select *" so I retrieve all the fields.

This is the php code

```<code><label>Owner: <?php echo $row['Owner']; ?></label></br>
<input type="radio" name="Owner" checked=<?php if($row['Owner'] = "A") { echo "true"; }?>  value="A">A
<input type="radio" name="Owner" checked=<?php if($row['Owner'] = "B") { echo "true"; }?> value="B">B</br></br>
</code>```

and I retrieve the values with mysqli_fetch_array().

This is the result:

As you can see the label retrieves the correct value, the radio buttons not.

I've already tried putting == instead of = and putting ' instead of " but I don't know why the checkbox "B" is checked, since Owner value is A.

Also, if there are any best practices which are better than this, you're welcome.

答:
i tried the answer given by @trincot but it give me errors so i have make little changes to improve the answer</p>

```<code><input type="radio" name="Owner" <?php if($row['Owner']=="A") {?> <?php echo "checked";?> <?php }?> value="A">A

<input type="radio" name="Owner" <?php if($row['Owner']=="B") {?> <?php echo "checked";?> <?php }?> value="B">B
</code>```

Body:
As trivial as it can seems, I'm having problems retrieving values for radio buttons from MySql database through PHP. It's my first learning project so I'm trying my best

Question has already been asked but I found no useful answer.

The php code does a simple "Select *" so I retrieve all the fields.

This is the php code

Owner: <?php echo $row['Owner']; ?>

<input type="radio" name="Owner" checked=<?php if($row['Owner'] = "A") { echo "true"; }?>  value="A">A
<input type="radio" name="Owner" checked=<?php if($row['Owner'] = "B") { echo "true"; }?> value="B">B

and I retrieve the values with mysqli_fetch_array().

This is the result:

As you can see the label retrieves the correct value, the radio buttons not.

I've already tried putting == instead of = and putting ' instead of " but I don't know why the checkbox "B" is checked, since Owner value is A.

Also, if there are any best practices which are better than this, you're welcome.

Body:
i tried the answer given by @trincot but it give me errors so i have make little changes to improve the answer

<input type="radio" name="Owner" <?php if($row['Owner']=="A") {?> <?php echo "checked";?> <?php }?> value="A">A

<input type="radio" name="Owner" <?php if($row['Owner']=="B") {?> <?php echo "checked";?> <?php }?> value="B">B


问:
Swift Eureka - capture MultivaluedSection delete action
I am using swift Eureka library with MultivaluedSection component. I want to capture when a user delete a row and update my application state. I took a look at examples, they show how to enable delete action but none of them provides the ability to capture the delete action Do you know how to do it?

code from example:

```<code>class MultivaluedOnlyDeleteController: FormViewController {

    @IBOutlet weak var editButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.isEditing = false
        let nameList = ["family", "male", "female", "client"]

        let section = MultivaluedSection(multivaluedOptions: .Delete, footer: "you can swipe to delete when table.isEditing = false (Not Editing)")

        for tag in nameList {
            section <<< TextRow {
                            $0.placeholder = "Tag Name"
                            $0.value = tag
                        }
        }

        let section2 =  MultivaluedSection(multivaluedOptions: .Delete, footer: "")
        for _ in 1..<4 {
            section2 <<< PickerInlineRow<String> {
                            $0.title = "Tap to select"
                            $0.value = "client"
                            $0.options = nameList
                         }
        }

        editButton.title = tableView.isEditing ? "Done" : "Edit"
        editButton.target = self
        editButton.action = #selector(editPressed(sender:))

        form    +++

                section

                +++

                section2
    }

    func editPressed(sender: UIBarButtonItem){
        tableView.setEditing(!tableView.isEditing, animated: true)
        editButton.title = tableView.isEditing ? "Done" : "Edit"

    }
}
</code>```

答:
In Core.swift file you need to change this function :

```<code>func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
</code>```

from public to open, then you can use this function in your view controller.

Body:
I am using swift Eureka library with MultivaluedSection component. I want to capture when a user delete a row and update my application state. I took a look at examples, they show how to enable delete action but none of them provides the ability to capture the delete action Do you know how to do it?

code from example:

class MultivaluedOnlyDeleteController: FormViewController {

    @IBOutlet weak var editButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.isEditing = false
        let nameList = ["family", "male", "female", "client"]

        let section = MultivaluedSection(multivaluedOptions: .Delete, footer: "you can swipe to delete when table.isEditing = false (Not Editing)")

        for tag in nameList {
            section <<< TextRow {
                            $0.placeholder = "Tag Name"
                            $0.value = tag
                        }
        }

        let section2 =  MultivaluedSection(multivaluedOptions: .Delete, footer: "")
        for _ in 1..<4 {
            section2 <<< PickerInlineRow<String> {
                            $0.title = "Tap to select"
                            $0.value = "client"
                            $0.options = nameList
                         }
        }

        editButton.title = tableView.isEditing ? "Done" : "Edit"
        editButton.target = self
        editButton.action = #selector(editPressed(sender:))

        form    +++

                section

                +++

                section2
    }

    func editPressed(sender: UIBarButtonItem){
        tableView.setEditing(!tableView.isEditing, animated: true)
        editButton.title = tableView.isEditing ? "Done" : "Edit"

    }
}

Body:
In Core.swift file you need to change this function :

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)

from public to open, then you can use this function in your view controller.


问:
Cloudformation Hide parameters in Wizard
I wish to keep instance type / VPC etc private for users using my cloudformation script. Does anyone know of a way to hide these parameters during the stack creation wizard?

I know echo keeps the values private, but is there a way for it all to not be displayed on screen.

Ideally it would ask for Stack name and the rest of the page would be blank.

答:
For sensitive parameter values (such as passwords), set the NoEcho property to true. That way, whenever anyone describes your stack, the parameter value is shown as asterisks (*****). </p>

<p>Although in your case, this cannot prevent the user of checking the instance type inside their respective tabs. Probably is a better idea to restrict the access of users to confidential information using IAM policies. </p>

Body:
For sensitive parameter values (such as passwords), set the NoEcho property to true. That way, whenever anyone describes your stack, the parameter value is shown as asterisks (*****).

Although in your case, this cannot prevent the user of checking the instance type inside their respective tabs. Probably is a better idea to restrict the access of users to confidential information using IAM policies.


问:
path param in URL in GO without any web framework
While developing a REST api in Go, how can we use path params? meaning to say what will be the format of the URI?

```<code>http://localhost:8765/myapp/{param1}/entries/{param2}
</code>```

I tried using something like this to create the route but the handler function is not getting invoked.

Please note that, i intent to use only the net/http package , not any other web framework like gorilla mux.

答:
Well this is why people use frameworks like gin-gonic because this is not easy to do this in the net/http package IIUC.

Otherwise, you would need to strings.Split(r.URL.Path, "/") and work from those elements.

Body:
While developing a REST api in Go, how can we use path params? meaning to say what will be the format of the URI?

http://localhost:8765/myapp/{param1}/entries/{param2}

I tried using something like this to create the route but the handler function is not getting invoked.

Please note that, i intent to use only the net/http package , not any other web framework like gorilla mux.


问:
Woocommerce: I want to make the shopping cart drop down after add to cart
I have been trying to do something rather simple: getting a cart to dropdown after a user added something to their cart and stay there, until they click it away.

I've tried adding a php function through functions.php in my childtheme, adding custom javascript code, but it doesn't react. I can't seem to capture the event with javascript/jquery.
Woocommerce reloads the page after adding something to the cart, since it's a variation product.

This is what the html code for the cart looks like:

```<code><div id="shoppingcart-dropdown" class="mkd-shopping-cart-dropdown">
                            <ul>
                                                                    <li>
                                        <div class="mkd-item-image-holder">
                                            <a itemprop="url" href="https://gemini-bracelets.com/collection/ladies/musthave-deluxe-vanilla-8mm/">
                                                <img src="//gemini-bracelets.com/wp-content/uploads/2017/06/Musthave-Deluxe-Summer-Night-8mm-300x200.jpg" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="" width="300" height="200">                                            </a>
                                        </div>
                                        <div class="mkd-item-info-holder">
                                            <h5 itemprop="name" class="mkd-product-title"><a itemprop="url" href="https://gemini-bracelets.com/collection/ladies/musthave-deluxe-vanilla-8mm/">Musthave Deluxe Summer Night 8mm</a></h5>
                                            <span class="mkd-quantity">2</span>
                                            <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">€</span>39,95</span>                                            <a href="https://gemini-bracelets.com/cart/?remove_item=6c2e0a0990dacd72f16b437da82dc6cc&_wpnonce=663fbc7a93" class="remove" title="Remove this item"><span class="icon-arrows-remove"></span></a>                                        </div>
                                    </li>
                                                                    <li>
                                        <div class="mkd-item-image-holder">
                                            <a itemprop="url" href="https://gemini-bracelets.com/collection/ladies/musthave-deluxe-vanilla-8mm/">
                                                <img src="//gemini-bracelets.com/wp-content/uploads/2017/06/Musthave-Deluxe-Summer-Night-8mm-300x200.jpg" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="" width="300" height="200">                                            </a>
                                        </div>
                                        <div class="mkd-item-info-holder">
                                            <h5 itemprop="name" class="mkd-product-title"><a itemprop="url" href="https://gemini-bracelets.com/collection/ladies/musthave-deluxe-vanilla-8mm/">Musthave Deluxe Summer Night 8mm</a></h5>
                                            <span class="mkd-quantity">3</span>
                                            <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">€</span>39,95</span>                                            <a href="https://gemini-bracelets.com/cart/?remove_item=8ed888de28bd08234d727d879e5f7a36&_wpnonce=663fbc7a93" class="remove" title="Remove this item"><span class="icon-arrows-remove"></span></a>                                        </div>
                                    </li>
                                                                <div class="mkd-cart-bottom">
                                    <div class="mkd-subtotal-holder clearfix">
                                        <span class="mkd-total">TOTAL:</span>
                                        <span class="mkd-total-amount">
                                        <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">€</span>199,75</span>                                  </span>
                                    </div>
                                                                        <div class="mkd-btn-holder clearfix">
                                        <a itemprop="url" href="https://gemini-bracelets.com/cart/" class="mkd-view-cart" data-title="VIEW CART"><span>VIEW CART</span></a>
                                    </div>
                                    <div class="mkd-btn-holder clearfix">
                                        <a itemprop="url" href="https://gemini-bracelets.com/checkout/" class="mkd-view-cart" data-title="CHECKOUT"><span>CHECKOUT</span></a>
                                    </div>
                                </div>
                            </ul>
                        </div>
</code>```

And this is what I have been trying to do with jquery:

```<code>window.jQuery( document ).ready( function ( $ ) {
    $( 'body' ).on( 'added_to_cart', function ( event, fragments, cart_hash, $button ) {

        $('div#shoppingcart-dropdown').addClass('.after-add');
        $('body').on('click', function(){
            $('#shoppingcart-dropdown').removeClass('.after-add');
        })
    } );
} );
</code>```

答:
you can add yourself into cart using ajax. First you have to prevent the running default function and add the cart by putting below function.
This function in your script file.

```<code>$('.add_to_cart_button').click(function(e){
    e.preventDefault();

    var product_id = $(this).attr('data-product_id');

    $.post(ajaxhandle,{'action':'add_foobar','product_id':product_id},function(response){

        if(response==0){
        console.log('error');
        }
      else{
            console.log('success');
        }
    });

});
</code>```

This function in functions.php

```<code>add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );

function prefix_ajax_add_foobar() {
$product_id  = $_POST['product_id'];

// add code the add the product to your cart
global $woocommerce;
$woocommerce->cart->add_to_cart( $product_id );
die();
}
</code>```

Bellow function create short code for Mini cart. You can put this[custom-mini-cart] shortcode wherever you want..

```<code>// you can change the display as per your wish
function custom_mini_cart() {
//don't want total means you can remove this
echo '<a href="#" class="dropdown-back" data-toggle="dropdown"> ';
    echo '<i class="fa fa-shopping-cart" aria-hidden="true"></i>';
    echo '<div class="basket-item-count" style="display: inline;">';
        echo '<span class="cart-items-count count">';
            echo WC()->cart->get_cart_contents_count();
        echo ' items -';
        echo WC()->cart->get_cart_total();
        echo  '</span>';
    echo '</div>';
echo '</a>';
echo '<ul class="dropdown-menu dropdown-menu-mini-cart">';
        echo '<li> <div class="widget_shopping_cart_content">';
                  woocommerce_mini_cart();
            echo '</div></li></ul>';

}
add_shortcode( 'custom-mini-cart', 'custom_mini_cart' );
</code>```

This function for automatically refresh the mini cart.

```<code>//you have to change according to above mini cart shortcode function.

add_filter( 'woocommerce_add_to_cart_fragments', function($fragments) {

ob_start();
?>

<a href="#" class="dropdown-back" data-toggle="dropdown">
    <i class="fa fa-shopping-cart" aria-hidden="true"></i>
    <div class="basket-item-count" style="display: inline;">
        <span class="cart-items-count count">
            <?php echo WC()->cart->get_cart_contents_count(); ?>
        items -
        <?php echo WC()->cart->get_cart_total(); ?>
        </span>
    </div>
</a>

<?php $fragments['a.dropdown-back'] = ob_get_clean();

return $fragments;

} );

add_filter( 'woocommerce_add_to_cart_fragments', function($fragments) {

ob_start();
?>

<ul class="dropdown-menu dropdown-menu-mini-cart">
       <li> <div class="widget_shopping_cart_content">
                  <?php woocommerce_mini_cart(); ?>
            </div></li></ul>

<?php $fragments['ul.dropdown-menu'] = ob_get_clean();

return $fragments;

} );
</code>```

please just try it..

Body:
I have been trying to do something rather simple: getting a cart to dropdown after a user added something to their cart and stay there, until they click it away.

I've tried adding a php function through functions.php in my childtheme, adding custom javascript code, but it doesn't react. I can't seem to capture the event with javascript/jquery.
Woocommerce reloads the page after adding something to the cart, since it's a variation product.

This is what the html code for the cart looks like:

Musthave Deluxe Summer Night 8mm

                                            2
                                            €39,95

Musthave Deluxe Summer Night 8mm

                                            3
                                            €39,95

                                        TOTAL:

                                        €199,75

                                        VIEW CART

                                        CHECKOUT

And this is what I have been trying to do with jquery:

window.jQuery( document ).ready( function ( $ ) {
    $( 'body' ).on( 'added_to_cart', function ( event, fragments, cart_hash, $button ) {

        $('div#shoppingcart-dropdown').addClass('.after-add');
        $('body').on('click', function(){
            $('#shoppingcart-dropdown').removeClass('.after-add');
        })
    } );
} );

Body:
you can add yourself into cart using ajax. First you have to prevent the running default function and add the cart by putting below function.
This function in your script file.

$('.add_to_cart_button').click(function(e){
    e.preventDefault();

    var product_id = $(this).attr('data-product_id');

    $.post(ajaxhandle,{'action':'add_foobar','product_id':product_id},function(response){

        if(response==0){
        console.log('error');
        }
      else{
            console.log('success');
        }
    });

});

This function in functions.php

add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );

function prefix_ajax_add_foobar() {
$product_id  = $_POST['product_id'];

// add code the add the product to your cart
global $woocommerce;
$woocommerce->cart->add_to_cart( $product_id );
die();
}

Bellow function create short code for Mini cart. You can put this[custom-mini-cart] shortcode wherever you want..

// you can change the display as per your wish
function custom_mini_cart() {
//don't want total means you can remove this
echo '<a href="#" class="dropdown-back" data-toggle="dropdown"> ';
    echo '<i class="fa fa-shopping-cart" aria-hidden="true"></i>';
    echo '<div class="basket-item-count" style="display: inline;">';
        echo '<span class="cart-items-count count">';
            echo WC()->cart->get_cart_contents_count();
        echo ' items -';
        echo WC()->cart->get_cart_total();
        echo  '</span>';
    echo '</div>';
echo '</a>';
echo '<ul class="dropdown-menu dropdown-menu-mini-cart">';
        echo '<li> <div class="widget_shopping_cart_content">';
                  woocommerce_mini_cart();
            echo '</div></li></ul>';

}
add_shortcode( 'custom-mini-cart', 'custom_mini_cart' );

This function for automatically refresh the mini cart.

//you have to change according to above mini cart shortcode function.

add_filter( 'woocommerce_add_to_cart_fragments', function($fragments) {

ob_start();
?>

<a href="#" class="dropdown-back" data-toggle="dropdown">
    <i class="fa fa-shopping-cart" aria-hidden="true"></i>
    <div class="basket-item-count" style="display: inline;">
        <span class="cart-items-count count">
            <?php echo WC()->cart->get_cart_contents_count(); ?>
        items -
        <?php echo WC()->cart->get_cart_total(); ?>
        </span>
    </div>
</a>

<?php $fragments['a.dropdown-back'] = ob_get_clean();

return $fragments;

} );

add_filter( 'woocommerce_add_to_cart_fragments', function($fragments) {

ob_start();
?>

<ul class="dropdown-menu dropdown-menu-mini-cart">
       <li> <div class="widget_shopping_cart_content">
                  <?php woocommerce_mini_cart(); ?>
            </div></li></ul>

<?php $fragments['ul.dropdown-menu'] = ob_get_clean();

return $fragments;

} );

please just try it..


问:
passing iterators to lambda
I want to use the lambda expression for the following codes,

```<code>long long noOfways =0;
 auto dist =0;
 for(auto iter = noChocolets.begin()+1;iter!=noChocolets.end();iter++)
 {
     dist+=*(iter)-*(iter-1);
     noOfways+=  minOper(dist);
 }
</code>```

I particularly want to convert  for loop to a lambda expression. How can I do that?

答:
Usage of iterators are equivalent with range-base loop/lambda and std::for_each so there is always a way to replace one of the approaches to the other. But as mentioned in comments the iterator approach has advantage of its clearness... Exemplary c++17 solution:

```<code>#include <vector>
#include <algorithm>
#include <optional>

int main() {
    std::vector<int> v {1, 2, 3, 4};
    auto dist =0;
    long long noOfways =0;
    auto minOper = [](auto e) {return e;};
    std::optional<decltype(v)::value_type> prev {};
    std::for_each(v.begin(), v.end(), [&](auto e)  {
        if (prev.has_value()) {
            dist += e - prev.value();
            noOfways+=  minOper(dist);
        }
        prev = e;
    });
}
</code>```

[live demo]

To back port it to c++11 use boost::optional and non-generic lambdas.

Title: passing iterators to lambda

Body:
I want to use the lambda expression for the following codes,

long long noOfways =0;
 auto dist =0;
 for(auto iter = noChocolets.begin()+1;iter!=noChocolets.end();iter++)
 {
     dist+=*(iter)-*(iter-1);
     noOfways+=  minOper(dist);
 }

I particularly want to convert  for loop to a lambda expression. How can I do that?

Body:
Usage of iterators are equivalent with range-base loop/lambda and std::for_each so there is always a way to replace one of the approaches to the other. But as mentioned in comments the iterator approach has advantage of its clearness... Exemplary c++17 solution:

#include <vector>
#include <algorithm>
#include <optional>

int main() {
    std::vector<int> v {1, 2, 3, 4};
    auto dist =0;
    long long noOfways =0;
    auto minOper = [](auto e) {return e;};
    std::optional<decltype(v)::value_type> prev {};
    std::for_each(v.begin(), v.end(), [&](auto e)  {
        if (prev.has_value()) {
            dist += e - prev.value();
            noOfways+=  minOper(dist);
        }
        prev = e;
    });
}

[live demo]

To back port it to c++11 use boost::optional and non-generic lambdas.


问:
Starting with SWIFT Programming
I am new to IOS applications development using SWIFT Programming. Are there any alternate software's or applications which can be used on a Windows laptop to code using Swift? I dont have a Mac system. </p>

答: You absolutely need OSX to write iOS apps. There are ways to run OSX on a Windows PC but they are against the OSX EULA.</p>

Title: Starting with SWIFT Programming


问:
Can I reduce mongo database size by normalizing and storing only values in each document?
I'm totally new to Mongo, and decided to give it a try with my dateset, which I store now in MySQL. I have started with a single table, which turns out to be document collection now.

Each document has about 30 properties and each property is generally a short string. So in MySQL I have varchar fields, and here in Mongo it's just BSON.

I was really surprised when I found out that the database size I got in Mongo almost 7 times bigger than mysql innodb. With 1,500,000 records/documents it is about 350 Mb in MySQL and 2.3 Gb in Monbo since it stores property name for each single piece of data.

Is there a way to come up with 'schema' and normalize data to reduce the database size?

UPD:
I use MongoDB 3.4, and since db.serverstatus().storageEngine.name is mmapv1, I suppose I use MMap.

Sample document:

```<code>{
  "_id" : ObjectId("595c4f4342ce99299c19c379"),
  "someNumber" : "11420",
  "companyDataFromSource1" : {
    "lolNumber" : "11420",
    "businessName" : "Feather mighty shop Inc",
    "businessOwner" : "",
    "businessHealthCode" : "Q",
    "realUpdateDate" : "13-OCt-16",
    "someNumericInfo" : "10000",
    "yearWhenItHappened" : "2014",
    "moreDate" : "22-Jan-02",
    "anotherStatus" : "DE",
    "numValue1" : "1",
    "numValue2" : "1",
    "someProp" : "E",
    "anotherProp" : "R",
    "street" : "BB251 Database St",
    "city" : "Denver",
    "state" : "CO",
    "zip" : "12345",
    "country" : "US",
    "anotherStreet" : "TT251 Server St",
    "anotherCity" : "Sratford",
    "anotherState" : "WI",
    "anotherZip" : "54484",
    "anotherCountry" : "US",
    "telephone" : "(123) 481-2222",
    "fax" : "",
    "emailAddress" : "qwwqwwqeewe@hotmail.com",
  }
}
</code>```

db.collecion('collection').stats results:

```<code>{
  "ns" : "db.collection",
  "size" : 1507059792.0,
  "count" : 1495099,
  "avgObjSize" : 1008,
  "numExtents" : 19,
  "storageSize" : 1580150784.0,
  "lastExtentSize" : 415174656.0,
  "paddingFactor" : 1.0,
  "paddingFactorNote" : "paddingFactor is unused and unmaintained in 3.0. It remains hard coded to 1.0 for compatibility only.",
  "userFlags" : 1,
  "capped" : false,
  "nindexes" : 1,
  "totalIndexSize" : 60518752,
  "indexSizes" : {
      "_id_" : 60518752
  },
"ok" : 1.0
}
</code>```

答:
Is there a way to come up with 'schema' and reduce the database size?

No. Mongodb is schemaless, that is one of its core features. You could use shorter names for your properties. Or use a compressing storage engine (WiredTiger).

Body:
I'm totally new to Mongo, and decided to give it a try with my dateset, which I store now in MySQL. I have started with a single table, which turns out to be document collection now.

Each document has about 30 properties and each property is generally a short string. So in MySQL I have varchar fields, and here in Mongo it's just BSON.

I was really surprised when I found out that the database size I got in Mongo almost 7 times bigger than mysql innodb. With 1,500,000 records/documents it is about 350 Mb in MySQL and 2.3 Gb in Monbo since it stores property name for each single piece of data.

Is there a way to come up with 'schema' and normalize data to reduce the database size?

UPD:
I use MongoDB 3.4, and since db.serverstatus().storageEngine.name is mmapv1, I suppose I use MMap.

Sample document:

{
  "_id" : ObjectId("595c4f4342ce99299c19c379"),
  "someNumber" : "11420",
  "companyDataFromSource1" : {
    "lolNumber" : "11420",
    "businessName" : "Feather mighty shop Inc",
    "businessOwner" : "",
    "businessHealthCode" : "Q",
    "realUpdateDate" : "13-OCt-16",
    "someNumericInfo" : "10000",
    "yearWhenItHappened" : "2014",
    "moreDate" : "22-Jan-02",
    "anotherStatus" : "DE",
    "numValue1" : "1",
    "numValue2" : "1",
    "someProp" : "E",
    "anotherProp" : "R",
    "street" : "BB251 Database St",
    "city" : "Denver",
    "state" : "CO",
    "zip" : "12345",
    "country" : "US",
    "anotherStreet" : "TT251 Server St",
    "anotherCity" : "Sratford",
    "anotherState" : "WI",
    "anotherZip" : "54484",
    "anotherCountry" : "US",
    "telephone" : "(123) 481-2222",
    "fax" : "",
    "emailAddress" : "qwwqwwqeewe@hotmail.com",
  }
}

db.collecion('collection').stats results:

{
  "ns" : "db.collection",
  "size" : 1507059792.0,
  "count" : 1495099,
  "avgObjSize" : 1008,
  "numExtents" : 19,
  "storageSize" : 1580150784.0,
  "lastExtentSize" : 415174656.0,
  "paddingFactor" : 1.0,
  "paddingFactorNote" : "paddingFactor is unused and unmaintained in 3.0. It remains hard coded to 1.0 for compatibility only.",
  "userFlags" : 1,
  "capped" : false,
  "nindexes" : 1,
  "totalIndexSize" : 60518752,
  "indexSizes" : {
      "_id_" : 60518752
  },
"ok" : 1.0
}


问:
Split comma separated string into rows in mysql
When I have string list like 1, 2, 3...
I'd like to use this as one column

```<code>Ids
1
2
3
</code>```

Is it possible by sql query?

ex) SELECT Ids from (1, 2, 3...)   <- I know this is not working.

答:
Use a subquery of arbitrary digits to split your string.Instead of vals you can use '1,2,3'.

```<code>SELECT
  DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(vals, ',', n.digit+1), ',', -1) val
FROM
  tt1
  INNER JOIN
  (SELECT 0 digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3  UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6) n
  ON LENGTH(REPLACE(vals, ',' , '')) <= LENGTH(vals)-n.digit;
</code>```

See it working

Body:
When I have string list like 1, 2, 3...
I'd like to use this as one column

Ids
1
2
3

Is it possible by sql query?

ex) SELECT Ids from (1, 2, 3...)   <- I know this is not working.

Body:
Use a subquery of arbitrary digits to split your string.Instead of vals you can use '1,2,3'.

SELECT
  DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(vals, ',', n.digit+1), ',', -1) val
FROM
  tt1
  INNER JOIN
  (SELECT 0 digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3  UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6) n
  ON LENGTH(REPLACE(vals, ',' , '')) <= LENGTH(vals)-n.digit;

See it working


问:
How to convert CSV file to XML format using linux script in linux box
I need to convert the CSV file to XML format to meet one of my requirement.
I am completely new for this process.

I have refereed some links like:
https://help.ubuntu.com/community/Converting%20CSV%20to%20XML

here they have asked to install tools.
But i don't have privilege to install any tool in the server.
So i need to try with any linux script to achieve my task.

before i have used xlsx2csv script for converting xlsx file to csv. in the same manner i am trying to get the script.

I have tried with https://gist.github.com/AnthonyNystrom/5547886
i am not able read the input file it self. I am trying in our linux server

Can any one help me on finding the solution.

Thanks for your help in advance.

答:
There are several tools for converting csv to xml. Those could do the job for you.

This site contains multiple tools you can use: https://help.ubuntu.com/community/Converting%20CSV%20to%20XML

Source: https://askubuntu.com/questions/581265/how-can-i-convert-a-csv-file-to-xml


问:
Error : RuntimeException at DisplayListCanvas.throwIfCannotDraw
My application work very well on nougat emulator and many devices, but i found this exception in google play crash reporter, I don't know why it happened, The exception causes with nougat devices ++ only.

the exception :

```<code>   java.lang.RuntimeException:
  at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
  at android.graphics.Canvas.drawBitmap(Canvas.java:1420)
  at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:545)
  at android.view.View.getDrawableRenderNode(View.java:18591)
  at android.view.View.drawBackground(View.java:18527)
  at android.view.View.draw(View.java:18315)
  at android.view.View.updateDisplayListIfDirty(View.java:17302)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.draw(View.java:18327)
  at com.android.internal.policy.DecorView.draw(DecorView.java:919)
  at android.view.View.updateDisplayListIfDirty(View.java:17302)
  at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:692)
  at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:698)
  at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:806)
  at android.view.ViewRootImpl.draw(ViewRootImpl.java:3135)
  at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2931)
  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2523)
  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1522)
  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7098)
  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:927)
  at android.view.Choreographer.doCallbacks(Choreographer.java:702)
  at android.view.Choreographer.doFrame(Choreographer.java:638)
  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
  at android.os.Handler.handleCallback(Handler.java:751)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:154)
  at android.app.ActivityThread.main(ActivityThread.java:6682)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

What this error could be?

CAUTION: all drawable i used is less than 1MB.

答: Try to set a debug point in android.view.DisplayListCanvas.throwIfCannotDraw and check what image is throw an exception. Some of them is incorrect - large size or you have too many images for example and cant record to canvas pool.

Body:
My application work very well on nougat emulator and many devices, but i found this exception in google play crash reporter, I don't know why it happened, The exception causes with nougat devices ++ only.

the exception :

   java.lang.RuntimeException:
  at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
  at android.graphics.Canvas.drawBitmap(Canvas.java:1420)
  at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:545)
  at android.view.View.getDrawableRenderNode(View.java:18591)
  at android.view.View.drawBackground(View.java:18527)
  at android.view.View.draw(View.java:18315)
  at android.view.View.updateDisplayListIfDirty(View.java:17302)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.updateDisplayListIfDirty(View.java:17297)
  at android.view.View.draw(View.java:18086)
  at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
  at android.view.View.draw(View.java:18327)
  at com.android.internal.policy.DecorView.draw(DecorView.java:919)
  at android.view.View.updateDisplayListIfDirty(View.java:17302)
  at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:692)
  at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:698)
  at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:806)
  at android.view.ViewRootImpl.draw(ViewRootImpl.java:3135)
  at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2931)
  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2523)
  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1522)
  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7098)
  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:927)
  at android.view.Choreographer.doCallbacks(Choreographer.java:702)
  at android.view.Choreographer.doFrame(Choreographer.java:638)
  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
  at android.os.Handler.handleCallback(Handler.java:751)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:154)
  at android.app.ActivityThread.main(ActivityThread.java:6682)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

What this error could be?

CAUTION: all drawable i used is less than 1MB.


问:
How to get the blogger first image URL in the post
I want the URL of the FIrst image in the post and then use it as background image of a DIV</p>

答:
help

```<code><div class="newphoto" ></div>
    <script>
    document.getElementsByClassName('newphoto')[0].style.backgroundImage = "url('<data:blog.postImageUrl/>')" ;
    </script>
</code>```

Add the else line to javascipt

```<code>document.getElementsByClassName('newphoto')[0].style.backgroundImage = "url('https://1.bp.blogspot.com/-aAjLvDndDIo/WH2DcqOeX9I/AAAAAAAAI9Y/W3_fmq0uGXseb_A1XWhaj5ZyL3DzKJD9ACLcB/s1600/bgplaydefault_djhayhay247.jpg')" ;
</code>```

Body:
help

<div class="newphoto" ></div>
    <script>
    document.getElementsByClassName('newphoto')[0].style.backgroundImage = "url('<data:blog.postImageUrl/>')" ;
    </script>

Add the else line to javascipt

document.getElementsByClassName('newphoto')[0].style.backgroundImage = "url('https://1.bp.blogspot.com/-aAjLvDndDIo/WH2DcqOeX9I/AAAAAAAAI9Y/W3_fmq0uGXseb_A1XWhaj5ZyL3DzKJD9ACLcB/s1600/bgplaydefault_djhayhay247.jpg')" ;


问:
XML Schema key/keyref - how to use them?
Long story short : i would like to know how to use the key/keyref from XSD to let elements have references to each other. it has to have a form of an example, using a simple xsd and an XML.

Long story : I am familiar with usage of ID/IDREF. I use those to connect elements for JAXB. I have been told repeatedly that the key/keyref construct in XSD offers enhanced flexibility for inter-element referencing. I have consulted the OReilly XML Schema book, that seems to teach everything about correct definition of key/keyref and how it is similar to the ID/IDREF (but better) and doesn't give a simple example of its use. It doesn't seem to be similar, because you define the ID as an attribute in one element and the IDREF in another element and voila. But key/keyref have to be defined in a common ancestor of the referencing and the referenced element (AFAIK)...

I use the XSD files to generate JAXB-bound Java classes with XJC

I have searched for how-tos, tutorials and examples, but google gives me scraps. same for searches on SO (also with google and inclusive search with '+' ).

In order to make everyone's lives easier i have prepared an XSD with already defined key/keyref pair as i have understood it.

```<code><xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="referenced">
                <xs:complexType>
                    <xs:attribute name="id" type="xs:string" />
                </xs:complexType>
            </xs:element>
            <xs:element name="owner">
                <xs:complexType>
                    <xs:attribute name="id" type="xs:string" />
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
    <xs:key name="aKey">
        <xs:selector xpath="owner" />
        <xs:field xpath="@id" />
    </xs:key>
    <xs:keyref name="aKeyRef" refer="aKey">
        <xs:selector xpath="referenced" />
        <xs:field xpath="@id" />
    </xs:keyref>
</xs:element>
</code>```

How would a piece of XML look like, with an 'owner'-element referencing a 'referenced'-element?

EDIT :  applied the change proposed by Tom W, changing the xpath attribute of the key element to "owner". JAXB (XJC) still doesnt care though.

Thank you

答:
There is no special syntax in the instance document. It is simply required that the keyref node matches an extant key node. Validation will tell you whether or not the key constraint is satisfied.

RE your code:

I've only just started dabbling with keys myself, but I think I've spotted an error in yours - aKey should look like:

```<code><xs:key name="aKey">
    <xs:selector xpath="owner" />
    <xs:field xpath="@id" />
</xs:key>
</code>```

Furthermore - this is a gotcha - key constraints don't recognise the default namespace. You must always prefix every part of the selector xpath with the namespace prefix of the element you're looking up. If you don't have a namespace prefix - tough, you'll need to add one. This is a limitation of the standard.

ContentLicense: CC BY-SA 2.5

Body:
Long story short : i would like to know how to use the key/keyref from XSD to let elements have references to each other. it has to have a form of an example, using a simple xsd and an XML.

Long story : I am familiar with usage of ID/IDREF. I use those to connect elements for JAXB. I have been told repeatedly that the key/keyref construct in XSD offers enhanced flexibility for inter-element referencing. I have consulted the OReilly XML Schema book, that seems to teach everything about correct definition of key/keyref and how it is similar to the ID/IDREF (but better) and doesn't give a simple example of its use. It doesn't seem to be similar, because you define the ID as an attribute in one element and the IDREF in another element and voila. But key/keyref have to be defined in a common ancestor of the referencing and the referenced element (AFAIK)...

I use the XSD files to generate JAXB-bound Java classes with XJC

I have searched for how-tos, tutorials and examples, but google gives me scraps. same for searches on SO (also with google and inclusive search with '+' ).

In order to make everyone's lives easier i have prepared an XSD with already defined key/keyref pair as i have understood it.

<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="referenced">
                <xs:complexType>
                    <xs:attribute name="id" type="xs:string" />
                </xs:complexType>
            </xs:element>
            <xs:element name="owner">
                <xs:complexType>
                    <xs:attribute name="id" type="xs:string" />
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
    <xs:key name="aKey">
        <xs:selector xpath="owner" />
        <xs:field xpath="@id" />
    </xs:key>
    <xs:keyref name="aKeyRef" refer="aKey">
        <xs:selector xpath="referenced" />
        <xs:field xpath="@id" />
    </xs:keyref>
</xs:element>

How would a piece of XML look like, with an 'owner'-element referencing a 'referenced'-element?

EDIT :  applied the change proposed by Tom W, changing the xpath attribute of the key element to "owner". JAXB (XJC) still doesnt care though.

Thank you

Body:
There is no special syntax in the instance document. It is simply required that the keyref node matches an extant key node. Validation will tell you whether or not the key constraint is satisfied.

RE your code:

I've only just started dabbling with keys myself, but I think I've spotted an error in yours - aKey should look like:

<xs:key name="aKey">
    <xs:selector xpath="owner" />
    <xs:field xpath="@id" />
</xs:key>

Furthermore - this is a gotcha - key constraints don't recognise the default namespace. You must always prefix every part of the selector xpath with the namespace prefix of the element you're looking up. If you don't have a namespace prefix - tough, you'll need to add one. This is a limitation of the standard.


问:
Show/hide a record based on condition inside ng-repeat not working
Below are my records :

```<code>$scope.currentSelection = "Admin";

$scope.records = [
     { id: 'Employee', params:[]},
     { id: 'Skills', params:[]},
     { id: 'Payroll', params:[]},
     { id: 'Appraisal', params:[]},
     { id : 'Statistics',params:[]}
];
</code>```

Now if $scope.currentSelection is admin then I want to show all items with statistics(Employee,Skills,Payroll,Appraisal,Statistics) else I don't want to show Statistics rest other items (Employee,Skills,Payroll,Appraisal) if $scope.currentSelection is Guest or Employee.

But the problem is when currentSelection is Admin then others items are not showing up except statistics.

Note: I don't want to use a filter for this.

But the problem

var app = angular.module("myApp", []);
app.controller("MyController", function ($scope) {
     $scope.currentSelection = "Admin";
     $scope.records = [
          { id: 'Employee', params:[]},
          { id: 'Skills', params:[]},
          { id: 'Payroll', params:[]},
          { id: 'Appraisal', params:[]},
          { id : 'Statistics',params:[]}
     ];
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <ul ng-app="myApp" ng-controller="MyController">
     <li ng-repeat="item in records">
         <div ng-show="currentSelection=='Admin' && item.id=='Statistics'">{{item.id}}
         </div>
    </li>
</ul></code>```

答:
You need to Change your show condition currentSelection === 'Admin' && item.id === 'Statistics' to currentSelection === 'Admin' && item.id !== 'Statistics'.

var app = angular.module("myApp", []);
        app.controller("MyController", function ($scope) {
            $scope.currentSelection = "Non";

 $scope.records = [ { id: 'Employee', params:[]},
                    { id: 'Skills', params:[]},
                    { id: 'Payroll', params:[]},
                    { id: 'Appraisal', params:[]},
                    { id : 'Statistics',params:[]}];

 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

 <ul ng-app="myApp" ng-controller="MyController">
  <div ng-if="currentSelection === 'Admin'">
    <li ng-repeat="item in records">
       <div>{{item.id}}</div>
    </li>
  </div>
  <div ng-if="currentSelection !== 'Admin'">
  <li ng-repeat="item in records" ng-show="item.id !== 'Statistics'">
       <div>{{item.id}}</div>
  </li>
  </div>
</ul></code>```

Body:
Below are my records :

$scope.currentSelection = "Admin";

$scope.records = [
     { id: 'Employee', params:[]},
     { id: 'Skills', params:[]},
     { id: 'Payroll', params:[]},
     { id: 'Appraisal', params:[]},
     { id : 'Statistics',params:[]}
];

Now if $scope.currentSelection is admin then I want to show all items with statistics(Employee,Skills,Payroll,Appraisal,Statistics) else I don't want to show Statistics rest other items (Employee,Skills,Payroll,Appraisal) if $scope.currentSelection is Guest or Employee.

But the problem is when currentSelection is Admin then others items are not showing up except statistics.

Note: I don't want to use a filter for this.

But the problem

var app = angular.module("myApp", []);
app.controller("MyController", function ($scope) {
     $scope.currentSelection = "Admin";
     $scope.records = [
          { id: 'Employee', params:[]},
          { id: 'Skills', params:[]},
          { id: 'Payroll', params:[]},
          { id: 'Appraisal', params:[]},
          { id : 'Statistics',params:[]}
     ];
 });

{{item.id}}

Body:
You need to Change your show condition currentSelection === 'Admin' && item.id === 'Statistics' to currentSelection === 'Admin' && item.id !== 'Statistics'.

var app = angular.module("myApp", []);
        app.controller("MyController", function ($scope) {
            $scope.currentSelection = "Non";

 $scope.records = [ { id: 'Employee', params:[]},
                    { id: 'Skills', params:[]},
                    { id: 'Payroll', params:[]},
                    { id: 'Appraisal', params:[]},
                    { id : 'Statistics',params:[]}];

 });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

 <ul ng-app="myApp" ng-controller="MyController">
  <div ng-if="currentSelection === 'Admin'">
    <li ng-repeat="item in records">
       <div>{{item.id}}</div>
    </li>
  </div>
  <div ng-if="currentSelection !== 'Admin'">
  <li ng-repeat="item in records" ng-show="item.id !== 'Statistics'">
       <div>{{item.id}}</div>
  </li>
  </div>
</ul>


答:
A few hints on how to reduce your database size:

Database engine

First, switch from MMApv1 to WiredTiger storage engine, as it's way more efficient to compress data.
The default compression level is snappy, but you can compress even more using zlib with few performance trade off. See Mongodb 3.0  for details.

To move to WiredTiger, see this tutorial from MongoDB documentation: https://docs.mongodb.com/manual/tutorial/change-standalone-wiredtiger/

Reduce key size

Second thing is to reduce your documents size (currently ~1008 bytes according to the avgObjSize field ). To do this, use smaller keys (ideally, two letter long keys).
for example,

companyDataFromSource1 ==> c1

The benefits from this will be small with compression enabled, but this is always a good practice as it reduce the size of data that will be send to your app / over network

Title: Can I reduce mongo database size by normalizing and storing only values in each document?


问:
Talend - System env variables not reflecting without restart
I'm using system environment variables to parameterise jobs in talend, But every time I change any value, without restarting talend I'm not able to get the changes reflected. Is there any workaround? I don't want to use Context groups or Implicit Context load. I'm using Talend Open Studio free edition. Is this any different in Enterprise version?</p>

答:
This has to do with Talend is handling environment variables. Talend is reading the environment variables at startup and stores them. There is a good answer here which explains this behavior in more detail regarding Java (Talend is build on Java).

There are also some tricks listed how to get the variables depending on your OS.


问:
File not readable from documents folder
I am creating a binary file using few c libraries and saving the file in documents folder of app in iOS. But when i try to read it its not reading. I am using the following code to read. </p>

```<code>let fileData = try NSData(contentsOfFile: filePath, options: NSData.ReadingOptions.mappedIfSafe) as Data
</code>```

<p>But this goes always into catch block. </p>

答:
```<code>do {
    let videoData = try Data(contentsOf: avsset.url)
    print(videoData.count)
} catch let err {
    print("Error:", err)
}
</code>```

you must catch error...

Title: File not readable from documents folder

Body:
I am creating a binary file using few c libraries and saving the file in documents folder of app in iOS. But when i try to read it its not reading. I am using the following code to read.

let fileData = try NSData(contentsOfFile: filePath, options: NSData.ReadingOptions.mappedIfSafe) as Data

But this goes always into catch block.

Body:
do {
    let videoData = try Data(contentsOf: avsset.url)
    print(videoData.count)
} catch let err {
    print("Error:", err)
}

you must catch error...


问:
How do I access the ngStyle key and values in decorator?
I have a list of colour names in my application.

```<code>let colours = {
  mango: '#e59c09',
  midnight: '#1476a0'
};
</code>```

I want to extend the ngStyle directive to be able to understand my custom colour names. I'm doing this by decorating the ngStyle directive. However, I've hit an uphill battle on the decorator's compile function. I can access the elements' ngStyle attribute, but it comes up as a string (understandably). JSON.parse() doesn't work on it as it isn't always a valid JSON string due to bind once etc...

I simply want to step-in, iterate over all style keys, and if it contains color, I want to check for the value - and replace with hex if it is one of the above custom colour.

I can't seem to be able to access any ngStyle internal functions, and the source code is confusing and short; it seems to just set element CSS - where does the $parse do its job? for example, when ng-style="{color: ctrl.textColor}" - there is nothing in ngStyle source code that is pulling the value of ctrl.textColour. Am I looking at the wrong place?

Anyway, how do I access ng-style key values so that I can change custom colours to its hex codes please?

This is what I've got so far in my decorator:

```<code>$provide.decorator('ngStyleDirective', function($delegate) {

    let directive = $delegate[0];
    let link = directive.link;

    directive.compile = function(element, attrs) {

        // Expression here is a string property
        let expression = attrs.ngStyle;

        return function(scope, elem, attr) {

          // How do I iterate over and update style values here?

          // Run original function
          link.apply(this, arguments);

        }

      }

      return $delegate;

});
</code>```

I tried using regex to pull out patterns etc. and inspect elements, but, it seems like the wrong way to approach the problem to me as I then have to manually update string and pass it on to base link function.

Here's a plnkr example.

IF there is a better way to do what I'm trying to do, please let me know.

答:
Actually, if you want to use parse - and you should - you can use it to parse the expression, replace attributes, and then transform the attribute back to json.

You should use $parse because if your code looks like

```<code>// in the HTML
<p ng-style="{ padding: '20px 10px', 'background-color': myController.color, color: '#ddd' }">It is dark here</p>
// in the JS
myController.color = 'midnight';
</code>```

Then parsing JSON will not work. You should parse the expression using $parse and call the resulting function with your directive's scope object.

That's why your provider should look like this :

```<code>$provide.decorator('ngStyleDirective', function($delegate, $parse) {
  let directive = $delegate[0];
  let link = directive.link;

  directive.compile = function(element, attrs) {
    return function(scope, elem, attrs) {
      let ngStyleObject = $parse(attrs.ngStyle)(scope, {});

      Object.keys(ngStyleObject).forEach(function(key) {
        if (key.indexOf('color') > -1 && Object.keys(colours).indexOf(ngStyleObject[key]) > -1) {
          ngStyleObject[key] = colours[ngStyleObject[key]];
        }
      });

      attrs.ngStyle = JSON.stringify(ngStyleObject);
      // Run original function
      link.apply(this, arguments);
    }
  }
  return $delegate;
});
</code>```

You could also copy the original ngStyle function (instead of calling its link function) as it's pretty simple to add the behavior you expected:

```<code>$provide.decorator('ngStyleDirective', function($delegate) {
  let directive = $delegate[0];

  directive.compile = function(element, attrs) {
    return function(scope, elem, attrs) {
      // here, watch will do the $parse(attrs.ngStyle)(scope) and call the callback when values change
      scope.$watch(attrs.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
        if (oldStyles && (newStyles !== oldStyles)) {
          oldStyles.forEach(function(val, style) {  element.css(style, ''); });
        }
        if (newStyles) {
          // instead of just setting the new styles, replace colors with their values
          Object.keys(newStyles).forEach(function(key) {
            if (key.indexOf('color') > -1 && Object.keys(colours).indexOf(newStyles[key]) > -1) {
              newStyles[key] = colours[newStyles[key]];
            }
          });
          element.css(newStyles);
        }
      }, true);

    }
  }
  return $delegate;
});
</code>```

You can find the plunker (two versions) here

Body:
I have a list of colour names in my application.

let colours = {
  mango: '#e59c09',
  midnight: '#1476a0'
};

I want to extend the ngStyle directive to be able to understand my custom colour names. I'm doing this by decorating the ngStyle directive. However, I've hit an uphill battle on the decorator's compile function. I can access the elements' ngStyle attribute, but it comes up as a string (understandably). JSON.parse() doesn't work on it as it isn't always a valid JSON string due to bind once etc...

I simply want to step-in, iterate over all style keys, and if it contains color, I want to check for the value - and replace with hex if it is one of the above custom colour.

I can't seem to be able to access any ngStyle internal functions, and the source code is confusing and short; it seems to just set element CSS - where does the $parse do its job? for example, when ng-style="{color: ctrl.textColor}" - there is nothing in ngStyle source code that is pulling the value of ctrl.textColour. Am I looking at the wrong place?

Anyway, how do I access ng-style key values so that I can change custom colours to its hex codes please?

This is what I've got so far in my decorator:

$provide.decorator('ngStyleDirective', function($delegate) {

    let directive = $delegate[0];
    let link = directive.link;

    directive.compile = function(element, attrs) {

        // Expression here is a string property
        let expression = attrs.ngStyle;

        return function(scope, elem, attr) {

          // How do I iterate over and update style values here?

          // Run original function
          link.apply(this, arguments);

        }

      }

      return $delegate;

});

I tried using regex to pull out patterns etc. and inspect elements, but, it seems like the wrong way to approach the problem to me as I then have to manually update string and pass it on to base link function.

Here's a plnkr example.

IF there is a better way to do what I'm trying to do, please let me know.

Body:
Actually, if you want to use parse - and you should - you can use it to parse the expression, replace attributes, and then transform the attribute back to json.

You should use $parse because if your code looks like

// in the HTML
<p ng-style="{ padding: '20px 10px', 'background-color': myController.color, color: '#ddd' }">It is dark here</p>
// in the JS
myController.color = 'midnight';

Then parsing JSON will not work. You should parse the expression using $parse and call the resulting function with your directive's scope object.

That's why your provider should look like this :

$provide.decorator('ngStyleDirective', function($delegate, $parse) {
  let directive = $delegate[0];
  let link = directive.link;

  directive.compile = function(element, attrs) {
    return function(scope, elem, attrs) {
      let ngStyleObject = $parse(attrs.ngStyle)(scope, {});

      Object.keys(ngStyleObject).forEach(function(key) {
        if (key.indexOf('color') > -1 && Object.keys(colours).indexOf(ngStyleObject[key]) > -1) {
          ngStyleObject[key] = colours[ngStyleObject[key]];
        }
      });

      attrs.ngStyle = JSON.stringify(ngStyleObject);
      // Run original function
      link.apply(this, arguments);
    }
  }
  return $delegate;
});

You could also copy the original ngStyle function (instead of calling its link function) as it's pretty simple to add the behavior you expected:

$provide.decorator('ngStyleDirective', function($delegate) {
  let directive = $delegate[0];

  directive.compile = function(element, attrs) {
    return function(scope, elem, attrs) {
      // here, watch will do the $parse(attrs.ngStyle)(scope) and call the callback when values change
      scope.$watch(attrs.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
        if (oldStyles && (newStyles !== oldStyles)) {
          oldStyles.forEach(function(val, style) {  element.css(style, ''); });
        }
        if (newStyles) {
          // instead of just setting the new styles, replace colors with their values
          Object.keys(newStyles).forEach(function(key) {
            if (key.indexOf('color') > -1 && Object.keys(colours).indexOf(newStyles[key]) > -1) {
              newStyles[key] = colours[newStyles[key]];
            }
          });
          element.css(newStyles);
        }
      }, true);

    }
  }
  return $delegate;
});

You can find the plunker (two versions) here


问:
Finding support for frequently occurring items
Assume I have a DataFrame where each row has order id and an item. I'd like to know which items appear most frequently with another (maybe probability of item appearing in order given that another item is there?)

Let's say the data is

```<code>order_id,item
1,a
1,b
1,c
2,a
2,b
2,d
3,a
3,b
3,e
</code>```

Then the pair a,b gets the highest score.

(I'm sure there's a technical name for this, can't find it :)

One possible output will be probability of pair appearing in order, in our case something like:

```<code>item1,item2,probablility
a,b,1
a,b,0.3
b,c,0.3
a,d,0.3
b,c,0.3
a,e,0.3
b,3,0.3
</code>```

答:
To arrive at co-occurrence matrix

First, get order, item combination of occurrences

```<code>In [249]: cross = pd.crosstab(df['order_id'], df['item'])

In [250]: cross
Out[250]:
item      a  b  c  d  e
order_id
1         1  1  1  0  0
2         1  1  0  1  0
3         1  1  0  0  1
</code>```

Then, do product of cross and transposed cross.

```<code>In [251]: cross.T.dot(cross)
Out[251]:
item  a  b  c  d  e
item
a     3  3  1  1  1
b     3  3  1  1  1
c     1  1  1  0  0
d     1  1  0  1  0
e     1  1  0  0  1
</code>```

This gives you co-occurrences of every item with every other item based on order_id.

Body:
Assume I have a DataFrame where each row has order id and an item. I'd like to know which items appear most frequently with another (maybe probability of item appearing in order given that another item is there?)

Let's say the data is

order_id,item
1,a
1,b
1,c
2,a
2,b
2,d
3,a
3,b
3,e

Then the pair a,b gets the highest score.

(I'm sure there's a technical name for this, can't find it :)

One possible output will be probability of pair appearing in order, in our case something like:

item1,item2,probablility
a,b,1
a,b,0.3
b,c,0.3
a,d,0.3
b,c,0.3
a,e,0.3
b,3,0.3

Body:
To arrive at co-occurrence matrix

First, get order, item combination of occurrences

In [249]: cross = pd.crosstab(df['order_id'], df['item'])

In [250]: cross
Out[250]:
item      a  b  c  d  e
order_id
1         1  1  1  0  0
2         1  1  0  1  0
3         1  1  0  0  1

Then, do product of cross and transposed cross.

In [251]: cross.T.dot(cross)
Out[251]:
item  a  b  c  d  e
item
a     3  3  1  1  1
b     3  3  1  1  1
c     1  1  1  0  0
d     1  1  0  1  0
e     1  1  0  0  1

This gives you co-occurrences of every item with every other item based on order_id.


问:
CRC checksum calculation from Python
I'm trying to calculate the CRC32-C checksum value. I referred lot of online CRC calculators and lot of websites for writing my own crc checksum calculator. I'm not getting the expected result. From my research only "http://crccalc.com/" is giving my expected value.

I see there are many approaches with tables, without tables.. etc Nothing seems to be working for me, I'm uploading simple approach program which i used to calculate crc

```<code>POLY_LENGTH = 32

def convertobin(input_message):
    input_message = bin(input_message[::-1])
    return input_message

def find_xor(polynomial, input_message):
    # print polynomial
    print input_message
    xor = polynomial ^ input_message
    return xor

def find_crc(polynomial, packet):
    print len(packet)
    input_messageInBin = bin(int(packet,16))[2:]
    print input_messageInBin, type(input_messageInBin)
    input_messageInBin = input_messageInBin + '0'*31
    inputMessageLength = len(input_messageInBin)
    firstTime = 1
    remainder = 0
    startmarker = 0
    control = 1
    diff = 0
    stopmarker = 0
    import pdb; pdb.set_trace()
    while control:
        if len(input_messageInBin) > (startmarker + 32) :
            if firstTime:
                inputString = input_messageInBin[0:POLY_LENGTH]
                stopmarker = POLY_LENGTH - 1
                xor = find_xor(polynomial, int(inputString,2))

                xor_bits_length = len(bin(xor)) - 2
                remainder = str(bin(xor))[2:]
                diff = POLY_LENGTH - xor_bits_length
                firstTime = 0
                startmarker = startmarker + diff - 1
            else:
                diff_bits = input_messageInBin[stopmarker+1:stopmarker+diff+1]
                inputString = remainder + diff_bits
                print "--------------------------------------------------------"
                print "Total number of different bits are: ", diff
                print "remainder + diff_bits : ", remainder, "+", diff_bits
                print "XOR of :"
                print inputString
                print bin(polynomial)[2:]
                xor = find_xor(polynomial, int(inputString,2))
                xor_bits_length = len(bin(xor)) - 2
                remainder = str(bin(xor))[2:]
                print remainder
                print "--------------------------------------------------------"
                diff = POLY_LENGTH - xor_bits_length
                stopmarker = stopmarker + diff
                startmarker = startmarker + diff

        else:
            control = 0
            remainder = remainder + input_messageInBin[startmarker:stopmarker]
            print stopmarker
            print startmarker

    return remainder
val = find_crc(0x1EDC6F41, 'FFFFFFFFFFFFFFFFFFFF0F0FB01013F2E8FAF0421208')
print val
</code>```

I'm trying to get this working. Appreciate if somebody has solution for this

答:
As far as I tested module to use CRC-32C (nasty mangling ceph objects), the best was crccheck, it does not require SSE4 like the most of its  implementations.

```<code>>>> from crccheck.crc import Crc32c
>>> Crc32c().process(b'kwarunek').finalhex()
'aa862086'
</code>```

http://crccalc.com/ gives the same results.

Edit: calc for hex value

crccheck is able to calc checksum for a hex value, just requires the value to be passed as bytes - method for large integers:

```<code>x = int('FFFFFFFFFFFFFFFFFFFF0F0FB01013F2E8FAF0421208', 16)
nbytes, rem = divmod(x.bit_length(), 8)
if rem: nbytes += 1
prepared = x.to_bytes(nbytes, 'big')

Crc32c().process(prepared).finalhex()
</code>```

Title: CRC checksum calculation from Python

Body:
I'm trying to calculate the CRC32-C checksum value. I referred lot of online CRC calculators and lot of websites for writing my own crc checksum calculator. I'm not getting the expected result. From my research only "http://crccalc.com/" is giving my expected value.

I see there are many approaches with tables, without tables.. etc Nothing seems to be working for me, I'm uploading simple approach program which i used to calculate crc

POLY_LENGTH = 32

def convertobin(input_message):
    input_message = bin(input_message[::-1])
    return input_message

def find_xor(polynomial, input_message):
    # print polynomial
    print input_message
    xor = polynomial ^ input_message
    return xor

def find_crc(polynomial, packet):
    print len(packet)
    input_messageInBin = bin(int(packet,16))[2:]
    print input_messageInBin, type(input_messageInBin)
    input_messageInBin = input_messageInBin + '0'*31
    inputMessageLength = len(input_messageInBin)
    firstTime = 1
    remainder = 0
    startmarker = 0
    control = 1
    diff = 0
    stopmarker = 0
    import pdb; pdb.set_trace()
    while control:
        if len(input_messageInBin) > (startmarker + 32) :
            if firstTime:
                inputString = input_messageInBin[0:POLY_LENGTH]
                stopmarker = POLY_LENGTH - 1
                xor = find_xor(polynomial, int(inputString,2))

                xor_bits_length = len(bin(xor)) - 2
                remainder = str(bin(xor))[2:]
                diff = POLY_LENGTH - xor_bits_length
                firstTime = 0
                startmarker = startmarker + diff - 1
            else:
                diff_bits = input_messageInBin[stopmarker+1:stopmarker+diff+1]
                inputString = remainder + diff_bits
                print "--------------------------------------------------------"
                print "Total number of different bits are: ", diff
                print "remainder + diff_bits : ", remainder, "+", diff_bits
                print "XOR of :"
                print inputString
                print bin(polynomial)[2:]
                xor = find_xor(polynomial, int(inputString,2))
                xor_bits_length = len(bin(xor)) - 2
                remainder = str(bin(xor))[2:]
                print remainder
                print "--------------------------------------------------------"
                diff = POLY_LENGTH - xor_bits_length
                stopmarker = stopmarker + diff
                startmarker = startmarker + diff

        else:
            control = 0
            remainder = remainder + input_messageInBin[startmarker:stopmarker]
            print stopmarker
            print startmarker

    return remainder
val = find_crc(0x1EDC6F41, 'FFFFFFFFFFFFFFFFFFFF0F0FB01013F2E8FAF0421208')
print val

I'm trying to get this working. Appreciate if somebody has solution for this

Body:
As far as I tested module to use CRC-32C (nasty mangling ceph objects), the best was crccheck, it does not require SSE4 like the most of its  implementations.

>>> from crccheck.crc import Crc32c
>>> Crc32c().process(b'kwarunek').finalhex()
'aa862086'

http://crccalc.com/ gives the same results.

Edit: calc for hex value

crccheck is able to calc checksum for a hex value, just requires the value to be passed as bytes - method for large integers:

x = int('FFFFFFFFFFFFFFFFFFFF0F0FB01013F2E8FAF0421208', 16)
nbytes, rem = divmod(x.bit_length(), 8)
if rem: nbytes += 1
prepared = x.to_bytes(nbytes, 'big')

Crc32c().process(prepared).finalhex()


问:
How can I find all subsets of a list which have specific items?
I am working on a program which I need to repeatedly make a subset list with 2 items out of a list with n items.

for example let's assume this is the list (The actual list has more items):

list = [50, 100, 250, 500, 750, 1000, 2000]

I need a function which takes list and a number like 2 and then give back a list like this:

[[50,100], [50,250], [50, 500], [50, 750], [50, 1000], [50, 2000], [100, 250],...]

As you can see I don't want items with the same numbers in the answer like [50,100], [100, 50].

I figure this out as the algorithm for finding All the subsets of list:

```<code>from itertools import chain, combinations

   def powerset(iterable):

     xs = list(iterable)
     return list(chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1)))
</code>```

Thanks for the helps.

Body:
I am working on a program which I need to repeatedly make a subset list with 2 items out of a list with n items.

for example let's assume this is the list (The actual list has more items):

list = [50, 100, 250, 500, 750, 1000, 2000]

I need a function which takes list and a number like 2 and then give back a list like this:

[[50,100], [50,250], [50, 500], [50, 750], [50, 1000], [50, 2000], [100, 250],...]

As you can see I don't want items with the same numbers in the answer like [50,100], [100, 50].

I figure this out as the algorithm for finding All the subsets of list:

from itertools import chain, combinations

   def powerset(iterable):

     xs = list(iterable)
     return list(chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1)))

Thanks for the helps.

Body:
This will do the job:

l = [50, 100, 250, 500, 750, 1000, 2000]
from itertools import combinations
res=list(combinations(l,2))
print(res)

This prints

[(50, 100),
 (50, 250),
 (50, 500),
 (50, 750),
 (50, 1000),
 (50, 2000),
 (100, 250),
 (100, 500),
 (100, 750),
 (100, 1000),
 (100, 2000),
 (250, 500),
 (250, 750),
 (250, 1000),
 (250, 2000),
 (500, 750),
 (500, 1000),
 (500, 2000),
 (750, 1000),
 (750, 2000),
 (1000, 2000)]


问:
Connect to MySQL Database on Local Network
I actually thought I could do this until I tried. I installed MySQL server on one PC in the Local network IP Address (192.168.1.4) and now I am trying to access it from another PC in the same network (192.168.1.5) but I am unable:

```<code>C:\Users\DOMICO>mysql -u domico -h 192.168.1.4 -p
Enter password: **********
ERROR 1045 (28000): Access denied for user 'domico'@'DOMICO-PC' (using password:
 YES)
</code>```

Surprisingly DOMICO-PC is the PC I am trying to connect from. Why is it not connecting to the given host but trying to connect to Local machine?

答:
creata a new user by mysql server
and give it privileges you can do it by command and by using any server e.g by using workbench</p>

Body:
I actually thought I could do this until I tried. I installed MySQL server on one PC in the Local network IP Address (192.168.1.4) and now I am trying to access it from another PC in the same network (192.168.1.5) but I am unable:

C:\Users\DOMICO>mysql -u domico -h 192.168.1.4 -p
Enter password: **********
ERROR 1045 (28000): Access denied for user 'domico'@'DOMICO-PC' (using password:
 YES)

Surprisingly DOMICO-PC is the PC I am trying to connect from. Why is it not connecting to the given host but trying to connect to Local machine?