问:
Local Storage not Defined
I'm trying to use localstorage in javascript to save data between executions. Here is the code using it

```<code>const commando = require('discord.js-commando');
roasts = localStorage.getItem("roasts").split(/\r?\n/);

class RoastMe  extends commando.Command {
    constructor(client){
        super(client, {
            name:'addroast',
            group:'insult',
            memberName:'addroast',
            description:'Add a roast to the !roastme archive'
        });
    }

    async run(message, args){
        if(args.length==0) message.reply("That aint a roast.");
        else{
            roasts.push();
            roasts[roasts.length-1] = args;
            var save = "";
            for(var i = 0; i < roasts.length; i++){
                save += roasts[i] + "\n";
            }

            localStorage.setItem("roasts", save);
        }
    }
}
module.exports = RoastMe;
</code>```

This is the error it produced when i tried to run it

```<code>ReferenceError: localStorage is not defined
at Object.<anonymous>

//location of error
(/home/ubuntu/workspace/commands/insult/addinsult.js:2:1)

at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at /home/ubuntu/workspace/node_modules/require-all/index.js:52:46
at Array.forEach (native)
</code>```

If there's a better way to store data between executions, please let me know. Otherwise, could you explain why this isn't working?
Thanks.

EDIT: The code posted is from addinsult.js

答:
you need to declare it somewhere, like in the top of the js file, specifying it is global:

/* global localStorage, */
```

<p>or, alternatively, use the version tied to window (it is your global object)</p>

<pre class="lang-js prettyprint-override"><code>window.localStorage.setItem("roasts", save);
</code>```

Title: Local Storage not Defined

Body:
I'm trying to use localstorage in javascript to save data between executions. Here is the code using it

const commando = require('discord.js-commando');
roasts = localStorage.getItem("roasts").split(/\r?\n/);

class RoastMe  extends commando.Command {
    constructor(client){
        super(client, {
            name:'addroast',
            group:'insult',
            memberName:'addroast',
            description:'Add a roast to the !roastme archive'
        });
    }

    async run(message, args){
        if(args.length==0) message.reply("That aint a roast.");
        else{
            roasts.push();
            roasts[roasts.length-1] = args;
            var save = "";
            for(var i = 0; i < roasts.length; i++){
                save += roasts[i] + "\n";
            }

            localStorage.setItem("roasts", save);
        }
    }
}
module.exports = RoastMe;

This is the error it produced when i tried to run it

ReferenceError: localStorage is not defined
at Object.<anonymous>

//location of error
(/home/ubuntu/workspace/commands/insult/addinsult.js:2:1)

at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at /home/ubuntu/workspace/node_modules/require-all/index.js:52:46
at Array.forEach (native)

If there's a better way to store data between executions, please let me know. Otherwise, could you explain why this isn't working?
Thanks.

EDIT: The code posted is from addinsult.js

Body:
you need to declare it somewhere, like in the top of the js file, specifying it is global:

/* global localStorage, */

or, alternatively, use the version tied to window (it is your global object)

window.localStorage.setItem("roasts", save);


来源: stackexchange

问:
How to compare two lists in Python using for loop?
I am doing an exercise that ask me the following tasks. I am stack in the third one:

Create two variables called gandalf and saruman and assign them the spell power lists. Create a variable called spells to store the number of spells that the sorcerers cast.

```<code>spells = 10
gandalf = [10, 11, 13, 30, 22, 11, 10, 33, 22, 22]
saruman = [23, 66, 12, 43, 12, 10, 44, 23, 12, 17]
</code>```

Create two variables called gandalf_wins and saruman_wins. Set both of them to 0.
You will use these variables to count the number of clashes each sorcerer wins.

```<code>gandalf_wins=0
saruman_wins=0
</code>```

Using the lists of spells of both sorcerers, update variables gandalf_wins and saruman_wins to count the number of times each sorcerer wins a clash.

My solution is that but is not comparing all the elements of the list, could you help me?

```<code>for spells in saruman, gandalf:
    if gandalf>saruman:
        gandalf_wins += 1
    elif saruman>gandalf:
        saruman_wins += 1

print("Total gandalf wins:", gandalf_wins)
print("Total saruman wins:", saruman_wins)
</code>```

答:
You can make use of zip() to create pairs of the spells, so can easily compare them:

```<code>gandalf_wins=0
saruman_wins=0

gandalf = [10, 11, 13, 30, 22, 11, 10, 33, 22, 22]
saruman = [23, 66, 12, 43, 12, 10, 44, 23, 12, 17]

for spells in zip(saruman, gandalf):
    # iterations look like: [(10, 23), (11, 66), (13, 12)...]
    gandalf_spell_power = spells[0]
    saruman_spell_power = spells[1]

    if gandalf_spell_power>saruman_spell_power:
        gandalf_wins += 1
    elif saruman_spell_power>gandalf_spell_power:
        saruman_wins += 1

print("Total gandalf wins:", gandalf_wins)
print("Total saruman wins:", saruman_wins)
</code>```

Output:

```<code>('Total gandalf wins:', 4)
('Total saruman wins:', 6)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am doing an exercise that ask me the following tasks. I am stack in the third one:

Create two variables called gandalf and saruman and assign them the spell power lists. Create a variable called spells to store the number of spells that the sorcerers cast.

spells = 10
gandalf = [10, 11, 13, 30, 22, 11, 10, 33, 22, 22]
saruman = [23, 66, 12, 43, 12, 10, 44, 23, 12, 17]

Create two variables called gandalf_wins and saruman_wins. Set both of them to 0.
You will use these variables to count the number of clashes each sorcerer wins.

gandalf_wins=0
saruman_wins=0

Using the lists of spells of both sorcerers, update variables gandalf_wins and saruman_wins to count the number of times each sorcerer wins a clash.

My solution is that but is not comparing all the elements of the list, could you help me?

for spells in saruman, gandalf:
    if gandalf>saruman:
        gandalf_wins += 1
    elif saruman>gandalf:
        saruman_wins += 1

print("Total gandalf wins:", gandalf_wins)
print("Total saruman wins:", saruman_wins)

Body:
You can make use of zip() to create pairs of the spells, so can easily compare them:

gandalf_wins=0
saruman_wins=0

gandalf = [10, 11, 13, 30, 22, 11, 10, 33, 22, 22]
saruman = [23, 66, 12, 43, 12, 10, 44, 23, 12, 17]

for spells in zip(saruman, gandalf):
    # iterations look like: [(10, 23), (11, 66), (13, 12)...]
    gandalf_spell_power = spells[0]
    saruman_spell_power = spells[1]

    if gandalf_spell_power>saruman_spell_power:
        gandalf_wins += 1
    elif saruman_spell_power>gandalf_spell_power:
        saruman_wins += 1

print("Total gandalf wins:", gandalf_wins)
print("Total saruman wins:", saruman_wins)

Output:

('Total gandalf wins:', 4)
('Total saruman wins:', 6)


问:
Could not find multidex.jar (com.android.support:multidex:1.0.2)
Could not find multidex.jar (com.android.support:multidex:1.0.2).
Searched in the following locations:
    https://jcenter.bintray.com/com/android/support/multidex/1.0.2/multidex

I have just installed latest version of Android Studio 3.1.3
When i tried to sync my project it shows failed to resolve : multidex

Also i tried https://jcenter.bintray.com/com/android/support/multidex/1.0.2/multidex this link which shows 404 error. Please help

Project Level :

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
apply from: 'buildsystem/dependencies.gradle'

buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
        maven {
            url 'https://maven.google.com'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.frogermcs.androiddevmetrics:androiddevmetrics-plugin:0.5'
        classpath 'com.google.gms:google-services:3.1.2'
        classpath 'io.fabric.tools:gradle:1.25.1'
    }
}

allprojects {
    ext {
        androidApplicationId = 'com.medikoe.connect'
        androidVersionCode = 23
        androidVersionName = "1.7.2"
        testInstrumentationRunner = "android.support.test.runner.AndroidJUnitRunner"
        testApplicationId = 'com.medikoe.test'
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
repositories {
    google()
}
</code>```

App Level :

```<code>apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'com.frogermcs.androiddevmetrics'

configurations {
    devDebugCompile
    devSignedDebugCompile
    devPreReleaseCompile
    devReleaseCompile
    prodDebugCompile
    prodSignedDebugCompile
    prodPreReleaseCompile
    prodReleaseCompile
}

android {
    def globalConfiguration = rootProject.extensions.getByName("ext")

    compileSdkVersion globalConfiguration.getAt("androidCompileSdkVersion")
    buildToolsVersion globalConfiguration.getAt("androidBuildToolsVersion")

    defaultConfig {
        minSdkVersion globalConfiguration.getAt("androidMinSdkVersion")
        targetSdkVersion globalConfiguration.getAt("androidTargetSdkVersion")
        versionCode globalConfiguration.getAt("androidVersionCode")
        applicationId globalConfiguration.getAt("androidApplicationId")
        testInstrumentationRunner globalConfiguration.getAt("testInstrumentationRunner")
        testApplicationId globalConfiguration.getAt("testApplicationId")

        multiDexEnabled true

        vectorDrawables.useSupportLibrary = true
    }

    dexOptions {

        jumboMode true
        javaMaxHeapSize "6g"

    }

    compileOptions {
        targetCompatibility 1.8
        sourceCompatibility 1.8
    }

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

    lintOptions {
        quiet true
        abortOnError false
        ignoreWarnings true
        disable 'InvalidPackage'            //Some libraries have issues with this.
        disable 'OldTargetApi'
        //Lint gives this warning but SDK 20 would be Android L Beta.
        disable 'IconDensities'             //For testing purpose. This is safe to remove.
        disable 'IconMissingDensityFolder'  //For testing purpose. This is safe to remove.
    }

    signingConfigs {
        debug {
            storeFile file('../buildsystem/debug.keystore')
            storePassword 'android'
            keyAlias '********'
            keyPassword '******'
        }

        signedDebug {
            storeFile file('../buildsystem/keystore_medikoe.jks')
            storePassword '*********'
            keyAlias '*********'
            keyPassword '**********'
        }
        preRelease {
            storeFile file('../buildsystem/keystore_medikoe.jks')
            storePassword '**********'
            keyAlias '******'
            keyPassword '********'
        }

        release {
            storeFile file('../buildsystem/keystore_medikoe.jks')
            storePassword '************'
            keyAlias '**********'
            keyPassword '************'
        }
    }

    dataBinding {
        enabled = false
    }

    flavorDimensions "default"

    productFlavors {
        dev {
            // Enable pre-dexing to produce an APK that can be tested on
            // Android 5.0+ without the time-consuming DEX build processes.
            minSdkVersion 19
        }
        prod {
            // The actual minSdkVersion for the production version.
            minSdkVersion globalConfiguration.getAt("androidMinSdkVersion")
        }
    }

    buildTypes {

        debug {
            signingConfig signingConfigs.debug
            applicationIdSuffix ".debug"
            resValue "string", "app_name", "Connect-D"
            buildConfigField "boolean", "PRE_RELEASE", "false"
        }
        signedDebug {
            minifyEnabled true
            zipAlignEnabled true
            shrinkResources true
            debuggable true
            signingConfig signingConfigs.signedDebug
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            applicationIdSuffix ".signeddebug"
            resValue "string", "app_name", "Connect-SD"
            buildConfigField "boolean", "PRE_RELEASE", "false"
        }
        preRelease {
            minifyEnabled true
            zipAlignEnabled true
            shrinkResources true
            debuggable false
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            applicationIdSuffix ".prerelease"
            resValue "string", "app_name", "Connect-PR"
            buildConfigField "boolean", "PRE_RELEASE", "true"
        }
        release {
            minifyEnabled true
            zipAlignEnabled true
            shrinkResources true
            debuggable false
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "Medikoe Connect"
            buildConfigField "boolean", "PRE_RELEASE", "false"
        }
    }

}

dependencies {
    def presentationDependencies = rootProject.ext.presentationDependencies
    def presentationTestDependencies = rootProject.ext.presentationTestDependencies
    def developmentDependencies = rootProject.ext.developmentDependencies

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:support-v4:27+'
    compile project(':Domain')

    devDebugCompile project(path: ':Data')
    devSignedDebugCompile project(path: ':Data')
    devPreReleaseCompile project(path: ':Data')
    devReleaseCompile project(path: ':Data')
    prodDebugCompile project(path: ':Data')
    prodSignedDebugCompile project(path: ':Data')
    prodPreReleaseCompile project(path: ':Data')
    prodReleaseCompile project(path: ':Data')

    devDebugCompile project(path: ':Infrastructure')
    devSignedDebugCompile project(path: ':Infrastructure')
    devPreReleaseCompile project(path: ':Infrastructure')
    devReleaseCompile project(path: ':Infrastructure')
    prodDebugCompile project(path: ':Infrastructure')
    prodSignedDebugCompile project(path: ':Infrastructure')
    prodPreReleaseCompile project(path: ':Infrastructure')
    prodReleaseCompile project(path: ':Infrastructure')

    //compile files('libs/date4j.jar')
    //compile files('libs/commons-collections4-4.1.jar')

    annotationProcessor presentationDependencies.daggerCompiler
    compile presentationDependencies.dagger
    compile presentationDependencies.rxJava
    compile presentationDependencies.rxAndroid
    provided presentationDependencies.javaxAnnotation
    //compile presentationDependencies.autoFactory
    compile presentationDependencies.butterKnife
    annotationProcessor presentationDependencies.butterKnifeCompiler

    compile presentationDependencies.designLibrary
    compile presentationDependencies.recyclerView
    compile presentationDependencies.cardView
    compile presentationDependencies.percent
    compile presentationDependencies.glide
    compile presentationDependencies.glideOkhttp3
    compile presentationDependencies.nineOldAndroids
    //compile presentationDependencies.ahBottomNav
    //compile presentationDependencies.lapismSearch
    //compile presentationDependencies.FragmentNavigator
    compile presentationDependencies.flexibleDivider
    compile presentationDependencies.materialDialogsCore
    compile presentationDependencies.materialFavoriteButton
    compile presentationDependencies.fancyButtons
    compile presentationDependencies.simpleRatingBar
    compile presentationDependencies.circularImageView
    compile presentationDependencies.waveLoadingView
    compile presentationDependencies.googleAutoFactory
    annotationProcessor presentationDependencies.googleAutoFactory
    compile presentationDependencies.playServicesPlaces
    compile presentationDependencies.playServicesLocation
    //compile presentationDependencies.tagGroup
    //compile presentationDependencies.expandableTextView
    //compile presentationDependencies.expandableLayout
    //compile presentationDependencies.touchImageView
    //compile presentationDependencies.sublimePicker
    compile presentationDependencies.rxpermissions
    compile presentationDependencies.rxActivityResult
    compile presentationDependencies.rxBinding
    compile presentationDependencies.rxPaparazzo
    compile presentationDependencies.rxBinding
    compile presentationDependencies.parcelerApi
    annotationProcessor presentationDependencies.parceler
    compile presentationDependencies.guava
    compile presentationDependencies.weekView
    compile presentationDependencies.jodaTime
    compile presentationDependencies.rxPaparazzo
    //compile presentationDependencies.collection
    compile presentationDependencies.RecyclerViewPager
    //compile presentationDependencies.googleAnalytics
    compile presentationDependencies.SpotsProgressDialog
    compile presentationDependencies.CustomActivityOnCrash

    compile presentationDependencies.multiDex
    compile presentationDependencies.SaripaarVersion
    //compile presentationDependencies.RazorPay
    compile presentationDependencies.Timecon
    compile presentationDependencies.ClansFab
    compile presentationDependencies.MPAndroidChart
    compile presentationDependencies.FragNav
    compile presentationDependencies.CircularFillableLoaders
    compile presentationDependencies.AvatarImageView
    compile presentationDependencies.AVLoadingIndicatorView
    compile presentationDependencies.Epoxy
    annotationProcessor presentationDependencies.EpoxyProcessor
    compile presentationDependencies.RelativeTimeTextView
    //compile presentationDependencies.AudioPlayerView
    compile presentationDependencies.EasyVideoPlayer
    compile presentationDependencies.ThreeTenAndroid
    //compile presentationDependencies.Steppers
    //compile presentationDependencies.RxAccountManager
    compile presentationDependencies.MaterialProgressBar
    compile presentationDependencies.FloatingView
//    compile presentationDependencies.HashtagView{
//        //Guava appears to be included explicitly in the list-services.jar
//        //Skip the redundant dependency
//        exclude group: 'com.google.guava'
//    }
    compile('com.github.greenfrvr:hashtag-view:1.3.1@aar') {
        transitive = false
    }

    androidTestCompile presentationTestDependencies.mockito
    androidTestCompile presentationTestDependencies.dexmaker
    androidTestCompile presentationTestDependencies.dexmakerMockito
    androidTestCompile presentationTestDependencies.espresso
    androidTestCompile presentationTestDependencies.testingSupportLib
    androidTestCompile presentationTestDependencies.androidAnnotations
    androidTestCompile presentationTestDependencies.autoFactory
//    androidTestCompile presentationTestDependencies.guava

    //Development
    compile developmentDependencies.leakCanary
    compile developmentDependencies.DebugDatabase
    compile 'com.facebook.stetho:stetho:1.4.1'
    compile 'com.facebook.stetho:stetho-okhttp3:1.4.1'
    compile('com.razorpay:checkout:1.4.4')
    compile 'com.aurelhubert:ahbottomnavigation:2.1.0'
    compile 'com.github.florent37:materialtextfield:1.0.7'
    compile 'com.github.rahatarmanahmed:circularprogressview:2.5.0'
    compile('com.github.ganfra:material-spinner:2.0.0')
    compile 'com.wdullaer:materialdatetimepicker:3.5.0'
    compile 'com.myhexaville:smart-image-picker:1.0'
    compile 'com.github.blikoon:QRCodeScanner:0.1.2'
    compile 'de.hdodenhof:circleimageview:2.2.0'
    compile 'com.github.IntruderShanky:Frisson:2.1.1'
    compile 'com.jsibbold:zoomage:1.1.0'
    compile 'com.github.emrekose26:PinchZoom:-SNAPSHOT'
    compile 'com.ablanco.zoomy:zoomy:1.0.0'
    compile 'xyz.danoz:recyclerviewfastscroller:0.1.3'
    compile 'com.irozon.sneaker:sneaker:1.0.2'
    compile 'com.kyanogen.signatureview:signature-view:1.2'
    compile 'com.getkeepsafe.taptargetview:taptargetview:1.11.0'
    compile 'com.rengwuxian.materialedittext:library:2.1.4'
    implementation 'com.github.takusemba:multisnaprecyclerview:1.3.3'
    compile 'com.github.chahine:pageindicator:0.2.6'
    compile 'com.github.florent37:tutoshowcase:1.0.1'
    implementation 'io.supercharge:shimmerlayout:2.1.0'

    compile 'com.github.yeriomin:play-store-api:0.19'
    compile 'com.squareup.okhttp3:okhttp:3.8.1'

    implementation 'com.github.antonKozyriatskyi:CircularProgressIndicator:1.0.5'}

configurations.all {
    exclude group: 'com.android.support', module: 'support-v13'
}
apply plugin: 'com.google.gms.google-services'
</code>```

答: for any one who encounters this problem nowadays just put google() before any other repositories, both in buildscrript repositories and allprojects respository inside project level build.gradle file</p>

Body:
Could not find multidex.jar (com.android.support:multidex:1.0.2).
Searched in the following locations:
    https://jcenter.bintray.com/com/android/support/multidex/1.0.2/multidex

I have just installed latest version of Android Studio 3.1.3
When i tried to sync my project it shows failed to resolve : multidex

Also i tried https://jcenter.bintray.com/com/android/support/multidex/1.0.2/multidex this link which shows 404 error. Please help

Project Level :

// Top-level build file where you can add configuration options common to all sub-projects/modules.
apply from: 'buildsystem/dependencies.gradle'

buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
        maven {
            url 'https://maven.google.com'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.frogermcs.androiddevmetrics:androiddevmetrics-plugin:0.5'
        classpath 'com.google.gms:google-services:3.1.2'
        classpath 'io.fabric.tools:gradle:1.25.1'
    }
}

allprojects {
    ext {
        androidApplicationId = 'com.medikoe.connect'
        androidVersionCode = 23
        androidVersionName = "1.7.2"
        testInstrumentationRunner = "android.support.test.runner.AndroidJUnitRunner"
        testApplicationId = 'com.medikoe.test'
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
repositories {
    google()
}

App Level :

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'com.frogermcs.androiddevmetrics'

configurations {
    devDebugCompile
    devSignedDebugCompile
    devPreReleaseCompile
    devReleaseCompile
    prodDebugCompile
    prodSignedDebugCompile
    prodPreReleaseCompile
    prodReleaseCompile
}

android {
    def globalConfiguration = rootProject.extensions.getByName("ext")

    compileSdkVersion globalConfiguration.getAt("androidCompileSdkVersion")
    buildToolsVersion globalConfiguration.getAt("androidBuildToolsVersion")

    defaultConfig {
        minSdkVersion globalConfiguration.getAt("androidMinSdkVersion")
        targetSdkVersion globalConfiguration.getAt("androidTargetSdkVersion")
        versionCode globalConfiguration.getAt("androidVersionCode")
        applicationId globalConfiguration.getAt("androidApplicationId")
        testInstrumentationRunner globalConfiguration.getAt("testInstrumentationRunner")
        testApplicationId globalConfiguration.getAt("testApplicationId")

        multiDexEnabled true

        vectorDrawables.useSupportLibrary = true
    }

    dexOptions {

        jumboMode true
        javaMaxHeapSize "6g"

    }

    compileOptions {
        targetCompatibility 1.8
        sourceCompatibility 1.8
    }

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

    lintOptions {
        quiet true
        abortOnError false
        ignoreWarnings true
        disable 'InvalidPackage'            //Some libraries have issues with this.
        disable 'OldTargetApi'
        //Lint gives this warning but SDK 20 would be Android L Beta.
        disable 'IconDensities'             //For testing purpose. This is safe to remove.
        disable 'IconMissingDensityFolder'  //For testing purpose. This is safe to remove.
    }

    signingConfigs {
        debug {
            storeFile file('../buildsystem/debug.keystore')
            storePassword 'android'
            keyAlias '********'
            keyPassword '******'
        }

        signedDebug {
            storeFile file('../buildsystem/keystore_medikoe.jks')
            storePassword '*********'
            keyAlias '*********'
            keyPassword '**********'
        }
        preRelease {
            storeFile file('../buildsystem/keystore_medikoe.jks')
            storePassword '**********'
            keyAlias '******'
            keyPassword '********'
        }

        release {
            storeFile file('../buildsystem/keystore_medikoe.jks')
            storePassword '************'
            keyAlias '**********'
            keyPassword '************'
        }
    }

    dataBinding {
        enabled = false
    }

    flavorDimensions "default"

    productFlavors {
        dev {
            // Enable pre-dexing to produce an APK that can be tested on
            // Android 5.0+ without the time-consuming DEX build processes.
            minSdkVersion 19
        }
        prod {
            // The actual minSdkVersion for the production version.
            minSdkVersion globalConfiguration.getAt("androidMinSdkVersion")
        }
    }

    buildTypes {

        debug {
            signingConfig signingConfigs.debug
            applicationIdSuffix ".debug"
            resValue "string", "app_name", "Connect-D"
            buildConfigField "boolean", "PRE_RELEASE", "false"
        }
        signedDebug {
            minifyEnabled true
            zipAlignEnabled true
            shrinkResources true
            debuggable true
            signingConfig signingConfigs.signedDebug
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            applicationIdSuffix ".signeddebug"
            resValue "string", "app_name", "Connect-SD"
            buildConfigField "boolean", "PRE_RELEASE", "false"
        }
        preRelease {
            minifyEnabled true
            zipAlignEnabled true
            shrinkResources true
            debuggable false
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            applicationIdSuffix ".prerelease"
            resValue "string", "app_name", "Connect-PR"
            buildConfigField "boolean", "PRE_RELEASE", "true"
        }
        release {
            minifyEnabled true
            zipAlignEnabled true
            shrinkResources true
            debuggable false
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "Medikoe Connect"
            buildConfigField "boolean", "PRE_RELEASE", "false"
        }
    }

}

dependencies {
    def presentationDependencies = rootProject.ext.presentationDependencies
    def presentationTestDependencies = rootProject.ext.presentationTestDependencies
    def developmentDependencies = rootProject.ext.developmentDependencies

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:support-v4:27+'
    compile project(':Domain')

    devDebugCompile project(path: ':Data')
    devSignedDebugCompile project(path: ':Data')
    devPreReleaseCompile project(path: ':Data')
    devReleaseCompile project(path: ':Data')
    prodDebugCompile project(path: ':Data')
    prodSignedDebugCompile project(path: ':Data')
    prodPreReleaseCompile project(path: ':Data')
    prodReleaseCompile project(path: ':Data')

    devDebugCompile project(path: ':Infrastructure')
    devSignedDebugCompile project(path: ':Infrastructure')
    devPreReleaseCompile project(path: ':Infrastructure')
    devReleaseCompile project(path: ':Infrastructure')
    prodDebugCompile project(path: ':Infrastructure')
    prodSignedDebugCompile project(path: ':Infrastructure')
    prodPreReleaseCompile project(path: ':Infrastructure')
    prodReleaseCompile project(path: ':Infrastructure')

    //compile files('libs/date4j.jar')
    //compile files('libs/commons-collections4-4.1.jar')

    annotationProcessor presentationDependencies.daggerCompiler
    compile presentationDependencies.dagger
    compile presentationDependencies.rxJava
    compile presentationDependencies.rxAndroid
    provided presentationDependencies.javaxAnnotation
    //compile presentationDependencies.autoFactory
    compile presentationDependencies.butterKnife
    annotationProcessor presentationDependencies.butterKnifeCompiler

    compile presentationDependencies.designLibrary
    compile presentationDependencies.recyclerView
    compile presentationDependencies.cardView
    compile presentationDependencies.percent
    compile presentationDependencies.glide
    compile presentationDependencies.glideOkhttp3
    compile presentationDependencies.nineOldAndroids
    //compile presentationDependencies.ahBottomNav
    //compile presentationDependencies.lapismSearch
    //compile presentationDependencies.FragmentNavigator
    compile presentationDependencies.flexibleDivider
    compile presentationDependencies.materialDialogsCore
    compile presentationDependencies.materialFavoriteButton
    compile presentationDependencies.fancyButtons
    compile presentationDependencies.simpleRatingBar
    compile presentationDependencies.circularImageView
    compile presentationDependencies.waveLoadingView
    compile presentationDependencies.googleAutoFactory
    annotationProcessor presentationDependencies.googleAutoFactory
    compile presentationDependencies.playServicesPlaces
    compile presentationDependencies.playServicesLocation
    //compile presentationDependencies.tagGroup
    //compile presentationDependencies.expandableTextView
    //compile presentationDependencies.expandableLayout
    //compile presentationDependencies.touchImageView
    //compile presentationDependencies.sublimePicker
    compile presentationDependencies.rxpermissions
    compile presentationDependencies.rxActivityResult
    compile presentationDependencies.rxBinding
    compile presentationDependencies.rxPaparazzo
    compile presentationDependencies.rxBinding
    compile presentationDependencies.parcelerApi
    annotationProcessor presentationDependencies.parceler
    compile presentationDependencies.guava
    compile presentationDependencies.weekView
    compile presentationDependencies.jodaTime
    compile presentationDependencies.rxPaparazzo
    //compile presentationDependencies.collection
    compile presentationDependencies.RecyclerViewPager
    //compile presentationDependencies.googleAnalytics
    compile presentationDependencies.SpotsProgressDialog
    compile presentationDependencies.CustomActivityOnCrash

    compile presentationDependencies.multiDex
    compile presentationDependencies.SaripaarVersion
    //compile presentationDependencies.RazorPay
    compile presentationDependencies.Timecon
    compile presentationDependencies.ClansFab
    compile presentationDependencies.MPAndroidChart
    compile presentationDependencies.FragNav
    compile presentationDependencies.CircularFillableLoaders
    compile presentationDependencies.AvatarImageView
    compile presentationDependencies.AVLoadingIndicatorView
    compile presentationDependencies.Epoxy
    annotationProcessor presentationDependencies.EpoxyProcessor
    compile presentationDependencies.RelativeTimeTextView
    //compile presentationDependencies.AudioPlayerView
    compile presentationDependencies.EasyVideoPlayer
    compile presentationDependencies.ThreeTenAndroid
    //compile presentationDependencies.Steppers
    //compile presentationDependencies.RxAccountManager
    compile presentationDependencies.MaterialProgressBar
    compile presentationDependencies.FloatingView
//    compile presentationDependencies.HashtagView{
//        //Guava appears to be included explicitly in the list-services.jar
//        //Skip the redundant dependency
//        exclude group: 'com.google.guava'
//    }
    compile('com.github.greenfrvr:hashtag-view:1.3.1@aar') {
        transitive = false
    }

    androidTestCompile presentationTestDependencies.mockito
    androidTestCompile presentationTestDependencies.dexmaker
    androidTestCompile presentationTestDependencies.dexmakerMockito
    androidTestCompile presentationTestDependencies.espresso
    androidTestCompile presentationTestDependencies.testingSupportLib
    androidTestCompile presentationTestDependencies.androidAnnotations
    androidTestCompile presentationTestDependencies.autoFactory
//    androidTestCompile presentationTestDependencies.guava

    //Development
    compile developmentDependencies.leakCanary
    compile developmentDependencies.DebugDatabase
    compile 'com.facebook.stetho:stetho:1.4.1'
    compile 'com.facebook.stetho:stetho-okhttp3:1.4.1'
    compile('com.razorpay:checkout:1.4.4')
    compile 'com.aurelhubert:ahbottomnavigation:2.1.0'
    compile 'com.github.florent37:materialtextfield:1.0.7'
    compile 'com.github.rahatarmanahmed:circularprogressview:2.5.0'
    compile('com.github.ganfra:material-spinner:2.0.0')
    compile 'com.wdullaer:materialdatetimepicker:3.5.0'
    compile 'com.myhexaville:smart-image-picker:1.0'
    compile 'com.github.blikoon:QRCodeScanner:0.1.2'
    compile 'de.hdodenhof:circleimageview:2.2.0'
    compile 'com.github.IntruderShanky:Frisson:2.1.1'
    compile 'com.jsibbold:zoomage:1.1.0'
    compile 'com.github.emrekose26:PinchZoom:-SNAPSHOT'
    compile 'com.ablanco.zoomy:zoomy:1.0.0'
    compile 'xyz.danoz:recyclerviewfastscroller:0.1.3'
    compile 'com.irozon.sneaker:sneaker:1.0.2'
    compile 'com.kyanogen.signatureview:signature-view:1.2'
    compile 'com.getkeepsafe.taptargetview:taptargetview:1.11.0'
    compile 'com.rengwuxian.materialedittext:library:2.1.4'
    implementation 'com.github.takusemba:multisnaprecyclerview:1.3.3'
    compile 'com.github.chahine:pageindicator:0.2.6'
    compile 'com.github.florent37:tutoshowcase:1.0.1'
    implementation 'io.supercharge:shimmerlayout:2.1.0'

    compile 'com.github.yeriomin:play-store-api:0.19'
    compile 'com.squareup.okhttp3:okhttp:3.8.1'

    implementation 'com.github.antonKozyriatskyi:CircularProgressIndicator:1.0.5'}

configurations.all {
    exclude group: 'com.android.support', module: 'support-v13'
}
apply plugin: 'com.google.gms.google-services'


问:
How to get end time as float in Android
I had a String time format like 08:25 now how can I convert to float time value

```<code>    String guestclosetime = getCurrentTime();
    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");

    timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {

        System.out.println("starttime"+ TestRideFragment.getCurrentTime());
        // convert12to24format(guestclosetime);
        Date date1 = timeFormat.parse("00:20");//run
        Date date2 = timeFormat.parse(guestclosetime);
        //Date date3=timeFormat.parse(idle_time);

        long sum = date1.getTime() + date2.getTime();

        String date3 = timeFormat.format(new Date(sum));
        System.out.println("The sum is "+date3);// 08:28
</code>```

now I need the date3 as float how can I do in android.

see I had a scenario as a driver drops a person at x place here I get the current time like 08:30 AM. and after dropping he needs to reach his destination and he took 20 mins this is in float need to convert as a string and if we add this 2 we need to get the total time as 08:50 now this total time need to save as float

I need like 1.30 = 1.5 like that

答:
java.time and ThreeTenABP

I recommend that you use java.time, the modern Java date and time API, for your time math. You cannot use a Date for an amount of time. Instead use LocalTime for a time of day and Duration for a duration, an amount of time.

```<code>    LocalTime dropOff = LocalTime.of(8, 30);
    System.out.println("Drop-off: " + dropOff);

    Duration timeToDest = Duration.ofMinutes(20);
    LocalTime end = dropOff.plus(timeToDest);
    System.out.println("Time at destination: " + end);
</code>```

Output:

```<code>Drop-off: 08:30
Time at destination: 08:50
</code>```

To convert to a flaot indicating the number of hours since midnight:

```<code>    float hoursSinceMidnight = (float) end.getLong(ChronoField.NANO_OF_DAY)
            / (float) Duration.ofHours(1).toNanos();
    System.out.println("As float: " + hoursSinceMidnight);
</code>```

```<code>As float: 8.833334
</code>```

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.

In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Title: How to get end time as float in Android

Body:
I had a String time format like 08:25 now how can I convert to float time value

    String guestclosetime = getCurrentTime();
    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");

    timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {

        System.out.println("starttime"+ TestRideFragment.getCurrentTime());
        // convert12to24format(guestclosetime);
        Date date1 = timeFormat.parse("00:20");//run
        Date date2 = timeFormat.parse(guestclosetime);
        //Date date3=timeFormat.parse(idle_time);

        long sum = date1.getTime() + date2.getTime();

        String date3 = timeFormat.format(new Date(sum));
        System.out.println("The sum is "+date3);// 08:28

now I need the date3 as float how can I do in android.

see I had a scenario as a driver drops a person at x place here I get the current time like 08:30 AM. and after dropping he needs to reach his destination and he took 20 mins this is in float need to convert as a string and if we add this 2 we need to get the total time as 08:50 now this total time need to save as float

I need like 1.30 = 1.5 like that

Body:
java.time and ThreeTenABP

I recommend that you use java.time, the modern Java date and time API, for your time math. You cannot use a Date for an amount of time. Instead use LocalTime for a time of day and Duration for a duration, an amount of time.

    LocalTime dropOff = LocalTime.of(8, 30);
    System.out.println("Drop-off: " + dropOff);

    Duration timeToDest = Duration.ofMinutes(20);
    LocalTime end = dropOff.plus(timeToDest);
    System.out.println("Time at destination: " + end);

Output:

Drop-off: 08:30
Time at destination: 08:50

To convert to a flaot indicating the number of hours since midnight:

    float hoursSinceMidnight = (float) end.getLong(ChronoField.NANO_OF_DAY)
            / (float) Duration.ofHours(1).toNanos();
    System.out.println("As float: " + hoursSinceMidnight);

As float: 8.833334

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.

In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.


问:
AsyncTask - wait for execution of other Asynctask
I was trying to make a program that will get a data with AsyncTask by HttpURLConnection, but in order to get the datas I need to be logged in, so I need to login and then take the data. In order to do have a good OOP, I mustn't have made similar programs that will do the same things. How can I approach this? This is an example of what I did:</p>

```<code>HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("content-type","application/json");
            httpURLConnection.setRequestProperty("user-agent","armon-api-android-client");

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            bufferedWriter.write(requestParams.toString());
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
.
.
.

</code>```

答:
You can override your onPostExecute function while creating AsyncTasks</p>

```<code>loginAndGetData = new RawRequest(){
            @Override
            protected void onPostExecute(String res){
            //DO YOUR JOB
            RawRequest newTask = new RawRequest();
            newTask.execute("get data params");
}
loginAndGetData.execute("login params");
</code>```

Body:
I was trying to make a program that will get a data with AsyncTask by HttpURLConnection, but in order to get the datas I need to be logged in, so I need to login and then take the data. In order to do have a good OOP, I mustn't have made similar programs that will do the same things. How can I approach this? This is an example of what I did:

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("content-type","application/json");
            httpURLConnection.setRequestProperty("user-agent","armon-api-android-client");

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            bufferedWriter.write(requestParams.toString());
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
.
.
.

Body:
You can override your onPostExecute function while creating AsyncTasks

loginAndGetData = new RawRequest(){
            @Override
            protected void onPostExecute(String res){
            //DO YOUR JOB
            RawRequest newTask = new RawRequest();
            newTask.execute("get data params");
}
loginAndGetData.execute("login params");


问:
Change the fill colour of a font to a gradient
I am trying to use Word VBA to create a custom font gradient fill to change a specific text block to a 'half and half' colour pattern. See the image below.

The two circles on the right (they're both text elements) are currently being filled using VBA to a single solid colour. What I'd like to be able to do is create the pattern in the left circle. This pattern can be quite easily created using the gradients section of the font format window.

The FillFormat methods OneColorGradient, TwoColorGradient and PresetGradient don't seem to have the available options to add gradient stops with specific properties for font fills.

If this is not technically possible, I'm very much open to alternative suggestions.

答: You should find the options you need if you use the VBA object Browser with Word as the library you are searching.


问:
How to define an optional entry point into custom Mac OS X framework / dynamic library?
In Windows there is a DllMain and DLL_PROCESS_ATTACH / DLL_PROCESS_DETACH flags, which allow to initialize / free resources after DLL is attached to a process... So how can I specify an entry point in case of OS X? As always, I can't find anything useful in Apple documentation :(

答:
I think malkia (upvoted) and Bavarious have the right answer, but since I already looked it up: One way to do this is to set your init routine. Look for the "Initialization Routine" in your Xcode build settings for your library. Prefix the function name with an underscore. I.e. if your init routine is called DllMain, enter "_DllMain".

Also, I have previously done some initialization using obj-c++ doing something like this:

```<code>class LibraryInit
{
    public LibraryInit()
    {
        // do some init stuff here
    }
} ;
static LibraryInit sLibraryInit();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think malkia (upvoted) and Bavarious have the right answer, but since I already looked it up: One way to do this is to set your init routine. Look for the "Initialization Routine" in your Xcode build settings for your library. Prefix the function name with an underscore. I.e. if your init routine is called DllMain, enter "_DllMain".

Also, I have previously done some initialization using obj-c++ doing something like this:

class LibraryInit
{
    public LibraryInit()
    {
        // do some init stuff here
    }
} ;
static LibraryInit sLibraryInit();


问:
how to populate a table with json data
i'm working on this calculator and when the user select one of the type a little table should appear to select a type from tha table which should be filled with a json data but doesn't work

this my code

```<code>document.addEventListener("DOMContentLoaded", get_json_data, false);

function get_json_data() {
    var json_url = 'example.json';
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var data = JSON.parse(this.responseText);
            append_json(data);
        }
    }
    xmlhttp.open("POST", json_url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send();
}

function append_json(data) {
    var table = document.getElementById('gable');
    data.forEach(function(object) {
        var tbody = document.createElement('tbody');
        tbody.innerHTML =
            '<tr>' +
            '<td > <input type="radio" value ="' + object.RendementDuPanneau + '" name="choice" class="rad" /> </td>' +
            '<td>' + object.Fournisseur + '</td>' +
            '<td>' + object.Modele + '</td>' +
            '<td>' + object.PuissanceMaximale + '</td>' +
            '<td>' + object.RendementDuPanneau + '</td>' + '</tr>';
        table.appendChild(tbody);
    });
    var elements = document.getElementsByTagName('tr');
    for (var i = 0; i < elements.length; i++) {

        (elements)[i].addEventListener("click", function() {
            const rb = this.querySelector('input[name="choice"]');
            rb.checked = true;

            let selectedValue = rb.value;
            alert(selectedValue);
        });
    }
}
</code>```

json file data look like

```<code>[{"Fournisseur":"Jinko Solar","Modèle":"JKM270PP-60","PuissanceMaximale":270,"RendementDuPanneau":"16,50%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM275PP-60","PuissanceMaximale":275,"RendementDuPanneau":"16,80%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM280PP-60","PuissanceMaximale":280,"RendementDuPanneau":"17,11%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM285PP-60","PuissanceMaximale":285,"RendementDuPanneau":"17,41%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM320PP-72","PuissanceMaximale":320,"RendementDuPanneau":"16,49%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM325PP-72","PuissanceMaximale":325,"RendementDuPanneau":"16,75%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM330PP-72","PuissanceMaximale":330,"RendementDuPanneau":"17,01%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM335PP-72","PuissanceMaximale":335,"RendementDuPanneau":"17,26%"}]
</code>```

this how it looks

this how it should look like

答:
An output of zero from the following indicates there's no element with id gable.

```<code>console.log( $('#gable').length );
</code>```

Please confirm that the table has this id, otherwise add an id attribute, thus:

```<code>id="gable"
</code>```

Title: how to populate a table with json data

Body:
i'm working on this calculator and when the user select one of the type a little table should appear to select a type from tha table which should be filled with a json data but doesn't work

this my code

document.addEventListener("DOMContentLoaded", get_json_data, false);

function get_json_data() {
    var json_url = 'example.json';
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var data = JSON.parse(this.responseText);
            append_json(data);
        }
    }
    xmlhttp.open("POST", json_url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send();
}

function append_json(data) {
    var table = document.getElementById('gable');
    data.forEach(function(object) {
        var tbody = document.createElement('tbody');
        tbody.innerHTML =
            '
' +
            ' <input type="radio" value ="' + object.RendementDuPanneau + '" name="choice" class="rad" /> 	' +
            '' + object.Fournisseur + '	' +
            '' + object.Modele + '	' +
            '' + object.PuissanceMaximale + '	' +
            '' + object.RendementDuPanneau + '	' + '
';
        table.appendChild(tbody);
    });
    var elements = document.getElementsByTagName('tr');
    for (var i = 0; i < elements.length; i++) {

        (elements)[i].addEventListener("click", function() {
            const rb = this.querySelector('input[name="choice"]');
            rb.checked = true;

            let selectedValue = rb.value;
            alert(selectedValue);
        });
    }
}

json file data look like

[{"Fournisseur":"Jinko Solar","Modèle":"JKM270PP-60","PuissanceMaximale":270,"RendementDuPanneau":"16,50%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM275PP-60","PuissanceMaximale":275,"RendementDuPanneau":"16,80%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM280PP-60","PuissanceMaximale":280,"RendementDuPanneau":"17,11%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM285PP-60","PuissanceMaximale":285,"RendementDuPanneau":"17,41%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM320PP-72","PuissanceMaximale":320,"RendementDuPanneau":"16,49%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM325PP-72","PuissanceMaximale":325,"RendementDuPanneau":"16,75%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM330PP-72","PuissanceMaximale":330,"RendementDuPanneau":"17,01%"},{"Fournisseur":"Jinko Solar","Modèle":"JKM335PP-72","PuissanceMaximale":335,"RendementDuPanneau":"17,26%"}]

this how it looks

this how it should look like

Body:
An output of zero from the following indicates there's no element with id gable.

console.log( $('#gable').length );

Please confirm that the table has this id, otherwise add an id attribute, thus:

id="gable"


问:
Made a class of Point in python but I'm not quite sure what i did wrong
```<code>#
class Point:

def __init__(self, x, y):
    self.x = x
    self.y = y

def __add__(self, x, y):
    return self.x + self.y

def __sub__(self, x, y):
    return self.x - self.y

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2

print(p3)
</code>```

<p>OUTPUT:
I get an an output which is looking for the parameter of y but i think i already pass y to it </p>

```<code>Traceback (most recent call last):
  File "C:##################################", line 18, in <module>
    p3 = p1 + p2
TypeError: __add__() missing 1 required positional argument: 'y'
</code>```

答:
The expression p3 = p1 + p2 is in reality executed as:

```<code>p3 = p1.__add__(p2)
</code>```

With your current function signature __add__(self, x, y), the Python interpreter will only receive self (p1), x (p2), but will be missing one argument (y), hence the error:

```<code>__add__() missing 1 required positional argument: 'y'
</code>```

What you need instead, is an __add__ implementation (same goes for sub) which takes self and another point instance as arguments, and returns a new point:

```<code>class Point(object):
    def __add__(self, other: "Point") -> "Point":
        # returns a new point created by adding coordinates
        # from self and the other point
</code>```

Body:
#
class Point:

def __init__(self, x, y):
    self.x = x
    self.y = y

def __add__(self, x, y):
    return self.x + self.y

def __sub__(self, x, y):
    return self.x - self.y

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2

print(p3)

OUTPUT:
I get an an output which is looking for the parameter of y but i think i already pass y to it

Traceback (most recent call last):
  File "C:##################################", line 18, in <module>
    p3 = p1 + p2
TypeError: __add__() missing 1 required positional argument: 'y'

Body:
The expression p3 = p1 + p2 is in reality executed as:

p3 = p1.__add__(p2)

With your current function signature __add__(self, x, y), the Python interpreter will only receive self (p1), x (p2), but will be missing one argument (y), hence the error:

__add__() missing 1 required positional argument: 'y'

What you need instead, is an __add__ implementation (same goes for sub) which takes self and another point instance as arguments, and returns a new point:

class Point(object):
    def __add__(self, other: "Point") -> "Point":
        # returns a new point created by adding coordinates
        # from self and the other point


问:
Recursive map over array using extension method
I have a collection of LayoutElement that I receive from an API.

For simplicity sake, imagine it contains 2 properties -

String or [LayoutElement]

I'd like to iterate over this collection and if the value has children, loop over the children recursively, returning the LayoutElement that contains a String

Essentially I should end up with a [LayoutElement] that contains only the elements that have a String value.

As this will be used in multiple places, I thought I could create an extension on Array where the element is LayoutElement but I am unsure how best to do this in the case of element.children.

import UIKit

struct LayoutElement {
  let children: [LayoutElement]?
  let text: String?
}

let data = [
  LayoutElement(children: nil, text: "First Text Element"),
  LayoutElement(children: [
    LayoutElement(children: nil, text: "Second Text Element"),
    LayoutElement(children: nil, text: "Third Text Element"),
    LayoutElement(children: [
      LayoutElement(children: nil, text: "Fourth Text Element"),
    ], text: nil)
  ], text: nil),
]

extension Array where Element == LayoutElement {
  var asLayout: [LayoutElement] {
    return map { element in
      if let children = element.children {
        // ???
      } else {
        return element
      }
    }
  }
}

let output = data.asLayout

print(output)
```

答:
You should be able to achieve this by capturing your collection in a local array before returning the result

extension Array where Element == LayoutElement {
  var asLayout: [LayoutElement] {
    var flatten: [LayoutElement] = []
    forEach { item in
      if let children = item.children {
        children.asLayout.forEach { child in
          flatten.append(child)
        }
      } else {
        flatten.append(item)
      }
    }

    return flatten
  }
}
```


问:
Typescript definitions of nested function
I am trying to create a type for my (nodejs)controller function like below

```<code>export const registerUser = asyncWrap(async function(req:Request, res:Response, next:NextFunction) {
    res.status(200).json({ success: true});
})
</code>```

and the above code is fine, but I want to create a type so I can stop giving the type for the function params which is kinda redundant

What I've tried

```<code>type NormTyped = (fn:Promise<any>) => (req: Request, res: Response, next: NextFunction) => any;

export const registerUser:NormTyped = asyncWrap(async function(req, res, next) {
    res.status(200).json({ success: true});
})
</code>```

But it gives me errors

```<code>Type '(...args: any) => Promise<any>' is not assignable to type 'NormTyped'.
  Type 'Promise<any>' is not assignable to type '(req: Request<ParamsDictionary, any, any, ParsedQs>,         res: Response<any>, next: NextFunction) => any'.
Type 'Promise<any>' provides no match for the signature '(req: Request<ParamsDictionary, any, any, ParsedQs>, res: Response<any>, next: NextFunction): any'.
</code>```

This is how my asyncWrap looks like(in-case)

```<code>const asyncWrap = (fn: (...args: any) => any) =>
function asyncHandlerWrap(...args: any){
    const fnReturn = fn(...args)
    const next = args[args.length-1]
    return Promise.resolve(fnReturn).catch(next)
}
</code>```

答:
Seem like typescript chooses to display the type of the one that defined in the function itself if provided so I ending up by defining the type directly in the asyncWrap like below</p>

```<code>const asyncWrap = (fn: (req: Request,res: Response,next: NextFunction) => Promise<any>) =>
function asyncHandlerWrap(req: Request,res: Response,next: NextFunction){
    const fnReturn = fn(req,res,next)
    return Promise.resolve(fnReturn).catch(next)
}
</code>```

Body:
I am trying to create a type for my (nodejs)controller function like below

export const registerUser = asyncWrap(async function(req:Request, res:Response, next:NextFunction) {
    res.status(200).json({ success: true});
})

and the above code is fine, but I want to create a type so I can stop giving the type for the function params which is kinda redundant

What I've tried

type NormTyped = (fn:Promise<any>) => (req: Request, res: Response, next: NextFunction) => any;

export const registerUser:NormTyped = asyncWrap(async function(req, res, next) {
    res.status(200).json({ success: true});
})

But it gives me errors

Type '(...args: any) => Promise<any>' is not assignable to type 'NormTyped'.
  Type 'Promise<any>' is not assignable to type '(req: Request<ParamsDictionary, any, any, ParsedQs>,         res: Response<any>, next: NextFunction) => any'.
Type 'Promise<any>' provides no match for the signature '(req: Request<ParamsDictionary, any, any, ParsedQs>, res: Response<any>, next: NextFunction): any'.

This is how my asyncWrap looks like(in-case)

const asyncWrap = (fn: (...args: any) => any) =>
function asyncHandlerWrap(...args: any){
    const fnReturn = fn(...args)
    const next = args[args.length-1]
    return Promise.resolve(fnReturn).catch(next)
}

Body:
Seem like typescript chooses to display the type of the one that defined in the function itself if provided so I ending up by defining the type directly in the asyncWrap like below

const asyncWrap = (fn: (req: Request,res: Response,next: NextFunction) => Promise<any>) =>
function asyncHandlerWrap(req: Request,res: Response,next: NextFunction){
    const fnReturn = fn(req,res,next)
    return Promise.resolve(fnReturn).catch(next)
}


问:
Date Pickers and custom display format
I'm a bit stuck here. My application is a non-mobile database front-end, and I need a date field in my form formatted in 'my own way', that is "20-jan-2020", and an accompanying date picker.

I cannot get the <input "date" /> element to format my date value this way (or can I?)

The picker itself is OK, but I cannot find a reliable way to open it from Javascript (or can I?). The idea was to use a hidden date input, and display the formatted value in a normal text input. Then invoke the picker of the hidden input from a button.

I have been looking for some custom pickers around, but those I find are either designed for mobile (way too big), requires jscript/jquery (which I know nothing about), cannot format the date any better than the built-in one (or is there any?), or overrides the rest of the styling of my font end.

Suggestions welcome.

答:
With doing an input type you need to remember to put it inside the form tags like this,

```<code>   <form action="/action_page.php">
      <label for="birthday">Birthday:</label>
      <input type="date" id="birthday" name="birthday">
      <input type="submit">
   </form>
</code>```

Hope this helped

Title: Date Pickers and custom display format

Body:
With doing an input type you need to remember to put it inside the form tags like this,

   <form action="/action_page.php">
      <label for="birthday">Birthday:</label>
      <input type="date" id="birthday" name="birthday">
      <input type="submit">
   </form>

Hope this helped


问:
array sorting php
I've an array like this

```
Array
(

[0] => Array

        (
            [result] => Array
                (
                    [0] => Array
                        (
                            [type] => ABC
                            [id] => 123232
                            [name] => Apple

                        )

                    [1] => Array
                        (
                            [type] => DEF
                            [id] => 2323232
                            [name] => Banana

                        )

                )

            [title] => Cool
            [rank] => 2
        )

  [1] => Array
        (
            [result] => Array
                (
                    [0] => Array
                        (
                            [type] => ZX
                            [id] => 3223
                            [name] => Danny

                        )

                    [1] => Array
                        (
                            [type] => QWER
                            [id] => 2323232
                            [name] => Cactus

                        )

                )

            [title] => Hot
            [rank] => 1
        )

[3]..
[4]..and son on
```

I would like to sort by rank, is there any quick sort method in PHP to do that?

答: There are multiple ways to sort an array, see : http://php.net/manual/en/array.sorting.php</p>

Title: array sorting php

Body:
I've an array like this

Array
(

[0] => Array

        (
            [result] => Array
                (
                    [0] => Array
                        (
                            [type] => ABC
                            [id] => 123232
                            [name] => Apple

                        )

                    [1] => Array
                        (
                            [type] => DEF
                            [id] => 2323232
                            [name] => Banana

                        )

                )

            [title] => Cool
            [rank] => 2
        )

  [1] => Array
        (
            [result] => Array
                (
                    [0] => Array
                        (
                            [type] => ZX
                            [id] => 3223
                            [name] => Danny

                        )

                    [1] => Array
                        (
                            [type] => QWER
                            [id] => 2323232
                            [name] => Cactus

                        )

                )

            [title] => Hot
            [rank] => 1
        )

[3]..
[4]..and son on

I would like to sort by rank, is there any quick sort method in PHP to do that?


问:
Logical AND operation across multiple lists
I have a dictionary that looks something like:

```<code>d= {'GAAP':[True,True],'L1':[True,False],'L2':[True,True]}
</code>```

I would like to perform a logical AND operation across each of the values in the dictionary and return a LIST of True/False values. Something like:

```<code>for counter in range(0,2):
    print(d['GAAP'][counter] & d['L1'][counter] & d['L2'][counter])
</code>```

My dictionary is fairly large so want to avoid manually typing each of the keys to perform the logical AND.

答:
One way would be to use zip to get all corresponding elements and then to ask if they are all true:

```<code>map(all, zip(*d.values()))
</code>```

Result it: [True, False]

Body:
I have a dictionary that looks something like:

d= {'GAAP':[True,True],'L1':[True,False],'L2':[True,True]}

I would like to perform a logical AND operation across each of the values in the dictionary and return a LIST of True/False values. Something like:

for counter in range(0,2):
    print(d['GAAP'][counter] & d['L1'][counter] & d['L2'][counter])

My dictionary is fairly large so want to avoid manually typing each of the keys to perform the logical AND.

Body:
One way would be to use zip to get all corresponding elements and then to ask if they are all true:

map(all, zip(*d.values()))

Result it: [True, False]


问:
margin-top: auto; not working for a flex child
I'm trying to push the footer, inside a flex, to page end. I'm using margin-top: auto to accomplish the same, but it doesn't work. I also tried align-self and align-items, they don't work as well. I also looked at all the SOs. What am I missing?

Codepen for my problem: https://codepen.io/vivekest/pen/XWmvyKq

Thanks in advance!

答:
the problem is that there is nothing between the footer and the all-content and hence the page-footer was not going down, so the usual way is to make a div block and set it's height to 100vh and it will be useful when you want to add more content between these two or

you can set margin-top:100vh that will bring the page-footer block down.

and yes stating the height is also a great method.


问:
When annotating an application as Eureka server, what is the need to specify its not a client
Out of curiosity throwing this question. If the Springboot application is annotated with
@EnableEurekaServer, what is the need for specifying the below properties in application.properties file.

eureka.client.register-with-eureka=false

eureka.client.fetch-registry=false

Should Eureka be intelligent enough to understand this is a server and not client.

答:
@EnableEurekaServer - we use this annotation to convert our service into a Eureka Registry Server.
By default, Eureka registry also tries to register itself, so you need to disable the Eureka feature for registering the own instance by setting below property.

```<code>eureka.client.register-with-eureka=false
</code>```

If eureka.client.fetchRegistry is true, the client fetches the Eureka server registry at startup and caches it locally.
Refer this for more details-

Body:
@EnableEurekaServer - we use this annotation to convert our service into a Eureka Registry Server.
By default, Eureka registry also tries to register itself, so you need to disable the Eureka feature for registering the own instance by setting below property.

eureka.client.register-with-eureka=false

If eureka.client.fetchRegistry is true, the client fetches the Eureka server registry at startup and caches it locally.
Refer this for more details-


问:
2D array conversion (an integer to a string)
I am writing a game code. The board of this game is 10x10 size. In the beginning, I wrote this board as a two-dimensional integer array. Now I have to replace some places on the board with letters. It will change with letters according to the coordinates entered by the player.</p>

```<code>private static int[][] board = new int[10][10]; //board

StringBuilder sb = new StringBuilder();
    for (int[] array : board) {
        sb.append('\n').append(Arrays.toString(array));
    }
    String new = sb.toString(); //I tried to convert this way

if (new[x][y].equals("r")){
    new[x][y] = "d"; //I'm getting an error in this part.
}
</code>```

答:
I would recommend you not use int as the array data type. Perhaps use a String, and you can use Integer.parseInt(x) to extract an integer from an array entry. If your numbers are single digits, using char would be a better choice.

If you want to do it that way, you'll have to do a lot of String operations and you'll have to store your entire board using a String. You might want to read this post to help you index a String like a 2D array.

Body:
I am writing a game code. The board of this game is 10x10 size. In the beginning, I wrote this board as a two-dimensional integer array. Now I have to replace some places on the board with letters. It will change with letters according to the coordinates entered by the player.

private static int[][] board = new int[10][10]; //board

StringBuilder sb = new StringBuilder();
    for (int[] array : board) {
        sb.append('\n').append(Arrays.toString(array));
    }
    String new = sb.toString(); //I tried to convert this way

if (new[x][y].equals("r")){
    new[x][y] = "d"; //I'm getting an error in this part.
}


问:
Program that will output three integers in descending ordrer
This program is meant to prompt a user to enter three integers, store the integers in three separate variables, and output the three integers in descending order (highest to lowest values).

```<code>import java.util.Scanner;

public class ProgramToo
{
public static void main(String [] args)
{
  Scanner kbd = new Scanner(System.in);

  System.out.println("Enter the first number:");
  int num1 = kbd.nextInt();

  System.out.println("Enter the second number:");
  int num2 = kbd.nextInt();

  System.out.println("Enter the three number:");
  int num3 = kbd.nextInt();

  int result = largeSmall(num1, num2, num3);
  System.out.println(result);
  }
  public static int largeSmall(int one, int two, int three)
  {
  if(one > two && two > three)
  {
     System.out.println(one + " " + two + " " + three);
  }
  else if(two > one && one > three)
  {
     System.out.println(two + " " + one + " " + three);
  }
  else if(three > two && two > one)
  {
     System.out.println(three + " " + two + " " + one);
  }
  else
  {
     System.out.println(one + " " + three + " " + two);
  }
  return largeSmall(one, two, three);
  }
  }
</code>```

When I run this program, it outputs the integers a million times and crashes. Why?

答: int num=0; Scanner kbd = new Scanner(System.in); num = kbd.nextInt(); System.out.println(num); Run this program but enter text instead of an integer. The program should crash and tell you what kind of exception was thrown by the nextInt method. Wrap this code inside a try/catch block where you catch the exception that is thrown. Add a loop so the user must enter the number again if text is entered.</p>

Body:
This program is meant to prompt a user to enter three integers, store the integers in three separate variables, and output the three integers in descending order (highest to lowest values).

import java.util.Scanner;

public class ProgramToo
{
public static void main(String [] args)
{
  Scanner kbd = new Scanner(System.in);

  System.out.println("Enter the first number:");
  int num1 = kbd.nextInt();

  System.out.println("Enter the second number:");
  int num2 = kbd.nextInt();

  System.out.println("Enter the three number:");
  int num3 = kbd.nextInt();

  int result = largeSmall(num1, num2, num3);
  System.out.println(result);
  }
  public static int largeSmall(int one, int two, int three)
  {
  if(one > two && two > three)
  {
     System.out.println(one + " " + two + " " + three);
  }
  else if(two > one && one > three)
  {
     System.out.println(two + " " + one + " " + three);
  }
  else if(three > two && two > one)
  {
     System.out.println(three + " " + two + " " + one);
  }
  else
  {
     System.out.println(one + " " + three + " " + two);
  }
  return largeSmall(one, two, three);
  }
  }

When I run this program, it outputs the integers a million times and crashes. Why?


问:
Basic Javascript Question
I'm messing around with the Head First Javascript book. So my question is why doesn't the if clause in my function turnSad() trigger? UPDATE I've tried this in Chrome and FF4. Also, if I were to comment out the if statement, the function will work.

```<code><script type="text/javascript">

    function turnSad() {
        if (document.getElementById("rockImg").src == "rock_happy.png")
            document.getElementById("rockImg").src = "rock.png";
    }

    function touchRock() {
        var userName = prompt("What is your name?", "Enter your name here");

        if (userName) {
            alert("It is nice to meet you " + userName + ".");
            document.getElementById("rockImg").src = "rock_happy.png";
        }
        setTimeout("turnSad();", 1000);
    }

</script>
<img id="rockImg" src="rock.png" alt="iRock"  style="cursor:pointer"
    onclick="touchRock();" />
</code>```

答:
@Anurag's answer is great, that's the best you can do, getAttribute() is supported by every browser that is around (being buggy in IE 5.5-7 but for getting src it works fine).

I just wanted to add a few things:

Don't use setTimeout()'s string syntax, always pass in a function (you can pass in a closure to run more than one functions), which is considered best practice. The string variation works like eval(), the widely known evil bastard. So your code should look like (same applies to setInterval):

```<code>setTimeout(turnSad, 1000);
</code>```

Othen than using getAttribute(), which is the best approach, you can also write a regex approach. I only add this for fun and broadening the view, please use @Anurag's solution.

```<code>if (document.getElementById("rockImg").src.match(/(^|\/)rock_happy\.png$/i)) {
    document.getElementById("rockImg").src = "rock.png";
}
</code>```

This will try to match in a case-insensitive way, looking for rock_happy.png in the end of the string, having either the beginning of the string or / before it.

jsFiddle Demo

Title: Basic Javascript Question

Body:
@Anurag's answer is great, that's the best you can do, getAttribute() is supported by every browser that is around (being buggy in IE 5.5-7 but for getting src it works fine).

I just wanted to add a few things:

Don't use setTimeout()'s string syntax, always pass in a function (you can pass in a closure to run more than one functions), which is considered best practice. The string variation works like eval(), the widely known evil bastard. So your code should look like (same applies to setInterval):

setTimeout(turnSad, 1000);

Othen than using getAttribute(), which is the best approach, you can also write a regex approach. I only add this for fun and broadening the view, please use @Anurag's solution.

if (document.getElementById("rockImg").src.match(/(^|\/)rock_happy\.png$/i)) {
    document.getElementById("rockImg").src = "rock.png";
}

This will try to match in a case-insensitive way, looking for rock_happy.png in the end of the string, having either the beginning of the string or / before it.

jsFiddle Demo


答:
Have a temporary array to collect all the results:</p>

```<code>extension Array where Element == LayoutElement {
    var asLayout: [LayoutElement] {
        var result = [LayoutElement]()
        forEach {
            if let children = $0.children {
                result.append(contentsOf: children.asLayout)
            } else if $0.text != nil {
                result.append($0)
            }
        }
        return result
    }
}

</code>```

Title: Recursive map over array using extension method

Body:
I have a collection of LayoutElement that I receive from an API.

For simplicity sake, imagine it contains 2 properties -

String or [LayoutElement]

I'd like to iterate over this collection and if the value has children, loop over the children recursively, returning the LayoutElement that contains a String

Essentially I should end up with a [LayoutElement] that contains only the elements that have a String value.

As this will be used in multiple places, I thought I could create an extension on Array where the element is LayoutElement but I am unsure how best to do this in the case of element.children.

import UIKit

struct LayoutElement {
  let children: [LayoutElement]?
  let text: String?
}

let data = [
  LayoutElement(children: nil, text: "First Text Element"),
  LayoutElement(children: [
    LayoutElement(children: nil, text: "Second Text Element"),
    LayoutElement(children: nil, text: "Third Text Element"),
    LayoutElement(children: [
      LayoutElement(children: nil, text: "Fourth Text Element"),
    ], text: nil)
  ], text: nil),
]

extension Array where Element == LayoutElement {
  var asLayout: [LayoutElement] {
    return map { element in
      if let children = element.children {
        // ???
      } else {
        return element
      }
    }
  }
}

let output = data.asLayout

print(output)

Body:
Have a temporary array to collect all the results:

extension Array where Element == LayoutElement {
    var asLayout: [LayoutElement] {
        var result = [LayoutElement]()
        forEach {
            if let children = $0.children {
                result.append(contentsOf: children.asLayout)
            } else if $0.text != nil {
                result.append($0)
            }
        }
        return result
    }
}


问:
weird variable hoisting in javascript
so we know that variables declared with the var keyword are hoisted and if we try to access their value before they have been initialized we get undefined. However, In the code below logging the name variable logs the function and not undefined why ?

console.log(name);
console.log(lol);

var name = function(args = "Hello World"){
    console.log(args)
}

var lol = function(args = "Hello world") {
    console.log(args)
}
```

<p>the output is </p>

```function(args = "Hello World"){
    console.log(args)
}
```

<p>and</p>

```main.js:57 undefined
```

why isnt name variable undefined ?

答:
I think you should logging like that why you confused.

console.log(name);
console.log(lol);

var name = function(args = "Hello World"){
    console.log(args)
}

var lol = function(args = "Hello world") {
    console.log(args)
}

console.log(name);
console.log(lol);```

Title: weird variable hoisting in javascript

Body:
so we know that variables declared with the var keyword are hoisted and if we try to access their value before they have been initialized we get undefined. However, In the code below logging the name variable logs the function and not undefined why ?

console.log(name);
console.log(lol);

var name = function(args = "Hello World"){
    console.log(args)
}

var lol = function(args = "Hello world") {
    console.log(args)
}

the output is

function(args = "Hello World"){
    console.log(args)
}

and

main.js:57 undefined

why isnt name variable undefined ?


问:
Cannot Import Google Fonts in Gatsby SCSS
** EDIT **

Nah, the problem is the css2 api who use wght@500:
so i must escape the @ and : with %40 and %3B and now its fixed.
but someone told me its better to use gatsby plugin typeface, and it slightly improved my site performance. Thanks all

**

I'm new to GatsbyJS and I'm trying to modify TaniaRascia's static blog template, the system works fine. But I cannot import google fonts in my SCSS file. I see this error on her site too. Any solutions?

The Code :

```<code>/*! Primitive

by Tania Rascia */

@import url(https://fonts.googleapis.com/css2?family=Inter:wght@500;600;700&display=swap);

@import url(https://fonts.googleapis.com/css?family=Roboto+Mono);

// Configuration

@import 'base/variables';

@import 'base/mixins';
</code>```

The Error in Console :

```<code>Refused to apply style from '``<SITE_URL>/url``(https://fonts.googleapis.com/css2?family=Inter:wght@500' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
</code>```

Instead of importing the css from url, it seems the browser read it as a link from my local directory.

I've tried solutions from the Internet such as :

```<code> - #import 'https://....' < this one produces error when i ran gatsby build
 - @import url("https://...'
 - @import url('https://...'
</code>```

And 2 of them produces same error "Refused to apply style from...."

Any solutions? Thanks

答:
Can you try using this meta:

<meta http-equiv="Content-Security-Policy" content="style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com;">
```

Either using react-helmet or via the html.js Gatsby template. Instructions on how to customize html.js here

Body:
** EDIT **

Nah, the problem is the css2 api who use wght@500:
so i must escape the @ and : with %40 and %3B and now its fixed.
but someone told me its better to use gatsby plugin typeface, and it slightly improved my site performance. Thanks all

**

I'm new to GatsbyJS and I'm trying to modify TaniaRascia's static blog template, the system works fine. But I cannot import google fonts in my SCSS file. I see this error on her site too. Any solutions?

The Code :

/*! Primitive

by Tania Rascia */

@import url(https://fonts.googleapis.com/css2?family=Inter:wght@500;600;700&display=swap);

@import url(https://fonts.googleapis.com/css?family=Roboto+Mono);

// Configuration

@import 'base/variables';

@import 'base/mixins';

The Error in Console :

Refused to apply style from '``<SITE_URL>/url``(https://fonts.googleapis.com/css2?family=Inter:wght@500' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Instead of importing the css from url, it seems the browser read it as a link from my local directory.

I've tried solutions from the Internet such as :

 - #import 'https://....' < this one produces error when i ran gatsby build
 - @import url("https://...'
 - @import url('https://...'

And 2 of them produces same error "Refused to apply style from...."

Any solutions? Thanks

Body:
Can you try using this meta:

<meta http-equiv="Content-Security-Policy" content="style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com;">

Either using react-helmet or via the html.js Gatsby template. Instructions on how to customize html.js here


问:
Open an app (iOS/Android) via JavaScript, with a fallback redirect to App/Play store (2016 edition)
Given: Website, iOS and Android applications, registered urlscheme "myapp://".

Goal: on the website have a link shown to iOS/Android devices with app installed. Clicking on that link should open the app and invoke specific logic (handled by the app, essentially like "universal links" from apple, but without shadowing website links).

Due to security constraints detecting if an app is installed is troublesome without webview cookie magic. Given that, what would be the best approach to try and open an app via JavaScript, and invoke a fallback redirect if that fails?

Solution from this thread: Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps? doesn't work with iOS10. Not sure about Android.

答:
So the way it works on ios without always opening the store when the app is installed is to do something like this:    </p>

```<code>function isIOS() {
    const iDevices = [
        'iPad Simulator',
        'iPhone Simulator',
        'iPod Simulator',
        'iPad',
        'iPhone',
        'iPod'
    ];

    if (navigator.platform) {
        while (iDevices.length) {
            if (navigator.platform === iDevices.pop()) {
                return true;
            }
        }
    }

    return false;
}

let openedApp = false;

function openAppOrStore() {
    setTimeout(function () {
        if (!openedApp) {
            window.location = "https://apps.apple.com/us/app/petleo/id1462882016";
        }
    }, 25);
    const parts = window.location.href.split('/');
    const consultationId = parts[parts.length - 2];
    const iosLink = "petleo://consultations/" + consultationId;
    try {
        window.location = iosLink;
        if (window.location.href.indexOf("petleo://") !== -1) {
            openedApp = true;
        }
    } catch (e) {
    }
}

setTimeout(function () {
    if (window.location.href.indexOf('consultation') !== -1) {
        if (isIOS()) {
            openAppOrStore();
        }
    }
}, 25);
</code>```

Body:
So the way it works on ios without always opening the store when the app is installed is to do something like this:

function isIOS() {
    const iDevices = [
        'iPad Simulator',
        'iPhone Simulator',
        'iPod Simulator',
        'iPad',
        'iPhone',
        'iPod'
    ];

    if (navigator.platform) {
        while (iDevices.length) {
            if (navigator.platform === iDevices.pop()) {
                return true;
            }
        }
    }

    return false;
}

let openedApp = false;

function openAppOrStore() {
    setTimeout(function () {
        if (!openedApp) {
            window.location = "https://apps.apple.com/us/app/petleo/id1462882016";
        }
    }, 25);
    const parts = window.location.href.split('/');
    const consultationId = parts[parts.length - 2];
    const iosLink = "petleo://consultations/" + consultationId;
    try {
        window.location = iosLink;
        if (window.location.href.indexOf("petleo://") !== -1) {
            openedApp = true;
        }
    } catch (e) {
    }
}

setTimeout(function () {
    if (window.location.href.indexOf('consultation') !== -1) {
        if (isIOS()) {
            openAppOrStore();
        }
    }
}, 25);


问:
Adding a new label where clicked SWIFT
I would like to write a simple swift code for a MacOS app which add a new label wherever the user perform a mouse click in a window.

This code compiles but make the app crash:

```<code>@IBOutlet var here2 = [NSTextField]()
var count: Int = 0
func getCoordinates(){
        NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown]) {
        if self.location.x < 700 && self.location.y<750 {
            self.here2.append(NSTextField.init())
            self.here2[self.count].frame.origin = CGPoint(x: self.location.x, y: self.location.y)
            self.here2[self.count].stringValue = String(self.count)
            print("count is: " + String(self.here2.count))
            self.count+=1
        }
        return $0
    }

</code>```

答:
You can't connect and array of NSTextField in a storyboard. In my opinion it's a bug in Xcode, IB shouldn't make the connection. It's also a bug in AppKit, I tried this and got this weird error:

Failed to set (contentViewController) user defined inspected property on (NSWindow): [<__NSTimeZone 0x6040000a2280> valueForUndefinedKey:]: this class is not key value coding-compliant for the key identifier.

Solution: remove the connection in IB and change

```<code>@IBOutlet var here2 = [NSTextField]()
</code>```

to

```<code>var here2 = [NSTextField]()
@IBOutlet weak var here2TextField: NSTextField!
</code>```

Connect here2TextField in IB and append here2TextField to here2 in viewDidLoad().

Title: Adding a new label where clicked SWIFT

Body:
I would like to write a simple swift code for a MacOS app which add a new label wherever the user perform a mouse click in a window.

This code compiles but make the app crash:

@IBOutlet var here2 = [NSTextField]()
var count: Int = 0
func getCoordinates(){
        NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown]) {
        if self.location.x < 700 && self.location.y<750 {
            self.here2.append(NSTextField.init())
            self.here2[self.count].frame.origin = CGPoint(x: self.location.x, y: self.location.y)
            self.here2[self.count].stringValue = String(self.count)
            print("count is: " + String(self.here2.count))
            self.count+=1
        }
        return $0
    }

Body:
You can't connect and array of NSTextField in a storyboard. In my opinion it's a bug in Xcode, IB shouldn't make the connection. It's also a bug in AppKit, I tried this and got this weird error:

Failed to set (contentViewController) user defined inspected property on (NSWindow): [<__NSTimeZone 0x6040000a2280> valueForUndefinedKey:]: this class is not key value coding-compliant for the key identifier.

Solution: remove the connection in IB and change

@IBOutlet var here2 = [NSTextField]()

to

var here2 = [NSTextField]()
@IBOutlet weak var here2TextField: NSTextField!

Connect here2TextField in IB and append here2TextField to here2 in viewDidLoad().


答:
You could use usort().

The example below requires >= PHP 5.3. If you don't have this version, just pass a reference to the callback.

```<code>usort($array, function($a, $b) {
   return $a['rank'] - $b['rank'];
}
</code>```

Title: array sorting php

Body:
You could use usort().

The example below requires >= PHP 5.3. If you don't have this version, just pass a reference to the callback.

usort($array, function($a, $b) {
   return $a['rank'] - $b['rank'];
}


问:
How to select multiple parents categories with multiple subcategories in 1 post?
I am creating a blog by Django framework.

In the blog, I have a Post function which I can assign multiple parents categories in that post in the admin page.

However Im struggling to create a model that can assign multiple subcategories under the multiple parents categories in admin page.

for example, I have 2 parents categories(Tom & Mike).

and I have different subcategories under those parents categories.

Tom(parents category)

|- This is nice (to Post A)(Subcategory)

|- This is not nice (to Post B)(Subcategory)

Mike(parents category)

|- This is cool (to Post A)(Subcategory)

|- This is not cool (to Post B)(Subcategory)

When the user selects the Parents category e.g. Tom, the user can see subcategories comments to each Post A and B.

e.g.

Localhost:8000/TOM

Show the post and comments related Category TOM

Post A - This is cool

Post B - This is not cool

the below is the model I created for the Post and Parents category.

Can anyone advise me how to create a Subcategory model what I want?

and am sorry in advance if my question was difficult to understand for you.

```<code>from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=20)
    description = models.TextField(default="")
    def __str__(self):
        return self.name

class Post(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
    categories = models.ManyToManyField("Category", related_name="posts")
    url = models.CharField(max_length=200, unique=True, default='')
    image = models.ImageField(upload_to='images/', null=True)
    def __str__(self):
        return self.title
</code>```

答:
Try designing your model something like this:

```<code>class Category(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField()
    parent = models.ForeignKey('self',blank=True, null=True ,related_name='children')

    class Meta:
        unique_together = ('slug', 'parent',) #enforcing that there can not be two categories under a parent with same slug
        verbose_name_plural = "categories"
</code>```

Check out the details of implementing category & sub-category here

Reference & Credits : https://djangopy.org/how-to/how-to-implement-categories-in-django/

Body:
I am creating a blog by Django framework.

In the blog, I have a Post function which I can assign multiple parents categories in that post in the admin page.

However Im struggling to create a model that can assign multiple subcategories under the multiple parents categories in admin page.

for example, I have 2 parents categories(Tom & Mike).

and I have different subcategories under those parents categories.

Tom(parents category)

|- This is nice (to Post A)(Subcategory)

|- This is not nice (to Post B)(Subcategory)

Mike(parents category)

|- This is cool (to Post A)(Subcategory)

|- This is not cool (to Post B)(Subcategory)

When the user selects the Parents category e.g. Tom, the user can see subcategories comments to each Post A and B.

e.g.

Localhost:8000/TOM

Show the post and comments related Category TOM

Post A - This is cool

Post B - This is not cool

the below is the model I created for the Post and Parents category.

Can anyone advise me how to create a Subcategory model what I want?

and am sorry in advance if my question was difficult to understand for you.

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=20)
    description = models.TextField(default="")
    def __str__(self):
        return self.name

class Post(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
    categories = models.ManyToManyField("Category", related_name="posts")
    url = models.CharField(max_length=200, unique=True, default='')
    image = models.ImageField(upload_to='images/', null=True)
    def __str__(self):
        return self.title

Body:
Try designing your model something like this:

class Category(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField()
    parent = models.ForeignKey('self',blank=True, null=True ,related_name='children')

    class Meta:
        unique_together = ('slug', 'parent',) #enforcing that there can not be two categories under a parent with same slug
        verbose_name_plural = "categories"

Check out the details of implementing category & sub-category here

Reference & Credits : https://djangopy.org/how-to/how-to-implement-categories-in-django/


问:
how to make windows file explorer to show files top to down in tiles rather than left to right`
tile1 tile2 tile3 tile4

to

tile1

tile2

tile3

tile4

from
==>to

it would look nice if the tiles or other formats look top to down rather than left to right.

答:
you can change it directly from the bottom bar as i show you in the first image
or you can click on top bar on view then choose ditals as i show you in second image