问:
Error inflating class material.bottomnavigation.BottomNavigationView
I am trying to implement a BottomNavigationView, I am aware that there are multiple answers about the same question however none of them seems to work for me.

I followed this doc

In preview mode, I get this error

```<code>IllegalArgumentException: Unknown color
</code>```

When I run TestActivity I get an error inflating the class

Drawables are inside res/drawable

Menu is inside res/menu

For what I was able to understand from answers in different posts this is a resources issue.

I tried to delete every resource call, but even with just the width and height defined I still get the error.

TestActivity

```<code>import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import pt.myapp.android.myapp.R;

public class TestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
    }
}
</code>```

test.xml

```<code><FrameLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     mlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent">

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:layout_gravity="bottom"
    android:background="@color/colorPrimary"
    app:itemIconTint="@drawable/bottom_navigation_colors"
    app:itemTextColor="@drawable/bottom_navigation_colors"
    app:menu="@menu/bottom_navigation_menu" />

</FrameLayout>
</code>```

bottom_navigation_menu

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

        <item
            android:id="@+id/nav_first_page"
            android:icon="@drawable/page"
            android:title="page"
            app:showAsAction="always" />

</menu>
</code>```

bottom_navigation_colors.xml

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="true"
        android:color="#ffffff" />
    <item
        android:state_checked="false"
        android:color="#ffffff" />
</selector>
</code>```

gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-kapt'

android {
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }
    compileSdkVersion 28
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "pt.myapp.android.myapp"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 42
        versionName "v1.5.0d"
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true
    }

    signingConfigs {
        config {
            Properties properties = new Properties()
        properties.load(project.rootProject.file('local.properties').newDataInputStream())
            storeFile file(properties.getProperty('storeFile'))
            keyAlias properties.getProperty('keyAlias')
            storePassword properties.getProperty('storePassword')
            keyPassword properties.getProperty('keyPassword')
        }
    }

    dataBinding {
        enabled = true
    }

    buildTypes {
        release {
            signingConfig signingConfigs.config
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            proguardFile "proguard-butterknife-7.pro"
            proguardFile "proguard-google-play-services.pro"
            proguardFile "proguard-support-v7-appcompat.pro"
            proguardFile "proguard-joda.pro"
        }
        debug {
            debuggable true
            signingConfig signingConfigs.config
            applicationIdSuffix ".debug"
        }
    }
    compileOptions {
        targetCompatibility 1.8
        sourceCompatibility 1.8
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation project(':FloatingView')

    implementation 'de.hdodenhof:circleimageview:2.2.0'

    /* Multidex */
    implementation 'androidx.multidex:multidex:2.0.1'

    implementation 'com.github.lzyzsd:circleprogress:1.2.1'

    /* FACEBOOK  */
    implementation 'com.facebook.android:facebook-android-sdk:4.35.0'
    implementation 'com.facebook.android:facebook-login:4.35'

    implementation 'com.github.wrdlbrnft:sorted-list-adapter:0.2.0.1'
    implementation 'com.github.chrisbanes:PhotoView:1.3.0'
    implementation 'com.scottyab:aescrypt:0.0.1'
    implementation 'com.github.traex.rippleeffect:library:1.3'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.miguelcatalan:materialsearchview:1.4.0'
    implementation 'com.github.rahatarmanahmed:circularprogressview:2.5.0'
    implementation 'com.jakewharton:butterknife:8.8.1'
    implementation 'im.dacer:AndroidCharts:1.0.4'
    implementation 'com.github.greenfrvr:rubber-loader:1.1.2@aar'

    /* SUPPORT LIBRARY */
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation "androidx.recyclerview:recyclerview:1.0.0"
    implementation "androidx.legacy:legacy-support-v4:1.0.0"
    implementation "androidx.preference:preference:1.0.0"
    implementation "androidx.annotation:annotation:1.0.1"
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "androidx.palette:palette:1.0.0"

    /* FIREBASE */
    implementation 'com.crashlytics.sdk.android:crashlytics:2.9.9'
    implementation 'com.google.firebase:firebase-core:16.0.7'

    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation "com.google.firebase:firebase-appindexing:17.1.0"
    implementation "com.google.firebase:firebase-auth:16.1.0"
    implementation "com.google.firebase:firebase-storage:16.0.5"
    implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
    implementation 'com.firebaseui:firebase-ui-auth:3.3.1'
    implementation "com.google.firebase:firebase-ads:17.1.3"
    implementation "com.google.firebase:firebase-config:16.3.0"
    implementation "com.google.firebase:firebase-perf:16.2.3"
    implementation "com.google.firebase:firebase-database:16.0.6"
    implementation "com.google.firebase:firebase-appindexing:17.1.0"
    implementation 'com.firebaseui:firebase-ui-storage:0.6.0'

    // Room components
    implementation "androidx.room:room-runtime:2.1.0-alpha04"
    annotationProcessor "androidx.room:room-compiler:2.1.0-alpha04"
    androidTestImplementation "androidx.room:room-testing:2.1.0-alpha04"

    // Lifecycle components
    implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0"

    /* Retrofit */
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:retrofit-converters:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

    implementation 'joda-time:joda-time:2.9.9'
    testImplementation 'junit:junit:4.12'

    implementation 'com.jakewharton:butterknife:9.0.0-SNAPSHOT'
    annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0-SNAPSHOT'

    debugImplementation 'com.sothree.slidinguppanel:library:3.3.1'

    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    kapt "com.android.databinding:compiler:3.3.0-alpha08"

}

kapt {
    generateStubs = true
}

apply plugin: 'com.google.gms.google-services'
repositories {
    mavenCentral()
}
</code>```

Error

```<code>Process: pt.myapp.android.myapp.debug, PID: 13653
java.lang.RuntimeException: Unable to start activity ComponentInfo{pt.myapp.android.myapp.debug/pt.myapp.android.myapp.ui.activities.TestActivity}: android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
 Caused by: android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
 Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Constructor.newInstance0(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
    at android.view.LayoutInflater.createView(LayoutInflater.java:647)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
    at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at pt.myapp.android.myapp.ui.activities.TestActivity.onCreate(TestActivity.java:13)
    at android.app.Activity.performCreate(Activity.java:7136)
    at android.app.Activity.performCreate(Activity.java:7127)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
 Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
    at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:216)
    at android.content.res.Resources.getColorStateList(Resources.java:1031)
2019-02-10 14:47:12.350 13653-13653/pt.myapp.android.myapp.debug E/AndroidRuntime:     at android.content.Context.getColorStateList(Context.java:642)
    at androidx.appcompat.content.res.AppCompatResources.getColorStateList(AppCompatResources.java:67)
    at com.google.android.material.bottomnavigation.BottomNavigationMenuView.createDefaultColorStateList(BottomNavigationMenuView.java:467)
    at com.google.android.material.bottomnavigation.BottomNavigationMenuView.<init>(BottomNavigationMenuView.java:101)
    at com.google.android.material.bottomnavigation.BottomNavigationMenuView.<init>(BottomNavigationMenuView.java:86)
    at com.google.android.material.bottomnavigation.BottomNavigationView.<init>(BottomNavigationView.java:123)
    at com.google.android.material.bottomnavigation.BottomNavigationView.<init>(BottomNavigationView.java:114)
        ... 28 more
</code>```

答:
In BottomNavigationView inflating error can occur due to XML it can be either in @layout, @drawable, @style or @color folder.

<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_gravity="bottom"
android:background="@color/colorPrimary"
app:itemIconTint="@drawable/bottom_navigation_colors"
app:itemTextColor="@drawable/bottom_navigation_colors"
app:menu="@menu/bottom_navigation_menu" />
```

This line may be causing inflating error:
app:menu="@menu/bottom_navigation_menu"

I resolved it by keeping my drawable files in both the folder:

drawable

drawable-v24

Body:
I am trying to implement a BottomNavigationView, I am aware that there are multiple answers about the same question however none of them seems to work for me.

I followed this doc

In preview mode, I get this error

IllegalArgumentException: Unknown color

When I run TestActivity I get an error inflating the class

Drawables are inside res/drawable

Menu is inside res/menu

For what I was able to understand from answers in different posts this is a resources issue.

I tried to delete every resource call, but even with just the width and height defined I still get the error.

TestActivity

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import pt.myapp.android.myapp.R;

public class TestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
    }
}

test.xml

<FrameLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     mlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent">

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:layout_gravity="bottom"
    android:background="@color/colorPrimary"
    app:itemIconTint="@drawable/bottom_navigation_colors"
    app:itemTextColor="@drawable/bottom_navigation_colors"
    app:menu="@menu/bottom_navigation_menu" />

</FrameLayout>

bottom_navigation_menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

        <item
            android:id="@+id/nav_first_page"
            android:icon="@drawable/page"
            android:title="page"
            app:showAsAction="always" />

</menu>

bottom_navigation_colors.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="true"
        android:color="#ffffff" />
    <item
        android:state_checked="false"
        android:color="#ffffff" />
</selector>

gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-kapt'

android {
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }
    compileSdkVersion 28
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "pt.myapp.android.myapp"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 42
        versionName "v1.5.0d"
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true
    }

    signingConfigs {
        config {
            Properties properties = new Properties()
        properties.load(project.rootProject.file('local.properties').newDataInputStream())
            storeFile file(properties.getProperty('storeFile'))
            keyAlias properties.getProperty('keyAlias')
            storePassword properties.getProperty('storePassword')
            keyPassword properties.getProperty('keyPassword')
        }
    }

    dataBinding {
        enabled = true
    }

    buildTypes {
        release {
            signingConfig signingConfigs.config
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            proguardFile "proguard-butterknife-7.pro"
            proguardFile "proguard-google-play-services.pro"
            proguardFile "proguard-support-v7-appcompat.pro"
            proguardFile "proguard-joda.pro"
        }
        debug {
            debuggable true
            signingConfig signingConfigs.config
            applicationIdSuffix ".debug"
        }
    }
    compileOptions {
        targetCompatibility 1.8
        sourceCompatibility 1.8
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation project(':FloatingView')

    implementation 'de.hdodenhof:circleimageview:2.2.0'

    /* Multidex */
    implementation 'androidx.multidex:multidex:2.0.1'

    implementation 'com.github.lzyzsd:circleprogress:1.2.1'

    /* FACEBOOK  */
    implementation 'com.facebook.android:facebook-android-sdk:4.35.0'
    implementation 'com.facebook.android:facebook-login:4.35'

    implementation 'com.github.wrdlbrnft:sorted-list-adapter:0.2.0.1'
    implementation 'com.github.chrisbanes:PhotoView:1.3.0'
    implementation 'com.scottyab:aescrypt:0.0.1'
    implementation 'com.github.traex.rippleeffect:library:1.3'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.miguelcatalan:materialsearchview:1.4.0'
    implementation 'com.github.rahatarmanahmed:circularprogressview:2.5.0'
    implementation 'com.jakewharton:butterknife:8.8.1'
    implementation 'im.dacer:AndroidCharts:1.0.4'
    implementation 'com.github.greenfrvr:rubber-loader:1.1.2@aar'

    /* SUPPORT LIBRARY */
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation "androidx.recyclerview:recyclerview:1.0.0"
    implementation "androidx.legacy:legacy-support-v4:1.0.0"
    implementation "androidx.preference:preference:1.0.0"
    implementation "androidx.annotation:annotation:1.0.1"
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "androidx.palette:palette:1.0.0"

    /* FIREBASE */
    implementation 'com.crashlytics.sdk.android:crashlytics:2.9.9'
    implementation 'com.google.firebase:firebase-core:16.0.7'

    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation "com.google.firebase:firebase-appindexing:17.1.0"
    implementation "com.google.firebase:firebase-auth:16.1.0"
    implementation "com.google.firebase:firebase-storage:16.0.5"
    implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
    implementation 'com.firebaseui:firebase-ui-auth:3.3.1'
    implementation "com.google.firebase:firebase-ads:17.1.3"
    implementation "com.google.firebase:firebase-config:16.3.0"
    implementation "com.google.firebase:firebase-perf:16.2.3"
    implementation "com.google.firebase:firebase-database:16.0.6"
    implementation "com.google.firebase:firebase-appindexing:17.1.0"
    implementation 'com.firebaseui:firebase-ui-storage:0.6.0'

    // Room components
    implementation "androidx.room:room-runtime:2.1.0-alpha04"
    annotationProcessor "androidx.room:room-compiler:2.1.0-alpha04"
    androidTestImplementation "androidx.room:room-testing:2.1.0-alpha04"

    // Lifecycle components
    implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0"

    /* Retrofit */
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:retrofit-converters:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

    implementation 'joda-time:joda-time:2.9.9'
    testImplementation 'junit:junit:4.12'

    implementation 'com.jakewharton:butterknife:9.0.0-SNAPSHOT'
    annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0-SNAPSHOT'

    debugImplementation 'com.sothree.slidinguppanel:library:3.3.1'

    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    kapt "com.android.databinding:compiler:3.3.0-alpha08"

}

kapt {
    generateStubs = true
}

apply plugin: 'com.google.gms.google-services'
repositories {
    mavenCentral()
}

Error

Process: pt.myapp.android.myapp.debug, PID: 13653
java.lang.RuntimeException: Unable to start activity ComponentInfo{pt.myapp.android.myapp.debug/pt.myapp.android.myapp.ui.activities.TestActivity}: android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
 Caused by: android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
 Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Constructor.newInstance0(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
    at android.view.LayoutInflater.createView(LayoutInflater.java:647)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
    at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at pt.myapp.android.myapp.ui.activities.TestActivity.onCreate(TestActivity.java:13)
    at android.app.Activity.performCreate(Activity.java:7136)
    at android.app.Activity.performCreate(Activity.java:7127)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
 Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
    at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:216)
    at android.content.res.Resources.getColorStateList(Resources.java:1031)
2019-02-10 14:47:12.350 13653-13653/pt.myapp.android.myapp.debug E/AndroidRuntime:     at android.content.Context.getColorStateList(Context.java:642)
    at androidx.appcompat.content.res.AppCompatResources.getColorStateList(AppCompatResources.java:67)
    at com.google.android.material.bottomnavigation.BottomNavigationMenuView.createDefaultColorStateList(BottomNavigationMenuView.java:467)
    at com.google.android.material.bottomnavigation.BottomNavigationMenuView.<init>(BottomNavigationMenuView.java:101)
    at com.google.android.material.bottomnavigation.BottomNavigationMenuView.<init>(BottomNavigationMenuView.java:86)
    at com.google.android.material.bottomnavigation.BottomNavigationView.<init>(BottomNavigationView.java:123)
    at com.google.android.material.bottomnavigation.BottomNavigationView.<init>(BottomNavigationView.java:114)
        ... 28 more

Body:
In BottomNavigationView inflating error can occur due to XML it can be either in @layout, @drawable, @style or @color folder.

<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_gravity="bottom"
android:background="@color/colorPrimary"
app:itemIconTint="@drawable/bottom_navigation_colors"
app:itemTextColor="@drawable/bottom_navigation_colors"
app:menu="@menu/bottom_navigation_menu" />

This line may be causing inflating error:
app:menu="@menu/bottom_navigation_menu"

I resolved it by keeping my drawable files in both the folder:

drawable

drawable-v24


来源: stackexchange

问:
Cannot get material-ui datepicker to work
For some reason, I cannot get the material-ui datepicker to work. Every time the datepicker is rendered in React, the following error is thrown:

RangeError: Format string contains an unescaped latin alphabet character n

I have created a stackblitz with just the datepicker (https://stackblitz.com/edit/react-6ma6xd?embed=1&file=index.js) and even there the error shows up. What am I doing wrong? I think I followed all the instructions from the installation guide.

Link to the material-ui/pickers: https://material-ui-pickers.dev/

答:
For me the only thing that was creating this issue was the order of import statement.Make sure you:

import 'date-fns'; before importing import DateFnsUtils from '@date-io/date-fns';

i.e

```<code>import 'date-fns'
import DateFnsUtils from '@date-io/date-fns';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For me the only thing that was creating this issue was the order of import statement.Make sure you:

import 'date-fns'; before importing import DateFnsUtils from '@date-io/date-fns';

i.e

import 'date-fns'
import DateFnsUtils from '@date-io/date-fns';


问:
How to reload Flask-based webpage after receiving data
I have a simple web project which gets data from, processes it and needs to output result on the page. After the spider works, the data is written to sqlite, but not displayed on the page. How to refresh page after writing data in sqlite?

button

```<code><button id="scrape" class="btn btn-success mr-2">Scrape</button>
</code>```

js

```<code>$.post('/wellness', {'specialty': specialty, 'state': state, 'city': city}, (res) => {
});
</code>```

flask

```<code>@app.route('/<page_id>', methods=['GET', 'POST'])
def page(page_id):
file_html = f"{page_id}.html"
file_py = f"{page_id}.py"
file_db = f"{page_id}.db"

specialty = request.form.getlist('specialty[]')
state = request.form.getlist('state[]')
city = request.form.getlist('city[]')

settings = ''
with open('settings.json', 'r') as f:
    for line in f.read():
        settings += line

settings = json.loads(settings)
settings['specialty'] = specialty
settings['state'] = state
settings['city'] = city

with open('settings.json', 'w') as f:
    f.write(json.dumps(settings, indent=4))

process = subprocess.Popen('python e:/Python/sqlite/spiders/' + file_py, shell=True)
process.wait()

try:
    db = sqlite3.connect(file_db)
    cursor = db.cursor()

    cursor.execute('SELECT * FROM wellness ORDER BY id DESC')
    cards = cursor.fetchall()

    db.close()
    return render_template(file_html, cards = cards)
except:
    return render_template(file_html)
</code>```

答:
Write the appropriate append/fill HTML code to the div where you want to show

```<code>(res) => {
 # Write append or fill here
});
</code>```

Example

```<code>$.ajax({
    url: "/update/",
    type: "POST",
    data: {"data": data},
    success: function(resp){
        $('div.stats').html(resp.data); # Filling the data in appropriate div
    }
});
</code>```

You would have to do similar thing for your use case.

Body:
I have a simple web project which gets data from, processes it and needs to output result on the page. After the spider works, the data is written to sqlite, but not displayed on the page. How to refresh page after writing data in sqlite?

button

<button id="scrape" class="btn btn-success mr-2">Scrape</button>

js

$.post('/wellness', {'specialty': specialty, 'state': state, 'city': city}, (res) => {
});

flask

@app.route('/<page_id>', methods=['GET', 'POST'])
def page(page_id):
file_html = f"{page_id}.html"
file_py = f"{page_id}.py"
file_db = f"{page_id}.db"

specialty = request.form.getlist('specialty[]')
state = request.form.getlist('state[]')
city = request.form.getlist('city[]')

settings = ''
with open('settings.json', 'r') as f:
    for line in f.read():
        settings += line

settings = json.loads(settings)
settings['specialty'] = specialty
settings['state'] = state
settings['city'] = city

with open('settings.json', 'w') as f:
    f.write(json.dumps(settings, indent=4))

process = subprocess.Popen('python e:/Python/sqlite/spiders/' + file_py, shell=True)
process.wait()

try:
    db = sqlite3.connect(file_db)
    cursor = db.cursor()

    cursor.execute('SELECT * FROM wellness ORDER BY id DESC')
    cards = cursor.fetchall()

    db.close()
    return render_template(file_html, cards = cards)
except:
    return render_template(file_html)

Body:
Write the appropriate append/fill HTML code to the div where you want to show

(res) => {
 # Write append or fill here
});

Example

$.ajax({
    url: "/update/",
    type: "POST",
    data: {"data": data},
    success: function(resp){
        $('div.stats').html(resp.data); # Filling the data in appropriate div
    }
});

You would have to do similar thing for your use case.


问:
Implement strategy pattern with enum
I'm trying to create a service to handle different payment methods. I want to implement strategy pattern. I'd like to have an enum with the different payment methods. This is an example of what I have:

```<code>public enum Pay {
    CREDITCARD(1) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }

    },
    OTHERMETHOD(2) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }
    };

    private int id;

    Payment(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public abstract void pay();
}
</code>```

somewhere in the client:

```<code>user.setPay(Pay.CREDITCARD);
user.pay();
</code>```

The problem with this approach is that method "pay" could be have a lot of logic so I'd like to have it in a different class. I could define an interface like this:

```<code>public interface Pay {
    void pay();
}

public class CreditCard implements Pay {
    @Override
    public void pay() {
    }
}

public class OtherMethod implements Pay {
    @Override
    public void pay() {
    }
}
</code>```

somewhere in the client:

```<code>if (method.equals("creditcard")) {
    user.setPay(new CreditCard());
    user.pay();
}
else {
    user.setPay(new OtherMethod());
    user.pay();
}
</code>```

but I like much more how it looks with Enum and that the reason to keep that way. Thanks

答: I don't recommend implementing the logic inside an enum because you will likely need to make calls to external services to implement a payment, and therefore you'll want to be able to inject those dependencies in your payment implementations. Enums being statically initialized, they are not friendly at all for injection. It can be ok to put some logic in enumerations, although they should generally largely remain simple data, but this case seems too complex for being handled in enums. You can have an enum to decide the type of payment and then have a mapping from each enum item to a singleton of a payment implementations if you want, but the logic should be decoupled from the enum.</p>

Title: Implement strategy pattern with enum

Body:
I'm trying to create a service to handle different payment methods. I want to implement strategy pattern. I'd like to have an enum with the different payment methods. This is an example of what I have:

public enum Pay {
    CREDITCARD(1) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }

    },
    OTHERMETHOD(2) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }
    };

    private int id;

    Payment(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public abstract void pay();
}

somewhere in the client:

user.setPay(Pay.CREDITCARD);
user.pay();

The problem with this approach is that method "pay" could be have a lot of logic so I'd like to have it in a different class. I could define an interface like this:

public interface Pay {
    void pay();
}

public class CreditCard implements Pay {
    @Override
    public void pay() {
    }
}

public class OtherMethod implements Pay {
    @Override
    public void pay() {
    }
}

somewhere in the client:

if (method.equals("creditcard")) {
    user.setPay(new CreditCard());
    user.pay();
}
else {
    user.setPay(new OtherMethod());
    user.pay();
}

but I like much more how it looks with Enum and that the reason to keep that way. Thanks


问:
Validating userName using Regex

The only numbers in the username have to be at the end. There can be zero or more of them at the end.

Username letters can be lowercase and uppercase.

Usernames have to be at least two characters long. A two-letter username can only use alphabet letter characters.

I'm trying with this but I'm stalled. /\d+$\w+/gi

答:
Simplified version of /^[a-z]{2,}\d*$|(?=\w{3,})^[a-z]{1,}\d+$/i:

```<code>/^\D(\d{2,}|\D+)\d*$/i
</code>```

Code explanation:

^ - start of input

\D - first character is a letter

\d{2,} - ends with two or more numbers

| - or

\D+ - has one or more letters next

\d* - and ends with zero or more numbers

$ - end of input

i - ignore case of input

ContentLicense: CC BY-SA 3.0

Title: Validating userName using Regex

Body:
Simplified version of /^[a-z]{2,}\d*$|(?=\w{3,})^[a-z]{1,}\d+$/i:

/^\D(\d{2,}|\D+)\d*$/i

Code explanation:

^ - start of input

\D - first character is a letter

\d{2,} - ends with two or more numbers

| - or

\D+ - has one or more letters next

\d* - and ends with zero or more numbers

$ - end of input

i - ignore case of input


问:
unexpected results which is empty array
when I run code, I see empty array, but I aim to have an array with some vowels.

let input = 'zai';
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];

for (let inputindex = 0; inputindex < input.inputindex; inputindex++) {
  for (let vowel = 0; vowel > vowels.length; vowel++) {
    if (input[inputindex] === vowels[vowel]) {
      resultArray.push(input[inputindex])
    }
  }
}

console.log(resultArray)```

答:
You have done a mistake by writing input.inputindex instead of input.length. Plus, you have wrote vowel > vowel.length instead of vowel < vowels.length. That's why your loop didn't run at least a single loop and ended up with an empty array. Correct the code as below and try again...

```<code>let input = 'zai';
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];

for (let inputindex = 0; inputindex < input.length; inputindex++) {
  for (let vowel = 0; vowel < vowels.length; vowel++) {
    if (input[inputindex] === vowels[vowel]) {
      resultArray.push(input[inputindex])
    }
  }
}

console.log(resultArray)
</code>```

Title: unexpected results which is empty array

Body:
You have done a mistake by writing input.inputindex instead of input.length. Plus, you have wrote vowel > vowel.length instead of vowel < vowels.length. That's why your loop didn't run at least a single loop and ended up with an empty array. Correct the code as below and try again...

let input = 'zai';
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];

for (let inputindex = 0; inputindex < input.length; inputindex++) {
  for (let vowel = 0; vowel < vowels.length; vowel++) {
    if (input[inputindex] === vowels[vowel]) {
      resultArray.push(input[inputindex])
    }
  }
}

console.log(resultArray)


问:
Check if files share same ending in python
how would i check if all files in specific directory dir/ share the same file ending .txt.

This is how I find the files:

for dirpath, dirnames, files in os.walk(dir):
    print(files)
```

答:
```<code>all_end_with_txt = True
for dirpath, dirnames, files in os.walk(dir):
        for file in files:
                if not file.lower().endswith('.txt'):
                        all_end_with_txt = False
</code>```


问:
changing range causes a distribution not normal
A post gives some code to plot this figure

```<code>import scipy.stats as ss
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10, 11)
xU, xL = x + 0.5, x - 0.5
prob = ss.norm.cdf(xU, scale = 3) - ss.norm.cdf(xL, scale = 3)
prob = prob / prob.sum() #normalize the probabilities so their sum is 1
nums = np.random.choice(x, size = 10000, p = prob)
plt.hist(nums, bins = len(x))
</code>```

I modifyied this line

```<code>x = np.arange(-10, 11)
</code>```

to this line

```<code>x = np.arange(10, 31)
</code>```

I got this figure

How to fix that?

答:
Given what you're asking Python to do, there's no error in this plot: it's a histogram of 10,000 samples from the tail (anything that rounds to between 10 and 31) of a normal distribution with mean 0 and standard deviation 3. Since probabilities drop off steeply in the tail of a normal, it happens that none of the 10,000 exceeded 17, which is why you didn't get the full range up to 31.

If you just want the x-axis of the plot to cover your full intended range, you could add plt.xlim(9.5, 31.5) after plt.hist.

If you want a histogram with support over this entire range, then you'll need to adjust the mean and/or variance of the distribution. For instance, if you specify that your normal distribution has mean 20 rather than mean 0 when you obtain prob, i.e.

```<code>prob = ss.norm.cdf(xU, loc=20, scale=3) - ss.norm.cdf(xL, loc=20, scale=3)
</code>```

then you'll recover a similar-looking histogram, just translated to the right by 20.

Body:
A post gives some code to plot this figure

import scipy.stats as ss
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10, 11)
xU, xL = x + 0.5, x - 0.5
prob = ss.norm.cdf(xU, scale = 3) - ss.norm.cdf(xL, scale = 3)
prob = prob / prob.sum() #normalize the probabilities so their sum is 1
nums = np.random.choice(x, size = 10000, p = prob)
plt.hist(nums, bins = len(x))

I modifyied this line

x = np.arange(-10, 11)

to this line

x = np.arange(10, 31)

I got this figure

How to fix that?

Body:
Given what you're asking Python to do, there's no error in this plot: it's a histogram of 10,000 samples from the tail (anything that rounds to between 10 and 31) of a normal distribution with mean 0 and standard deviation 3. Since probabilities drop off steeply in the tail of a normal, it happens that none of the 10,000 exceeded 17, which is why you didn't get the full range up to 31.

If you just want the x-axis of the plot to cover your full intended range, you could add plt.xlim(9.5, 31.5) after plt.hist.

If you want a histogram with support over this entire range, then you'll need to adjust the mean and/or variance of the distribution. For instance, if you specify that your normal distribution has mean 20 rather than mean 0 when you obtain prob, i.e.

prob = ss.norm.cdf(xU, loc=20, scale=3) - ss.norm.cdf(xL, loc=20, scale=3)

then you'll recover a similar-looking histogram, just translated to the right by 20.


问:
Css compression - Vuetify
I use vuetify, with a nuxt project and when I look at the page source I see 26k lines of code and around99% of it css comes from vuetify. and when Icheck some other pages page souce I see less lines of code with unreadable css. Should I do something explicitly for this? I didnt change anything from nuxt.config for vuetify</p>

```<code>vuetify: {
customVariables: ['~/assets/variables.scss'],
theme: {
  dark: false,
  themes: {
    dark: {
      primary: colors.blue.darken2,
      accent: colors.grey.darken3,
      secondary: colors.amber.darken3,
      info: colors.teal.lighten1,
      warning: colors.amber.base,
      error: colors.deepOrange.accent4,
      success: colors.green.accent3
    }
  }
}
</code>```

答:
Don't worry. You do not have to do anything explicitly. The page source you are seeing just development version of your page. In the production, that will be handled by Nuxt.

For a quick test, try nuxt start and see the page source again.

Title: Css compression - Vuetify

Body:
I use vuetify, with a nuxt project and when I look at the page source I see 26k lines of code and around99% of it css comes from vuetify. and when Icheck some other pages page souce I see less lines of code with unreadable css. Should I do something explicitly for this? I didnt change anything from nuxt.config for vuetify

vuetify: {
customVariables: ['~/assets/variables.scss'],
theme: {
  dark: false,
  themes: {
    dark: {
      primary: colors.blue.darken2,
      accent: colors.grey.darken3,
      secondary: colors.amber.darken3,
      info: colors.teal.lighten1,
      warning: colors.amber.base,
      error: colors.deepOrange.accent4,
      success: colors.green.accent3
    }
  }
}


问:
Avoiding Global State
Currently I'm writing an app. If I want to avoid Singletons, do I have to simply pass references of everything around?

For example,

I have a "main" class.

Class: Main

+---- Screen

+---- Camera

+---- Terrain

+---- Vehicle

+---- PhysicsWorld

It contains my Camera, Terrain, and Vehicle,etc classes.  Now, I have issues when I'm creating say, the Terrain object.  Terrain wants to access Main classes Screen object so it can add its Terrain Graphics to the screen.  It also wants to know about the Camera object for when it is drawing so it knows what scale to draw it.  It also wants to know about my PhysicsWorld object so it can add itself to the physics engine.

Do I have to always lug these objects back and forth between constructors?  I mean, when I create a Terrain object, do I simply have to pass around my screen object, my physicsWorld, camera, etc?

Another random scenario I have, is now.. inside my Vehicle class I need to call a Restart() method on my Main class.  Does this mean I have to pass an instance of main to Vehicle?  Really??

It feels cumbersome to constantly have to pass 4-5 things to my classes, especially in my scenario now where almost every in-game object I have needs a screen, physics, camera info, etc.

Any suggestions?

答:
It feels cumbersome to constantly have
  to pass 4-5 things to my classes,
  especially in my scenario now where
  almost every in-game object I have
  needs a screen, physics, camera info,
  etc.
  Then the correct question to ask is "why do I need all 5 objects in all my classes?"
  Why on Earth does every in-gmae object need any of the mentioned things? An in-game object needs a position and whatever it needs to process its behavior. Then a separate renderer can, you know, render, the object. Which means that only the renderer needs the camera info and screen.

The physics could go either way. You could have a separate physics entity which updates the game object, or you could pass that physics object to every game object. But even if you do pass that around, we're down to one out of the three objects listed. :)

That's why globals and singletons are often best avoided. They disguise your dependencies so you end up with far more dependencies between your objects than you actually need. And then it becomes almost impossible to remove the globals.

However, if you do stick with globals, do yourself a favor, and at least avoid singletons. You don't need the additional constraints enforced by a singleton.

Terrain wants to access Main classes
  Screen object so it can add its
  Terrain Graphics to the screen. It
  also wants to know about the Camera
  object for when it is drawing so it
  knows what scale to draw it. It also
  wants to know about my PhysicsWorld
  object so it can add itself to the
  physics engine.

The terrain object needs to know one thing: What is the terrain like. Someone else can take responsibility for rendering it. That someone will need to know about the camera, screen and terrain graphics, sure, which suggests that the same object might plausibly be able to do other tasks involving these objects (such as other rendering tasks).
Why should the terrain care about what scale it's drawn in? It needs to know the scale ingame, but not the scale in camera-space. And why can't someone else add the terrain to the physics engine? The main function might be able to do that, even. Create terrain, create physics engine, register terrain with physics engine, start game.

OwnerDisplayName: KingNestor

ContentLicense: CC BY-SA 2.5

Title: Avoiding Global State

LastEditorDisplayName: KingNestor

OwnerDisplayName: jalf


问:
Flutter ListView into ListView.builder
I want to convert this ListView into a ListView.builder, because i need the Index. Can someone show me how to cnvert thsi ListView?`Thank for your Help :)</p>

```<code>return new ListView(
   children: snapshot.data.documents.map((DocumentSnapshot document) {
                  return new ListTile(
                    title: new Text(document['name']),
                  );
                }).toList(),
              );
</code>```

答:
You just provide a builder function. This function gets called for each Item in your data. The amount of items you set with itemCount.

Example:

```<code>var dataList = []; //this would be your snapshot data

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(gallery),
      ),
      body: ListView.builder(
        itemBuilder: (context, index) => ListTile(
          title: Text(dataList[index]),
        ),
      ),
    );
  }
</code>```

Title: Flutter ListView into ListView.builder

Body:
I want to convert this ListView into a ListView.builder, because i need the Index. Can someone show me how to cnvert thsi ListView?`Thank for your Help :)

return new ListView(
   children: snapshot.data.documents.map((DocumentSnapshot document) {
                  return new ListTile(
                    title: new Text(document['name']),
                  );
                }).toList(),
              );

Body:
You just provide a builder function. This function gets called for each Item in your data. The amount of items you set with itemCount.

Example:

var dataList = []; //this would be your snapshot data

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(gallery),
      ),
      body: ListView.builder(
        itemBuilder: (context, index) => ListTile(
          title: Text(dataList[index]),
        ),
      ),
    );
  }


问:
Matlab ShortEng number format via sprintf() and fprintf()?
I like using MATLAB's shortEng notation in the interactive Command Window:

```<code>>> a = 123e-12;
>> disp(a);

   1.2300e-10       % Scientific notation. Urgh!

>> format shortEng;
>> disp(a);

   123.0000e-012    % Engineering notation! :-D
</code>```

But I want to use fprintf:

```<code>>> format shortEng;
>> fprintf('%0.3e', a);
1.2300e-10          % Scientific. Urgh!
</code>```

How do I print values with fprintf or sprintf with Engineering formatting using the MATLAB Format Operators?

I know I could write my own function to format the values into strings, but I'm looking for something already built into MATLAB.

NOTE: "Engineering" notation differs from "Scientific" in that the exponent is always a multiple of 3.

```<code>>> fprintf('%0.3e', a);    % This is Scientific notation.
1.230000e-10
</code>```

答:
You can use the following utility posted to the MATLAB file exchange:
num2eng

It offers extensive control over the formatting of the output string and full input checking, so is more flexible and less prone to error than the simpler evalc approach suggested by user2271770.

It can also output strings using SI prefixes instead of engineering notation, if you prefer.

Body:
I like using MATLAB's shortEng notation in the interactive Command Window:

>> a = 123e-12;
>> disp(a);

   1.2300e-10       % Scientific notation. Urgh!

>> format shortEng;
>> disp(a);

   123.0000e-012    % Engineering notation! :-D

But I want to use fprintf:

>> format shortEng;
>> fprintf('%0.3e', a);
1.2300e-10          % Scientific. Urgh!

How do I print values with fprintf or sprintf with Engineering formatting using the MATLAB Format Operators?

I know I could write my own function to format the values into strings, but I'm looking for something already built into MATLAB.

NOTE: "Engineering" notation differs from "Scientific" in that the exponent is always a multiple of 3.

>> fprintf('%0.3e', a);    % This is Scientific notation.
1.230000e-10


问:
Spec for not-inheriting certain font settings in textarea
This is a wonderful question about why styles do not get inherited in form fields.
This is a wonderful answer that explains "Certain controls are not defaulted to inherit font settings."

Is there a specification about this? "Certain controls" seems vague to me.

I checked

MDN - Inheritance Article does not mention form fields.

MDN - <textarea> Article does not mention inheritance

答:
The answer to your question is pretty simple and it's not related to the specification. If you take the example of a textarea inside Google Chrome and inspect the element you will get the following:

The browser is applying a default font-family (and many other properties) so the inherit rule no more apply.

Now if you want to know how these default style are defined you need to consider each browser and its implementation since this is out of the scope of the CSS specification.


答:
Here is how you can create a ListView builder, which provides an index   </p>

```<code> var documents = snapshot.data.documents.map((DocumentSnapshot document);
    return ListView.builder(
     itemCount: documents.length,
    itemBuilder: (context, index) => {
       // Just an example, use your own fields
       Text(documents[index].Name);
    });
</code>```

Title: Flutter ListView into ListView.builder

Body:
Here is how you can create a ListView builder, which provides an index

 var documents = snapshot.data.documents.map((DocumentSnapshot document);
    return ListView.builder(
     itemCount: documents.length,
    itemBuilder: (context, index) => {
       // Just an example, use your own fields
       Text(documents[index].Name);
    });


问:
Flutter command not found
Apparently, none of the Flutter commands are working in the terminal of Android Studio which I believe I am trying to run it at the root of my project.

Output:

```<code>bash: flutter: command not found
</code>```

答:
On macOS v10.15 (Catalina), the issue is with the Path environment variable.

Open Terminal and check the shell (command: echo $SHELL),

If output is /bin/bash, we need to convert to Z shell (Zsh). Z shell is only the default shell on newly created user accounts, so any existing accounts you have on an upgraded Mac will still use Bash by default unless you change it. Simply run the chsh -s (change shell) command in a Terminal window.

(command: chsh -s /bin/zsh)

Enter your password when prompted. After you close the terminal window and reopen it, you’ll be using Z shell.

Update your Path

2.1. Open the zshrc file (command: vim ~/.zshrc)

2.2. Press 'I' to insert the path as (export PATH=~/Dev/flutter/bin:$PATH). Here ~/Dev/ is the folder where Flutter is installed

2.3. Hit Esc key and then :wq to save and exit the file

Done! try (command: flutter doctor)

Title: Flutter command not found

Body:
Apparently, none of the Flutter commands are working in the terminal of Android Studio which I believe I am trying to run it at the root of my project.

Output:

bash: flutter: command not found


问:
How to count the number detected object (in bounding box) with tensorflow object detection API
i use tutorial from edje electronics with Faster R-CNN and it's works
but i want to improve it. i want to count the object
the question is....... how can i remove the percentage of accuracy and replace it with number of counted bounding box.

i don't know which one i must add and remove it to counting the bounding box
here is the code

```<code>import os
import cv2
import numpy as np
import tensorflow as tf
import sys

sys.path.append("..")

from utils import label_map_util
from utils import visualization_utils as vis_util

MODEL_NAME = 'inference_graph'
VIDEO_NAME = 'animal.mov'

# Grab path to current working directory
CWD_PATH = os.getcwd()

# Path to frozen detection graph .pb file, which contains the model that is used
# for object detection.
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')

# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt')

PATH_TO_VIDEO = os.path.join(CWD_PATH,VIDEO_NAME)

NUM_CLASSES = 6

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

    sess = tf.Session(graph=detection_graph)

# Define input and output tensors (i.e. data) for the object detection classifier

image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')

video = cv2.VideoCapture(PATH_TO_VIDEO)

while(video.isOpened()):

    ret, frame = video.read()
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame_expanded = np.expand_dims(frame_rgb, axis=0)

    (boxes, scores, classes, num) = sess.run(
        [detection_boxes, detection_scores, detection_classes, num_detections],
        feed_dict={image_tensor: frame_expanded})

    vis_util.visualize_boxes_and_labels_on_image_array(
        frame,
        np.squeeze(boxes),
        np.squeeze(classes).astype(np.int32),
        np.squeeze(scores),
        category_index,
        use_normalized_coordinates=True,
        line_thickness=8,
        min_score_thresh=0.60)

    cv2.imshow('Object detector', frame)

    if cv2.waitKey(1) == ord('q'):
        break

video.release()
cv2.destroyAllWindows()
</code>```

答: You have to modify the visualize_boxes_and_labels_on_image_array() function in utils/visualization_utils.py to remove the conf score display and show length of boxes array</p>

Body:
i use tutorial from edje electronics with Faster R-CNN and it's works
but i want to improve it. i want to count the object
the question is....... how can i remove the percentage of accuracy and replace it with number of counted bounding box.

i don't know which one i must add and remove it to counting the bounding box
here is the code

import os
import cv2
import numpy as np
import tensorflow as tf
import sys

sys.path.append("..")

from utils import label_map_util
from utils import visualization_utils as vis_util

MODEL_NAME = 'inference_graph'
VIDEO_NAME = 'animal.mov'

# Grab path to current working directory
CWD_PATH = os.getcwd()

# Path to frozen detection graph .pb file, which contains the model that is used
# for object detection.
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')

# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt')

PATH_TO_VIDEO = os.path.join(CWD_PATH,VIDEO_NAME)

NUM_CLASSES = 6

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

    sess = tf.Session(graph=detection_graph)

# Define input and output tensors (i.e. data) for the object detection classifier

image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')

video = cv2.VideoCapture(PATH_TO_VIDEO)

while(video.isOpened()):

    ret, frame = video.read()
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame_expanded = np.expand_dims(frame_rgb, axis=0)

    (boxes, scores, classes, num) = sess.run(
        [detection_boxes, detection_scores, detection_classes, num_detections],
        feed_dict={image_tensor: frame_expanded})

    vis_util.visualize_boxes_and_labels_on_image_array(
        frame,
        np.squeeze(boxes),
        np.squeeze(classes).astype(np.int32),
        np.squeeze(scores),
        category_index,
        use_normalized_coordinates=True,
        line_thickness=8,
        min_score_thresh=0.60)

    cv2.imshow('Object detector', frame)

    if cv2.waitKey(1) == ord('q'):
        break

video.release()
cv2.destroyAllWindows()


问:
Hudson CI: Job waits until all of its dependency jobs are done
I have a bunch of jobs of which some of them can run parallel. However I also have a consolidation job which has to wait until all of the parallel jobs are completed and perform the consolidation.

Eg:

Job A -> Job B, Job C

Job B -> Job D, Job E

Job C -> Job F

Job F, Job E -> Job G

After Job A is done, Job B and Job C are to be triggered. Job D & Job E will be triggered after Job B is completed and similarly Job F is triggered after Job C is completed. and Job G is to be triggered after Job F & Job E are completed.

I notice that Job G is triggered twice after completion of each of the dependent jobs (Job F, Job E). Is there any way I can ensure that Job G runs only once but after completion of Job F and Job E.

答:
One of the better approaches to CI is developing a build process that mirror's the developer's build-cycle as closely possible. You haven't mentioned any other constraints other than build parallelism, and with that information in mind, I'd recommend pulling the hierarchy that you've created in Hudson and moving it into a ant, nant, msbuild, or other script that can be reasonably run on a developer's work station. Then configure Hudson to use that script as its project script. That doesn't mean you can't have the other project's as independent projects in Hudson, it just means that the final project knows how to build itself from all the others.

Lastly, unless the build is long lived, I can't see an issue with letting Hudson run the job twice.


问:
Python 3 Enums with Function Values
I noticed an oddity in the Python 3 Enums (link).

If you set the value of an Enum to a function, it prevents the attribute from being wrapped as an Enum object, which prevents you from being able to use the cool features like EnumCls['AttrName'] to dynamically load the attribute.

Is this a bug? Done on purpose?

I searched for a while but found no mention of restricted values that you can use in an Enum.

Here is sample code that displays the issue:

```<code>class Color(Enum):
    Red = lambda: print('In Red')
    Blue = lambda: print('In Blue')

print(Color.Red)    # <function> - should be Color.Red via Docs
print(Color.Blue)   # <function> - should be Color.Bluevia Docs
print(Color['Red']) # throws KeyError - should be Color.Red via Docs
</code>```

Also, this is my first time asking, so let me know if there's anything I should be doing differently! And thanks for the help!

答:
I ran into this issue recently, found this post, and first was tempted to use the wrapper pattern suggested in the other related post. However eventually I found out that this was a bit overkill for what I had to do. In the past years this happened to me several times with Enum, so I would like to share this simple experience feedback:

if you need an enumeration, ask yourself whether you actually need an enum or just a namespace.

The difference is simple: Enum members are instances of their host enum class, while namespace members are completely independent from the class, they are just located inside.

Here is an example of namespace containing callables, with a get method to return any of them by name.

```<code>class Foo(object):
    """ A simple namespace class with a `get` method to access members """
    @classmethod
    def get(cls, member_name: str):
        """Get a member by name"""
        if not member_name.startswith('__') and member_name != 'get':
            try:
                return getattr(cls, member_name)
            except AttributeError:
                pass
        raise ValueError("Unknown %r member: %r" % (cls.__name__, member_name))

    # -- the "members" --

    a = 1

    @staticmethod
    def welcome(name):
        return "greetings, %s!" % name

    @staticmethod
    def wave(name):
        return "(silently waving, %s)" % name

w = Foo.get('welcome')
a = Foo.get('a')
Foo.get('unknown')  # ValueError: Unknown 'Foo' member: 'unknown'
</code>```

See also this post on namespaces.

Title: Python 3 Enums with Function Values

Body:
I noticed an oddity in the Python 3 Enums (link).

If you set the value of an Enum to a function, it prevents the attribute from being wrapped as an Enum object, which prevents you from being able to use the cool features like EnumCls['AttrName'] to dynamically load the attribute.

Is this a bug? Done on purpose?

I searched for a while but found no mention of restricted values that you can use in an Enum.

Here is sample code that displays the issue:

class Color(Enum):
    Red = lambda: print('In Red')
    Blue = lambda: print('In Blue')

print(Color.Red)    # <function> - should be Color.Red via Docs
print(Color.Blue)   # <function> - should be Color.Bluevia Docs
print(Color['Red']) # throws KeyError - should be Color.Red via Docs

Also, this is my first time asking, so let me know if there's anything I should be doing differently! And thanks for the help!

Body:
I ran into this issue recently, found this post, and first was tempted to use the wrapper pattern suggested in the other related post. However eventually I found out that this was a bit overkill for what I had to do. In the past years this happened to me several times with Enum, so I would like to share this simple experience feedback:

if you need an enumeration, ask yourself whether you actually need an enum or just a namespace.

The difference is simple: Enum members are instances of their host enum class, while namespace members are completely independent from the class, they are just located inside.

Here is an example of namespace containing callables, with a get method to return any of them by name.

class Foo(object):
    """ A simple namespace class with a `get` method to access members """
    @classmethod
    def get(cls, member_name: str):
        """Get a member by name"""
        if not member_name.startswith('__') and member_name != 'get':
            try:
                return getattr(cls, member_name)
            except AttributeError:
                pass
        raise ValueError("Unknown %r member: %r" % (cls.__name__, member_name))

    # -- the "members" --

    a = 1

    @staticmethod
    def welcome(name):
        return "greetings, %s!" % name

    @staticmethod
    def wave(name):
        return "(silently waving, %s)" % name

w = Foo.get('welcome')
a = Foo.get('a')
Foo.get('unknown')  # ValueError: Unknown 'Foo' member: 'unknown'

See also this post on namespaces.


问:
How to find the reason of "Cannot find module" for nrwl modules?
I use nrwl.io in my project.

I created several libs:

```<code>ng g lib rest //ok
ng g lib services //ok
ng g lib models //created ok, but "Cannot find module " later on!
</code>```

All of these libs were successfully created, but when I try to import my models lib I see error "Cannot find module":

```<code>import { ModelA, ModelB } from '@myproj/models'; //Cannot find module '@myproj/models'
</code>```

The question is: How and where I can check if my '@myproj/models' was properly registered?

P.S. I can see "models" module in nx.json, angular.json and tsconfig.json. And I can see no difference with other modules.

P.P.S. I use "@nrwl/nx": "6.1.0" and  "@nrwl/schematics": "6.1.0"

答:
In my case it was because I was dumb and didn't restart my TypeScript server in VS Code:</p>

```<code>CMD / CTRL + SHIFT + P
>TypeScript: Restart TS Server
</code>```

Body:
I use nrwl.io in my project.

I created several libs:

ng g lib rest //ok
ng g lib services //ok
ng g lib models //created ok, but "Cannot find module " later on!

All of these libs were successfully created, but when I try to import my models lib I see error "Cannot find module":

import { ModelA, ModelB } from '@myproj/models'; //Cannot find module '@myproj/models'

The question is: How and where I can check if my '@myproj/models' was properly registered?

P.S. I can see "models" module in nx.json, angular.json and tsconfig.json. And I can see no difference with other modules.

P.P.S. I use "@nrwl/nx": "6.1.0" and  "@nrwl/schematics": "6.1.0"

Body:
In my case it was because I was dumb and didn't restart my TypeScript server in VS Code:

CMD / CTRL + SHIFT + P
>TypeScript: Restart TS Server


问:
Dispatch async action and getState right after the value is updated in an utility function Redux JS
I have a synchronous flow

```<code>const data = store.getState().data
// ... rest of the code
</code>```

If data === undefined I like to to get it and store in data const similar to this

```<code>const data = store.getState().data || getData()
// wait till the data not undefined
// ... rest of the code
</code>```

getData() is just a wrapper for the dispatch({ type: GET_DATA_ASYNC })

since this dispatch is async it will be caught and executed by a saga watcher and the data object will be updated.

My problem that I can't figured out how to handle this gracefully, to be clear, I want to:

get value from the store

if there is no value - request store update (by already existing action)

when the this particular value is updated - get it back

and store it in the data const

BTW: This is all happening in an external util function

答:
If you are using React hooks, you can use the useSelector hook from "react-redux".
This hook allows you to directly access the store and get the data whenever the store is updated.</p>

```<code>import { useSelector } from "react-redux";

export default function Test() {
    const data = useSelector(store => store.__reducerVariable_name__);
    console.log(data);
    // ...
    return data;
}
</code>```

Body:
I have a synchronous flow

const data = store.getState().data
// ... rest of the code

If data === undefined I like to to get it and store in data const similar to this

const data = store.getState().data || getData()
// wait till the data not undefined
// ... rest of the code

getData() is just a wrapper for the dispatch({ type: GET_DATA_ASYNC })

since this dispatch is async it will be caught and executed by a saga watcher and the data object will be updated.

My problem that I can't figured out how to handle this gracefully, to be clear, I want to:

get value from the store

if there is no value - request store update (by already existing action)

when the this particular value is updated - get it back

and store it in the data const

BTW: This is all happening in an external util function

Body:
If you are using React hooks, you can use the useSelector hook from "react-redux".
This hook allows you to directly access the store and get the data whenever the store is updated.

import { useSelector } from "react-redux";

export default function Test() {
    const data = useSelector(store => store.__reducerVariable_name__);
    console.log(data);
    // ...
    return data;
}


问:
Strange side effect from a copy constructor
This simple code:

```<code>#include <iostream>
#include <vector>

struct my_struct
{
    int m_a;

    my_struct(int a) : m_a(a) { std::cout << "normal const " << m_a << std::endl; }

    my_struct(const my_struct&& other) : m_a(other.m_a) { std::cout << "copy move " << other.m_a << std::endl; }

    my_struct(const my_struct &other) : m_a(other.m_a) { std::cout << "copy const " << other.m_a << std::endl; }
};

class my_class
{
public:
    my_class() {}

    void append(my_struct &&m) { m_vec.push_back(m); }

private:
    std::vector<my_struct> m_vec;
};

int main()
{
    my_class m;

    m.append(my_struct(5));
    m.append(std::move(my_struct(6)));
}
</code>```

produces this output:

```<code>normal const 5
copy const 5
normal const 6
copy const 6
copy const 5
</code>```

The first call to append creates the object, and push_back creates a copy. Likewise, the second call to append creates the object, and push_back creates a copy. Now, a copy constructor of the first object is mysteriously called. Could someone explain me what happens? It looks like a strange side effect...

答:
That's just how std::vector works!
When you call push_back(), the underlying array needs to grow to make room for the new element.
So internally, a new larger array is allocated and all the elements of the previous smaller array are copied into the freshly created array. This also comes with some overhead. Now, you can use some techniques to optimize away the copies.

If you have an idea of how large the array could grow, you can use the reserve() method to ensure that no resizing will occur upto that many locations.

```<code>vct.reserve(5)
</code>```

This is will ensure that no resizing will occur until 5 elements.
Also, you can use the emplace_back() function to avoid an additional copy. It constructs the object in place. Simply pass the constructor parameters of the object to emplace_back()

Body:
This simple code:

#include <iostream>
#include <vector>

struct my_struct
{
    int m_a;

    my_struct(int a) : m_a(a) { std::cout << "normal const " << m_a << std::endl; }

    my_struct(const my_struct&& other) : m_a(other.m_a) { std::cout << "copy move " << other.m_a << std::endl; }

    my_struct(const my_struct &other) : m_a(other.m_a) { std::cout << "copy const " << other.m_a << std::endl; }
};

class my_class
{
public:
    my_class() {}

    void append(my_struct &&m) { m_vec.push_back(m); }

private:
    std::vector<my_struct> m_vec;
};

int main()
{
    my_class m;

    m.append(my_struct(5));
    m.append(std::move(my_struct(6)));
}

produces this output:

normal const 5
copy const 5
normal const 6
copy const 6
copy const 5

The first call to append creates the object, and push_back creates a copy. Likewise, the second call to append creates the object, and push_back creates a copy. Now, a copy constructor of the first object is mysteriously called. Could someone explain me what happens? It looks like a strange side effect...

Body:
That's just how std::vector works!
When you call push_back(), the underlying array needs to grow to make room for the new element.
So internally, a new larger array is allocated and all the elements of the previous smaller array are copied into the freshly created array. This also comes with some overhead. Now, you can use some techniques to optimize away the copies.

If you have an idea of how large the array could grow, you can use the reserve() method to ensure that no resizing will occur upto that many locations.

vct.reserve(5)

This is will ensure that no resizing will occur until 5 elements.
Also, you can use the emplace_back() function to avoid an additional copy. It constructs the object in place. Simply pass the constructor parameters of the object to emplace_back()


问:
How to do bulk insertion in cosmosdb using nodejs?
How to do a bulk insertion in cosmos DB using node.js?

Is there any library available to make a bulk insertion in cosmos DB?

答:
There is no bulk support directly with the node.js SDK but there is this sample that uses stored procedure for updates. Can modify to do inserts instead.

hope this is helpful.


问:
How to calculate moving sums of rows of unique observation in R (example provided)?
I have a data.frame called df , and I am trying to count unique devices on a moving hour basis with a gap of 4 minutes as shown in expected_df . I have provided an example below . I did not find any query meeting my requirements , hence this ...

Given data frame

```<code>df<-data.frame(customer=rep("xyz",19),
           device=c("a","a","a","a","a","a","b","b","b","b","b","b","c","c","c","c","c","c","c"),
           local_date=rep("2020-06-04",19),
           local_hour=rep(4,19),
           local_minute=c(1:6,4:9,6:12))
</code>```

Expected data frame

```<code>expected_df<-data.frame(customer=rep("xyz",8),local_hour=rep(4,8),
                    local_date=rep("2020-06-04",8),
                    local_minute_bucket=c("1_5","2_6","3_7","4_9","5_9","6_10","7_11","8_12"),
                    unique_devices=c(2,3,3,3,3,3,2,2))
</code>```

答:
Here's an approach with dplyr, lubridate and purrr:

First, we create the time so that windows can cross hours and days. Second, we arrange by time so that findInterval can work. Next, we create a bucket. Then we use findInterval to calculate the rows that are within the bucket. Then, we use map2 to find the unique devices in those rows.

We then deselect the appropriate columns and use unique to get rid of duplicates.

```<code>library(dplyr)
library(purrr)
library(lubridate)
df %>%
  mutate(time = ymd_hm(paste0(local_date," ",local_hour,":",local_minute))) %>%
  arrange(time) %>%
  mutate(local_minute_bucket = paste0(minute(time),"_",minute(time+minutes(4))),
         unique_devices = map2_chr(row_number(time),
                                   findInterval(time + minutes(4),time),
                                   ~length(unique(device[.x:.y])))) %>%
  dplyr::select(-time,-device) %>%
  unique()
   customer local_date local_hour local_minute local_minute_bucket unique_devices
1       xyz 2020-06-04          4            1                 1_5              2
2       xyz 2020-06-04          4            2                 2_6              3
3       xyz 2020-06-04          4            3                 3_7              3
4       xyz 2020-06-04          4            4                 4_8              3
6       xyz 2020-06-04          4            5                 5_9              3
8       xyz 2020-06-04          4            6                6_10              3
9       xyz 2020-06-04          4            6                6_10              2
11      xyz 2020-06-04          4            7                7_11              2
13      xyz 2020-06-04          4            8                8_12              2
15      xyz 2020-06-04          4            9                9_13              2
16      xyz 2020-06-04          4            9                9_13              1
17      xyz 2020-06-04          4           10               10_14              1
18      xyz 2020-06-04          4           11               11_15              1
19      xyz 2020-06-04          4           12               12_16              1
</code>```

Body:
I have a data.frame called df , and I am trying to count unique devices on a moving hour basis with a gap of 4 minutes as shown in expected_df . I have provided an example below . I did not find any query meeting my requirements , hence this ...

Given data frame

df<-data.frame(customer=rep("xyz",19),
           device=c("a","a","a","a","a","a","b","b","b","b","b","b","c","c","c","c","c","c","c"),
           local_date=rep("2020-06-04",19),
           local_hour=rep(4,19),
           local_minute=c(1:6,4:9,6:12))

Expected data frame

expected_df<-data.frame(customer=rep("xyz",8),local_hour=rep(4,8),
                    local_date=rep("2020-06-04",8),
                    local_minute_bucket=c("1_5","2_6","3_7","4_9","5_9","6_10","7_11","8_12"),
                    unique_devices=c(2,3,3,3,3,3,2,2))

Body:
Here's an approach with dplyr, lubridate and purrr:

First, we create the time so that windows can cross hours and days. Second, we arrange by time so that findInterval can work. Next, we create a bucket. Then we use findInterval to calculate the rows that are within the bucket. Then, we use map2 to find the unique devices in those rows.

We then deselect the appropriate columns and use unique to get rid of duplicates.

library(dplyr)
library(purrr)
library(lubridate)
df %>%
  mutate(time = ymd_hm(paste0(local_date," ",local_hour,":",local_minute))) %>%
  arrange(time) %>%
  mutate(local_minute_bucket = paste0(minute(time),"_",minute(time+minutes(4))),
         unique_devices = map2_chr(row_number(time),
                                   findInterval(time + minutes(4),time),
                                   ~length(unique(device[.x:.y])))) %>%
  dplyr::select(-time,-device) %>%
  unique()
   customer local_date local_hour local_minute local_minute_bucket unique_devices
1       xyz 2020-06-04          4            1                 1_5              2
2       xyz 2020-06-04          4            2                 2_6              3
3       xyz 2020-06-04          4            3                 3_7              3
4       xyz 2020-06-04          4            4                 4_8              3
6       xyz 2020-06-04          4            5                 5_9              3
8       xyz 2020-06-04          4            6                6_10              3
9       xyz 2020-06-04          4            6                6_10              2
11      xyz 2020-06-04          4            7                7_11              2
13      xyz 2020-06-04          4            8                8_12              2
15      xyz 2020-06-04          4            9                9_13              2
16      xyz 2020-06-04          4            9                9_13              1
17      xyz 2020-06-04          4           10               10_14              1
18      xyz 2020-06-04          4           11               11_15              1
19      xyz 2020-06-04          4           12               12_16              1


问:
How do I insert an error message after a certain block of the loop?
I'm writing an e-book. I use a loop to output phone numbers.I use the jQuery plugin Maks and Validator. But the error text is output after each div block. How can I make it output only after the block where there is an error?Any help would be appreciated.

enter image description here

enter image description here

My HTML code:

```<code><form action="${pageContext.request.contextPath}/editDone" id="updateForm" class="form-horizontal form-back" method="post" enctype="multipart/form-data">
//code blocks
    <div class="form-group">
         <label class="col-sm-2 control-label">Телефоны</label>
             <div class="col-sm-10">
                <div class="phones">
                   <div class="input-group phone-input">
                      <div class="input-group-btn">
                         <select class="btn btn-default dropdown-toggle" name="phones[1].phoneType" aria-expanded="false">
                           <option value="HOME" selected>Домашний</option>
                           <option value="WORK">Рабочий</option>
                         </select>
                      </div>
                      <input type="text" name="phones[1].number" class="mask-phone form-control"
                                       value="${phone.number}"/><br>
                         <span class="input-group-btn">
                           <button class="btn btn-danger btn-remove-phone m8" type="button">
                            <span class="glyphicon glyphicon-minus"></span></button>
                         </span>
                   </div>
-----------------------------------------------------
                   <div class="input-group phone-input">
                      <div class="input-group-btn">
                         <select class="btn btn-default dropdown-toggle" name="phones[20].phoneType"
                             aria-expanded="false">
                           <option value="HOME" selected>Домашний</option>
                           <option value="WORK">Рабочий</option>
                         </select>
                      </div>
                      <input type="text" name="phones[20].number" class="mask-phone form-control"
                                       value="${phone.number}"/><br>
                         <span class="input-group-btn">
                           <button class="btn btn-danger btn-remove-phone m8" type="button">
                            <span class="glyphicon glyphicon-minus"></span></button>
                         </span>
                   </div>

</code>```

JS:

```<code>jQuery.validator.addMethod("checkMask", function(value, element) {
    return /\+\d{1}\ \(\d{3}\)\ \d{3}-\d{2}-\d{2}/g.test(value);
}, "Error!");

$(function () {
    $.validator.addClassRules({
        'mask-phone': {
            checkMask: true
        }
    });

    $('#updateForm').validate({
        errorPlacement: function(error, element) {
            if (element.hasClass('mask-phone')) {
                 error.insertAfter('.phone-input')
            }
        }
    });
$('.mask-phone').mask("+9 (999) 999-99-99", {autoclear: false});
</code>```

答:
The issue was resolved adding the string 'p'</p>

```<code>$('#updateForm').validate({
        errorElement: "p",
        errorPlacement: function (error, element) {
            error.insertAfter(element.parent("div"));
        },
        success: function(error) {
            error.remove();
        }
});
</code>```

Body:
I'm writing an e-book. I use a loop to output phone numbers.I use the jQuery plugin Maks and Validator. But the error text is output after each div block. How can I make it output only after the block where there is an error?Any help would be appreciated.

enter image description here

enter image description here

My HTML code:

<form action="${pageContext.request.contextPath}/editDone" id="updateForm" class="form-horizontal form-back" method="post" enctype="multipart/form-data">
//code blocks

         Телефоны

                         <select class="btn btn-default dropdown-toggle" name="phones[1].phoneType" aria-expanded="false">
                           <option value="HOME" selected>Домашний</option>
                           <option value="WORK">Рабочий</option>
                         </select>

                      <input type="text" name="phones[1].number" class="mask-phone form-control"
                                       value="${phone.number}"/>

                           <button class="btn btn-danger btn-remove-phone m8" type="button">
                            </button>

-----------------------------------------------------

                         <select class="btn btn-default dropdown-toggle" name="phones[20].phoneType"
                             aria-expanded="false">
                           <option value="HOME" selected>Домашний</option>
                           <option value="WORK">Рабочий</option>
                         </select>

                      <input type="text" name="phones[20].number" class="mask-phone form-control"
                                       value="${phone.number}"/>

                           <button class="btn btn-danger btn-remove-phone m8" type="button">
                            </button>

JS:

jQuery.validator.addMethod("checkMask", function(value, element) {
    return /\+\d{1}\ \(\d{3}\)\ \d{3}-\d{2}-\d{2}/g.test(value);
}, "Error!");

$(function () {
    $.validator.addClassRules({
        'mask-phone': {
            checkMask: true
        }
    });

    $('#updateForm').validate({
        errorPlacement: function(error, element) {
            if (element.hasClass('mask-phone')) {
                 error.insertAfter('.phone-input')
            }
        }
    });
$('.mask-phone').mask("+9 (999) 999-99-99", {autoclear: false});

Body:
The issue was resolved adding the string 'p'

$('#updateForm').validate({
        errorElement: "p",
        errorPlacement: function (error, element) {
            error.insertAfter(element.parent("div"));
        },
        success: function(error) {
            error.remove();
        }
});


问:
PushNotificationsAPI: Failed to register device: NOKResponse(error=Unauthorized)
I am using Pusher Beams for sending notification to my users. It worked fine but today I got this error, and I don't know how to solve it.

```<code>PushNotificationsAPI: Failed to register device: NOKResponse(error=Unauthorized, description=The device token provided could not be validated against any known credentials)
</code>```

This is my code:

```<code>private fun setPusherBeam() {
    try {
        val tokenProvider = BeamsTokenProvider(
            BuildConfig.PUSHER_BEAM,
            object : AuthDataGetter {
                override fun getAuthData(): AuthData {
                    return AuthData(
                        headers = hashMapOf(
                            "Authorization" to getHawkString(AUTH_TOKEN)
                        ),
                        queryParams = hashMapOf()
                    )
                }
            }
        )

        PushNotifications.setUserId(
            DbHelper.getUser()?.user_id.toString(),
            tokenProvider,
            object : BeamsCallback<Void, PusherCallbackError> {
                override fun onFailure(error: PusherCallbackError) {
                    Timber.i("BeamsAuth Could not login to Beams: ${error.message}")
                }

                override fun onSuccess(vararg values: Void) {
                    Timber.i("BeamsAuth Beams login success $values")
                }
            }
        )
    } catch (ex: Exception) {
        Timber.i("BeamsAuth ex ${ex.localizedMessage}")
    }
}
</code>```

答:
After 2days of struggling with this error, finally, it resolved due to these steps.

1-stop the API

```<code>PushNotifications.start(applicationContext, BuildConfig.INSTANCE_ID)
PushNotifications.stop()
PushNotifications.removeDeviceInterest("example")
PushNotifications.clearDeviceInterests()
</code>```

2-clear android studio cash and reset it

3-remove the app from mobile and reinstall it

4-replace code from step1 with this

```<code>PushNotifications.start(applicationContext, BuildConfig.INSTANCE_ID)
PushNotifications.addDeviceInterest("example")
</code>```

5-repeat 2 and 3

Body:
I am using Pusher Beams for sending notification to my users. It worked fine but today I got this error, and I don't know how to solve it.

PushNotificationsAPI: Failed to register device: NOKResponse(error=Unauthorized, description=The device token provided could not be validated against any known credentials)

This is my code:

private fun setPusherBeam() {
    try {
        val tokenProvider = BeamsTokenProvider(
            BuildConfig.PUSHER_BEAM,
            object : AuthDataGetter {
                override fun getAuthData(): AuthData {
                    return AuthData(
                        headers = hashMapOf(
                            "Authorization" to getHawkString(AUTH_TOKEN)
                        ),
                        queryParams = hashMapOf()
                    )
                }
            }
        )

        PushNotifications.setUserId(
            DbHelper.getUser()?.user_id.toString(),
            tokenProvider,
            object : BeamsCallback<Void, PusherCallbackError> {
                override fun onFailure(error: PusherCallbackError) {
                    Timber.i("BeamsAuth Could not login to Beams: ${error.message}")
                }

                override fun onSuccess(vararg values: Void) {
                    Timber.i("BeamsAuth Beams login success $values")
                }
            }
        )
    } catch (ex: Exception) {
        Timber.i("BeamsAuth ex ${ex.localizedMessage}")
    }
}

Body:
After 2days of struggling with this error, finally, it resolved due to these steps.

1-stop the API

PushNotifications.start(applicationContext, BuildConfig.INSTANCE_ID)
PushNotifications.stop()
PushNotifications.removeDeviceInterest("example")
PushNotifications.clearDeviceInterests()

2-clear android studio cash and reset it

3-remove the app from mobile and reinstall it

4-replace code from step1 with this

PushNotifications.start(applicationContext, BuildConfig.INSTANCE_ID)
PushNotifications.addDeviceInterest("example")

5-repeat 2 and 3


问:
Compiling C++ repl May 2020
Compiling C++ repl

I wonder whether you can help.

I am working through the FreeCodeCamp tutorial on C++ and I am using repl.it as an online IDE.

https://www.freecodecamp.org/news/the-c-plus-plus-programming-language/

The "+new repl" command and choosing a langauage C++ works just fine.

Since I wanted to create a Repl linked to a Github repo, which I thought migth be a good thing to keep both up-to-date, it seems it autocreates a ".replit" file alongside the main.cpp file. The default .replit file which contains two lines:

```<code>language="cpp"
run=""
</code>```

Which won't compile and the error is:

```<code>'run' isn't configured in the .replit file try adding 'run = "echo
hello word"' to .replit
</code>```

I read this: "Configuring the run button / .replit" in the Docs section
https://docs.repl.it/repls/dot-replit

I went back to creating a new Repl, looking at the output when it's run successfully (a new C++ Repl, unlinked to Github, trying to guess what's the default run="" for a C++ Repl), then copied a line from the terminal output and made my .replit file look like this (clang being the compiler, it seems, the rest - some necessary parameters). I haven't researched each of the parameter, so I apologise in advance.

```<code>run="clang++-7 -pthread -std=c++17 -o main main.cpp"
language="cpp"
</code>```

The result is but I was expecting a Hello World print out which normally works, if I'd use a +new Repl:

```<code>clang++-7 -pthread -std=c++17 -o main main.cpp
</code>```

A screenshot from Repl.it tryingt to compile a new C++ Repl :

答:
Delete the .replit file on the and see if that resolves your problem.
Check this image for reference: Image reference</p>

Title: Compiling C++ repl May 2020

Body:
Compiling C++ repl

I wonder whether you can help.

I am working through the FreeCodeCamp tutorial on C++ and I am using repl.it as an online IDE.

https://www.freecodecamp.org/news/the-c-plus-plus-programming-language/

The "+new repl" command and choosing a langauage C++ works just fine.

Since I wanted to create a Repl linked to a Github repo, which I thought migth be a good thing to keep both up-to-date, it seems it autocreates a ".replit" file alongside the main.cpp file. The default .replit file which contains two lines:

language="cpp"
run=""

Which won't compile and the error is:

'run' isn't configured in the .replit file try adding 'run = "echo
hello word"' to .replit

I read this: "Configuring the run button / .replit" in the Docs section
https://docs.repl.it/repls/dot-replit

I went back to creating a new Repl, looking at the output when it's run successfully (a new C++ Repl, unlinked to Github, trying to guess what's the default run="" for a C++ Repl), then copied a line from the terminal output and made my .replit file look like this (clang being the compiler, it seems, the rest - some necessary parameters). I haven't researched each of the parameter, so I apologise in advance.

run="clang++-7 -pthread -std=c++17 -o main main.cpp"
language="cpp"

The result is but I was expecting a Hello World print out which normally works, if I'd use a +new Repl:

clang++-7 -pthread -std=c++17 -o main main.cpp

A screenshot from Repl.it tryingt to compile a new C++ Repl :


问:
I want efficient data structure to store items and their counts and search for min of them?
I want efficient data structure to store items and their counts and search for min of them?

I have a number of items, and a count of each item, I want a data sturucture to store the items and their counts. in my script each time i will search about an item and update its count, also I want to find the item that has the min count, and some times I want the count of some items. would you please tell me which data structure to use with low space and low cost search operations?

答:
You have conflicting requests.

You want fast lookup of an item by it's key (name, item number, id, whatever)
You want fast lookup of an item by it's quantity on hand (count)

Since the fastest lookup possible would be something like a map, which has O(1) lookup, the question is "which key would you use?"  Count is conflicting, so you'll get a little less than the ideal O(1); and, name or id will mean you'll have to lookup a lot of items to get the low quantity items.

This means you need two data structures.

One would be the typical map of name/id to the item.
One would be an index of quantity to a list of items with that quantity.

This means you'll have to update both data structures at the same time, to keep you data consistent within the application.

And then you want to pull up lists of items efficently.  Well, we don't have any idea if your lists are stable, or may be randomly selected, so I would just go over the list item by item.  If you knew you had stable, long lived (reused) lists, another approach might be better.

I hope you read between the lines in this commentary.  There is no "efficient" data structure without considering the use cases.  While you already show that you know that; there is another level to it.  When you combine multiple conflicting use cases, sometimes you wind up sacraficing efficiency in one for efficency in others.  For example, to get fast lookup, you're now going to reduce your insert/update times by needing to rebuild another different data structure.

Of course, you could also require (in the future) your data structure to grow beyond the capacity of a single machine.  If so, you might find that all of your solutions aren't that great, as they all assume a single memory address space.  Then you'll probably have to shift to a distributed data model, like Apache Spark/Hadoop.  In that space, building an index might make less sense, as filtering results is an incredibly cheap operation, while building a distributed index can become even more expensive.  So, you might just shift to "read all entries, throwing away the ones I don't want" and that might service you well, depending on the data, the required latencies, and the actual use in operation.

The key here is to benchmark, and to know what is "good enough."  If you get hung up in "best" or "most efficient" you will spend far more money makeing fast things fast.  Instead set some benchmarks that read like "must be returned from a set of (some number) in under X milliseconds" and then build your solution to beat that rule.


问:
unexpected results which is empty array
when I run code, I see empty array, but I aim to have an array with some vowels.

let input = 'zai';
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];

for (let inputindex = 0; inputindex < input.inputindex; inputindex++) {
  for (let vowel = 0; vowel > vowels.length; vowel++) {
    if (input[inputindex] === vowels[vowel]) {
      resultArray.push(input[inputindex])
    }
  }
}

console.log(resultArray)```

答:
looping through the inputs and comparing them with each value in vowels using the .some method as so:

let input = 'zai';
let vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];

for (let inputindex = 0; inputindex < input.length; inputindex++) {
    if (vowels.some(v => v === input[inputindex])) {
      resultArray.push(input[inputindex])
  }
}

console.log(resultArray)```

Title: unexpected results which is empty array


问:
Perl WWW-Mechanize Module
I am using www-mechanize module to access website controls. Some html pages contains frames. I cant get the links names and i am unable to access the links in frames. Please any one suggest right solution to resolve this issue.

Working Platform: Windows, Perl

Thanks in advance

答:
From what I see, WWW::Mechanize does not load frames automatically; you need to do so yourself.  You can get links to the frames with:

```<code>@frames = $mech->find_link( 'tag' => 'frame' );
</code>```

and then $mech->get each one (cloning your mech object if necessary).

Title: Perl WWW-Mechanize Module

Body:
From what I see, WWW::Mechanize does not load frames automatically; you need to do so yourself.  You can get links to the frames with:

@frames = $mech->find_link( 'tag' => 'frame' );

and then $mech->get each one (cloning your mech object if necessary).