问:
Ktor - Quickstart new project from plugin throwing Error
I am using:

Kotlin 1.3.3

Ktor plugin 1.2.0

IntelliJ IDEA 2019.1.3 (Ultimate Edition) Build #IU-191.7479.7, built
on May 21, 2019

openjdk version "11.0.2" 2019-01-15 - OpenJDK Runtime Environment
18.9 (build 11.0.2+9)

macOS Mojave 10.14.5

Also tried with 'jdk1.8.0_202.jdk/'

I follow the QuickStart from https://ktor.io/quickstart/index.html

When I run the generated code from inside IntelliJ I get:

```<code>/Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home/bin/java "-javaagent:/Applications/IntelliJ IDEA 2019.1 EAP.app/Contents/lib/idea_rt.jar=50192:/Applications/IntelliJ IDEA 2019.1 EAP.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath /Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/classes:/Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/resources:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-server-netty/1.2.0/c30ea7f287343d3007a0794dbfeb3f69aad76ca8/ktor-server-netty-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-html-builder/1.2.0/53ef376dc21a1f404a5154096708fc104092ec77/ktor-html-builder-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-server-host-common/1.2.0/a4335b06f785b39d976e70a00a988bd077beacd1/ktor-server-host-common-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-server-core/1.2.0/4ba64df7deeb3b3cc81b66f005962edfaf63e554/ktor-server-core-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains/kotlin-css-jvm/1.0.0-pre.31-kotlin-1.2.41/718c1d40ec10699ee0ab086e2e9d4d1ebe95646d/kotlin-css-jvm-1.0.0-pre.31-kotlin-1.2.41.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-client-jetty/1.2.0/3dd4fd4541dd7c85564c65162117a2dd60933f0b/ktor-client-jetty-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-client-core-jvm/1.2.0/f88e71cffbb49bdba1f1e93131cdee2e2bae0eaa/ktor-client-core-jvm-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-http-cio-jvm/1.2.0/d37a4df9617f49378780554421a3744ab5ceb1d9/ktor-http-cio-jvm-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-http-jvm/1.2.0/aab3e7e34ba1c1947fe362f899d308d97622cfb8/ktor-http-jvm-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-network/1.2.0/bbaefc8c4d66d3707b0a247a341a2f3ea7bd0c5/ktor-network-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-utils-jvm/1.2.0/9d79aff946644c0f489e75f315fcb396f5b4581e/ktor-utils-jvm-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-jdk8/1.3.31/21edc5a6b2e39bc4dc2860346fd778e27503d6cb/kotlin-stdlib-jdk8-1.3.31.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-classic/1.2.1/706a8b8206ead3683ec639dd270d11fd948fbb0e/logback-classic-1.2.1.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-client-core/1.2.0/5788736ce2795078281e5eeb4523e0c81cf8d06/ktor-client-core-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-jdk7/1.3.31/e652770b6416c6d85934086899ffed3eccd35813/kotlin-stdlib-jdk7-1.3.31.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-reflect/1.3.31/5a426a5ada97967ca60fba495eeaa66cfa7c9e2f/kotlin-reflect-1.3.31.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-io-jvm/0.1.8/591b0489ce565c32d4874610ef64c948e6a5c627/kotlinx-coroutines-io-jvm-0.1.8.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-io-jvm/0.1.8/595d4772d0600272bac6a2dcec2646b037285863/kotlinx-io-jvm-0.1.8.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-html-jvm/0.6.12/95dfe9d85947c8dd57c16dced385a37280166e56/kotlinx-html-jvm-0.6.12.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-jdk8/1.2.1/4d891cee198626c08ac30028afdd743558507ad9/kotlinx-coroutines-jdk8-1.2.1.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-core/1.2.1/3839faf625f4197acaeceeb6da000f011a2acb49/kotlinx-coroutines-core-1.2.1.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.3.31/11289d20fd95ae219333f3456072be9f081c30cc/kotlin-stdlib-1.3.31.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-http-cio/1.2.0/9dc1ab0d309da3a03b4e4435b9dc52afbc78c580/ktor-http-cio-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-http/1.2.0/c160a65dea5200650efd8db738fa157d8e7c3f8/ktor-http-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-utils/1.2.0/67edd57c63978974769e6ab6792713d9253c1db9/ktor-utils-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/atomicfu/0.12.6/2840b58706d9ef8df7c8aee2e8b6e1444d09df60/atomicfu-0.12.6.jar:/Users/NOTiFY/.m2/repository/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/com.typesafe/config/1.3.1/2cf7a6cc79732e3bdf1647d7404279900ca63eb0/config-1.3.1.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-codec-http2/4.1.24.Final/c0c0d9d20402e4493083447052b59d5680e88b2e/netty-codec-http2-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-alpn-openjdk8-client/9.4.15.v20190215/d46fbf9d9c37f75e621a30bf8a192fe2ade30963/jetty-alpn-openjdk8-client-9.4.15.v20190215.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.alpn/alpn-api/1.1.3.v20160715/a1bf3a937f91b4c953acd13e8c9552347adc2198/alpn-api-1.1.3.v20160715.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-core/1.2.1/378913dfc3c6c71e7e2a2853eff2c3e8ac27599/logback-core-1.2.1.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains/kotlin-css/1.0.0-pre.31-kotlin-1.2.41/c40316f81304348a9983ce15a53c81130b16b36a/kotlin-css-1.0.0-pre.31-kotlin-1.2.41.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-io/0.1.8/ab4c5ab04fe13e78ab0d55d71909b22b6f52f658/kotlinx-coroutines-io-0.1.8.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-core-common/1.2.1/5806e3dd5e8dff59fec96747795353f3ba2bfd60/kotlinx-coroutines-core-common-1.2.1.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-io/0.1.8/59bcca58d0dae17790c96a775664267ff8492356/kotlinx-io-0.1.8.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-common/1.3.31/20c34a04ea25cb1ef0139598bd67c764562cb170/kotlin-stdlib-common-1.3.31.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.http2/http2-client/9.4.15.v20190215/dea5744484dbb7e192b6eb061e46d3e53a7edd95/http2-client-9.4.15.v20190215.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-alpn-java-client/9.4.15.v20190215/9e513ee27c5ea1fa4d97186e46f613b44e3a7795/jetty-alpn-java-client-9.4.15.v20190215.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains/annotations/13.0/919f0dfe192fb4e063e7dacadee7f8bb9a2672a9/annotations-13.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/atomicfu-common/0.12.3/b09ed1e1b1a0996e0a3b6c454797d44788a21747/atomicfu-common-0.12.3.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-codec-http/4.1.24.Final/8f20009953b2c7c3d860cef928007bc01aa58ac/netty-codec-http-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-handler/4.1.24.Final/bad56e7da211c5ebe031ae155cb648b1065c7bb6/netty-handler-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.http2/http2-common/9.4.15.v20190215/8983928afb3064fe41b449cabcb827c1024dfba/http2-common-9.4.15.v20190215.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-alpn-client/9.4.15.v20190215/1b215197407fdf8582711e32b187ce458c6097d9/jetty-alpn-client-9.4.15.v20190215.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-codec/4.1.24.Final/290857e5103956bbda11836e33245f2439226b77/netty-codec-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-transport/4.1.24.Final/d37292c94d3a4cba48d9b6cfb6e8e55282035d0d/netty-transport-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-buffer/4.1.24.Final/e354bed2e60b568307138e403f55ba241c1c16d2/netty-buffer-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.http2/http2-hpack/9.4.15.v20190215/1a2b990e51ea38fb742f7cdec24064c32596edb8/http2-hpack-9.4.15.v20190215.jar:/Users/NOTiFY/.m2/repository/org/eclipse/jetty/jetty-http/9.4.15.v20190215/jetty-http-9.4.15.v20190215.jar:/Users/NOTiFY/.m2/repository/org/eclipse/jetty/jetty-io/9.4.15.v20190215/jetty-io-9.4.15.v20190215.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-resolver/4.1.24.Final/dbc1e5b50d31aed883ea3beeb6489e1977d0687f/netty-resolver-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-common/4.1.24.Final/7eeecd7906543214c3c1c984d275d3c6de10b99d/netty-common-4.1.24.Final.jar:/Users/NOTiFY/.m2/repository/org/eclipse/jetty/jetty-util/9.4.15.v20190215/jetty-util-9.4.15.v20190215.jar com.example.ApplicationKt
2019-05-22 08:08:07.394 [main] TRACE Application - {
    # application.conf @ file:/Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/resources/application.conf: 6
    "application" : {
        # application.conf @ file:/Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/resources/application.conf: 7
        "modules" : [
            # application.conf @ file:/Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/resources/application.conf: 7
            "com.example.ApplicationKt.module"
        ]
    },
    # application.conf @ file:/Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/resources/application.conf: 2
    "deployment" : {
        # application.conf @ file:/Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/resources/application.conf: 3
        "port" : 8080
    },
    # Content hidden
    "security" : "***"
}

2019-05-22 08:08:07.885 [main] INFO  Application - No ktor.deployment.watch patterns specified, automatic reload is not active
Exception in thread "main" java.lang.ClassNotFoundException: Module function cannot be found for the fully qualified name 'com.example.ApplicationKt.module'
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.executeModuleFunction(ApplicationEngineEnvironmentReloading.kt:367)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.access$executeModuleFunction(ApplicationEngineEnvironmentReloading.kt:33)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1$$special$$inlined$forEach$lambda$1.invoke(ApplicationEngineEnvironmentReloading.kt:287)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1$$special$$inlined$forEach$lambda$1.invoke(ApplicationEngineEnvironmentReloading.kt:33)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.avoidingDoubleStartupFor(ApplicationEngineEnvironmentReloading.kt:320)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.access$avoidingDoubleStartupFor(ApplicationEngineEnvironmentReloading.kt:33)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1.invoke(ApplicationEngineEnvironmentReloading.kt:286)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1.invoke(ApplicationEngineEnvironmentReloading.kt:33)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.avoidingDoubleStartup(ApplicationEngineEnvironmentReloading.kt:302)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.instantiateAndConfigureApplication(ApplicationEngineEnvironmentReloading.kt:284)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createApplication(ApplicationEngineEnvironmentReloading.kt:137)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.start(ApplicationEngineEnvironmentReloading.kt:257)
    at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:116)
    at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:22)
    at io.ktor.server.engine.ApplicationEngine$DefaultImpls.start$default(ApplicationEngine.kt:56)
    at io.ktor.server.netty.EngineMain.main(EngineMain.kt:21)
    at com.example.ApplicationKt.main(Application.kt:14)

Process finished with exit code 1
</code>```

Any suggestions, besides look at your stack trace it's a:

java.lang.ClassNotFoundException: Module function cannot be found for the fully qualified name 'com.example.ApplicationKt.module' ?

答:
The problem is with argument testing: Boolean = false in function Application.module. It looks like that io.ktor.server.engine.ApplicationEngineEnvironmentReloading.executeModuleFunction doesn't play well if module has argument(s). Or arguments have to be declared somehow in application.conf file, but this doesn't make sense since it already has default false value. Or we are not building the project correctly.

Just remove the argument from the function, the annotations and delete the ApplicationTest.kt from test folder and you'll good to go.

Body:
I am using:

Kotlin 1.3.3

Ktor plugin 1.2.0

IntelliJ IDEA 2019.1.3 (Ultimate Edition) Build #IU-191.7479.7, built
on May 21, 2019

openjdk version "11.0.2" 2019-01-15 - OpenJDK Runtime Environment
18.9 (build 11.0.2+9)

macOS Mojave 10.14.5

Also tried with 'jdk1.8.0_202.jdk/'

I follow the QuickStart from https://ktor.io/quickstart/index.html

When I run the generated code from inside IntelliJ I get:

/Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home/bin/java "-javaagent:/Applications/IntelliJ IDEA 2019.1 EAP.app/Contents/lib/idea_rt.jar=50192:/Applications/IntelliJ IDEA 2019.1 EAP.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath /Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/classes:/Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/resources:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-server-netty/1.2.0/c30ea7f287343d3007a0794dbfeb3f69aad76ca8/ktor-server-netty-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-html-builder/1.2.0/53ef376dc21a1f404a5154096708fc104092ec77/ktor-html-builder-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-server-host-common/1.2.0/a4335b06f785b39d976e70a00a988bd077beacd1/ktor-server-host-common-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-server-core/1.2.0/4ba64df7deeb3b3cc81b66f005962edfaf63e554/ktor-server-core-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains/kotlin-css-jvm/1.0.0-pre.31-kotlin-1.2.41/718c1d40ec10699ee0ab086e2e9d4d1ebe95646d/kotlin-css-jvm-1.0.0-pre.31-kotlin-1.2.41.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-client-jetty/1.2.0/3dd4fd4541dd7c85564c65162117a2dd60933f0b/ktor-client-jetty-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-client-core-jvm/1.2.0/f88e71cffbb49bdba1f1e93131cdee2e2bae0eaa/ktor-client-core-jvm-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-http-cio-jvm/1.2.0/d37a4df9617f49378780554421a3744ab5ceb1d9/ktor-http-cio-jvm-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-http-jvm/1.2.0/aab3e7e34ba1c1947fe362f899d308d97622cfb8/ktor-http-jvm-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-network/1.2.0/bbaefc8c4d66d3707b0a247a341a2f3ea7bd0c5/ktor-network-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-utils-jvm/1.2.0/9d79aff946644c0f489e75f315fcb396f5b4581e/ktor-utils-jvm-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-jdk8/1.3.31/21edc5a6b2e39bc4dc2860346fd778e27503d6cb/kotlin-stdlib-jdk8-1.3.31.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-classic/1.2.1/706a8b8206ead3683ec639dd270d11fd948fbb0e/logback-classic-1.2.1.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-client-core/1.2.0/5788736ce2795078281e5eeb4523e0c81cf8d06/ktor-client-core-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-jdk7/1.3.31/e652770b6416c6d85934086899ffed3eccd35813/kotlin-stdlib-jdk7-1.3.31.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-reflect/1.3.31/5a426a5ada97967ca60fba495eeaa66cfa7c9e2f/kotlin-reflect-1.3.31.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-io-jvm/0.1.8/591b0489ce565c32d4874610ef64c948e6a5c627/kotlinx-coroutines-io-jvm-0.1.8.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-io-jvm/0.1.8/595d4772d0600272bac6a2dcec2646b037285863/kotlinx-io-jvm-0.1.8.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-html-jvm/0.6.12/95dfe9d85947c8dd57c16dced385a37280166e56/kotlinx-html-jvm-0.6.12.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-jdk8/1.2.1/4d891cee198626c08ac30028afdd743558507ad9/kotlinx-coroutines-jdk8-1.2.1.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-core/1.2.1/3839faf625f4197acaeceeb6da000f011a2acb49/kotlinx-coroutines-core-1.2.1.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.3.31/11289d20fd95ae219333f3456072be9f081c30cc/kotlin-stdlib-1.3.31.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-http-cio/1.2.0/9dc1ab0d309da3a03b4e4435b9dc52afbc78c580/ktor-http-cio-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-http/1.2.0/c160a65dea5200650efd8db738fa157d8e7c3f8/ktor-http-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-utils/1.2.0/67edd57c63978974769e6ab6792713d9253c1db9/ktor-utils-1.2.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/atomicfu/0.12.6/2840b58706d9ef8df7c8aee2e8b6e1444d09df60/atomicfu-0.12.6.jar:/Users/NOTiFY/.m2/repository/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/com.typesafe/config/1.3.1/2cf7a6cc79732e3bdf1647d7404279900ca63eb0/config-1.3.1.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-codec-http2/4.1.24.Final/c0c0d9d20402e4493083447052b59d5680e88b2e/netty-codec-http2-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-alpn-openjdk8-client/9.4.15.v20190215/d46fbf9d9c37f75e621a30bf8a192fe2ade30963/jetty-alpn-openjdk8-client-9.4.15.v20190215.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.alpn/alpn-api/1.1.3.v20160715/a1bf3a937f91b4c953acd13e8c9552347adc2198/alpn-api-1.1.3.v20160715.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-core/1.2.1/378913dfc3c6c71e7e2a2853eff2c3e8ac27599/logback-core-1.2.1.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains/kotlin-css/1.0.0-pre.31-kotlin-1.2.41/c40316f81304348a9983ce15a53c81130b16b36a/kotlin-css-1.0.0-pre.31-kotlin-1.2.41.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-io/0.1.8/ab4c5ab04fe13e78ab0d55d71909b22b6f52f658/kotlinx-coroutines-io-0.1.8.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-core-common/1.2.1/5806e3dd5e8dff59fec96747795353f3ba2bfd60/kotlinx-coroutines-core-common-1.2.1.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-io/0.1.8/59bcca58d0dae17790c96a775664267ff8492356/kotlinx-io-0.1.8.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-common/1.3.31/20c34a04ea25cb1ef0139598bd67c764562cb170/kotlin-stdlib-common-1.3.31.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.http2/http2-client/9.4.15.v20190215/dea5744484dbb7e192b6eb061e46d3e53a7edd95/http2-client-9.4.15.v20190215.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-alpn-java-client/9.4.15.v20190215/9e513ee27c5ea1fa4d97186e46f613b44e3a7795/jetty-alpn-java-client-9.4.15.v20190215.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains/annotations/13.0/919f0dfe192fb4e063e7dacadee7f8bb9a2672a9/annotations-13.0.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/atomicfu-common/0.12.3/b09ed1e1b1a0996e0a3b6c454797d44788a21747/atomicfu-common-0.12.3.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-codec-http/4.1.24.Final/8f20009953b2c7c3d860cef928007bc01aa58ac/netty-codec-http-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-handler/4.1.24.Final/bad56e7da211c5ebe031ae155cb648b1065c7bb6/netty-handler-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.http2/http2-common/9.4.15.v20190215/8983928afb3064fe41b449cabcb827c1024dfba/http2-common-9.4.15.v20190215.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty/jetty-alpn-client/9.4.15.v20190215/1b215197407fdf8582711e32b187ce458c6097d9/jetty-alpn-client-9.4.15.v20190215.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-codec/4.1.24.Final/290857e5103956bbda11836e33245f2439226b77/netty-codec-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-transport/4.1.24.Final/d37292c94d3a4cba48d9b6cfb6e8e55282035d0d/netty-transport-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-buffer/4.1.24.Final/e354bed2e60b568307138e403f55ba241c1c16d2/netty-buffer-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/org.eclipse.jetty.http2/http2-hpack/9.4.15.v20190215/1a2b990e51ea38fb742f7cdec24064c32596edb8/http2-hpack-9.4.15.v20190215.jar:/Users/NOTiFY/.m2/repository/org/eclipse/jetty/jetty-http/9.4.15.v20190215/jetty-http-9.4.15.v20190215.jar:/Users/NOTiFY/.m2/repository/org/eclipse/jetty/jetty-io/9.4.15.v20190215/jetty-io-9.4.15.v20190215.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-resolver/4.1.24.Final/dbc1e5b50d31aed883ea3beeb6489e1977d0687f/netty-resolver-4.1.24.Final.jar:/Users/NOTiFY/.gradle/caches/modules-2/files-2.1/io.netty/netty-common/4.1.24.Final/7eeecd7906543214c3c1c984d275d3c6de10b99d/netty-common-4.1.24.Final.jar:/Users/NOTiFY/.m2/repository/org/eclipse/jetty/jetty-util/9.4.15.v20190215/jetty-util-9.4.15.v20190215.jar com.example.ApplicationKt
2019-05-22 08:08:07.394 [main] TRACE Application - {
    # application.conf @ file:/Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/resources/application.conf: 6
    "application" : {
        # application.conf @ file:/Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/resources/application.conf: 7
        "modules" : [
            # application.conf @ file:/Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/resources/application.conf: 7
            "com.example.ApplicationKt.module"
        ]
    },
    # application.conf @ file:/Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/resources/application.conf: 2
    "deployment" : {
        # application.conf @ file:/Users/NOTiFY/IdeaProjects/HelloKtorWorld/out/production/resources/application.conf: 3
        "port" : 8080
    },
    # Content hidden
    "security" : "***"
}

2019-05-22 08:08:07.885 [main] INFO  Application - No ktor.deployment.watch patterns specified, automatic reload is not active
Exception in thread "main" java.lang.ClassNotFoundException: Module function cannot be found for the fully qualified name 'com.example.ApplicationKt.module'
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.executeModuleFunction(ApplicationEngineEnvironmentReloading.kt:367)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.access$executeModuleFunction(ApplicationEngineEnvironmentReloading.kt:33)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1$$special$$inlined$forEach$lambda$1.invoke(ApplicationEngineEnvironmentReloading.kt:287)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1$$special$$inlined$forEach$lambda$1.invoke(ApplicationEngineEnvironmentReloading.kt:33)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.avoidingDoubleStartupFor(ApplicationEngineEnvironmentReloading.kt:320)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.access$avoidingDoubleStartupFor(ApplicationEngineEnvironmentReloading.kt:33)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1.invoke(ApplicationEngineEnvironmentReloading.kt:286)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1.invoke(ApplicationEngineEnvironmentReloading.kt:33)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.avoidingDoubleStartup(ApplicationEngineEnvironmentReloading.kt:302)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.instantiateAndConfigureApplication(ApplicationEngineEnvironmentReloading.kt:284)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createApplication(ApplicationEngineEnvironmentReloading.kt:137)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.start(ApplicationEngineEnvironmentReloading.kt:257)
    at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:116)
    at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:22)
    at io.ktor.server.engine.ApplicationEngine$DefaultImpls.start$default(ApplicationEngine.kt:56)
    at io.ktor.server.netty.EngineMain.main(EngineMain.kt:21)
    at com.example.ApplicationKt.main(Application.kt:14)

Process finished with exit code 1

Any suggestions, besides look at your stack trace it's a:

java.lang.ClassNotFoundException: Module function cannot be found for the fully qualified name 'com.example.ApplicationKt.module' ?


来源: stackexchange

问:
Child component life cycle in parent component
I have a child component in a parent component. My question is: when will the child component be displayed in the code? Before a function in the parent finishes or after the statement of the variable is assigned. Please see the code below:

parent.component.html

```<code><child-component *ngIf="show"> </child-component>
</code>```

parent.component.ts

```<code>function(){
  this.show = true;
  this.anotherVariable = 5;
}
</code>```

In the code above, when will the child component will be displayed? As soon as the statement  this.show = true; runs or after the function ends (which is after this.anotherVariable = 5;  statement).

答:
It will be shown on the next change detection cycle after show is set to true.

Generally, yes, that means immediately(ish) after the variable is changed.

Change detection is a large topic, read more about it here, but basically by changing any of your bound properties in the parent, you are likely invoking the change detector, which is notifying the child-component of their new values (the primary job of the CD).

To optimize this process, you should probably show your component as the last step of this transaction.

https://blog.angular-university.io/how-does-angular-2-change-detection-really-work/

https://blog.angularindepth.com/a-gentle-introduction-into-change-detection-in-angular-33f9ffff6f10

https://medium.com/@bencabanes/angular-change-detection-strategy-an-introduction-819aaa7204e7

ContentLicense: CC BY-SA 4.0

Body:
I have a child component in a parent component. My question is: when will the child component be displayed in the code? Before a function in the parent finishes or after the statement of the variable is assigned. Please see the code below:

parent.component.html

<child-component *ngIf="show"> </child-component>

parent.component.ts

function(){
  this.show = true;
  this.anotherVariable = 5;
}

In the code above, when will the child component will be displayed? As soon as the statement  this.show = true; runs or after the function ends (which is after this.anotherVariable = 5;  statement).


问:
TypeError: 'type' object is not subscriptable + iteration as 'A' not A
I'm very new to programming and I'm trying to write a program in python3 that locates specific pictures on the screen. The pictures are of letters of the alphabet and I'm trying to write a for-loop to cover all of the letters instead of writing it out each time.

I've managed to make it work for individual of letters but when I try to run it through all, it spits out the error

"TypeError: 'type' object is not subscriptable"

Not sure what that means but in addition when attempting to change the file path in each iteration it includes the apostrophes and thus messes up the file path.

THIS WORKS-

```<code>LETTERSONBOARD = [ ]

Letter_A =(list (pyautogui.locateAllOnScreen(r'C:\Users\Letter_A.png'))

LetA = [ ]

for a in Letter_A:

    LetAC.append(pyautogui.center(a))

for a in LetA:

    LETTERSONBOARD.append(a)

print (LetA)
</code>```

THIS DOESN'T-

```<code>ALPHABET = ['A', 'B', ..., 'Z']

LETTERSONBOARD = []

for xx in ALPHABET:

    Letter_[xx] =(list (pyautogui.locateAllOnScreen(r'C:\Users\Letter_'+str[xx]+'.png',))

    Let[xx] = []

    for aa in Letter_[xx]:

        Let[xx].append(pyautogui.center(aa))
    for bb in Let[xx]:

        LETTERSONBOARD.append(bb)

    print (Let[xx])
</code>```

答:
The error TypeError: 'type' object is not subscriptable is an indicator that you are trying to use square brackets on an object that doesn't support that. Typically "subscription" is how you access dictionary values.

I can see in your code you use Letter_[xx], but I can't see where you defined Letter_ as a dictionary. You can try to fix it by adding Letter_ = {} before the top loop.

A few other hints:

You are filling up LETTERSONBOARD, but you seem to never use it.

You are creating plenty of lists and dictionaries. Think about what you actually really need. What information are you interested in once the whole code snippet is done running?

Consider using proper variable names that actually tell you what they contain. This will make your code MUCH easier to understand. Not just to others, but also to yourself.

Here's your code rewritten with better structure and variable names. Note that I did not test this.

```<code>ALPHABET = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
FoundLetter = namedtuple("FoundLetter", ["letter", "center_x", "center_y"])
found_letters = []
for letter in ALPHABET:
  letter_image = "C:\\Users\\Letter_{}.png".format(letter)
  for found_letter in pyautogui.locateAllOnScreen(letter_image):
    center = pyautogui.center(found_letter)
    finding = FoundLetter(letter, center.x, center.y)
    found_letters.append(finding)
</code>```

Now found_letters contains a list of objects that offer the fields letter, center_x and center_y.

Body:
I'm very new to programming and I'm trying to write a program in python3 that locates specific pictures on the screen. The pictures are of letters of the alphabet and I'm trying to write a for-loop to cover all of the letters instead of writing it out each time.

I've managed to make it work for individual of letters but when I try to run it through all, it spits out the error

"TypeError: 'type' object is not subscriptable"

Not sure what that means but in addition when attempting to change the file path in each iteration it includes the apostrophes and thus messes up the file path.

THIS WORKS-

LETTERSONBOARD = [ ]

Letter_A =(list (pyautogui.locateAllOnScreen(r'C:\Users\Letter_A.png'))

LetA = [ ]

for a in Letter_A:

    LetAC.append(pyautogui.center(a))

for a in LetA:

    LETTERSONBOARD.append(a)

print (LetA)

THIS DOESN'T-

ALPHABET = ['A', 'B', ..., 'Z']

LETTERSONBOARD = []

for xx in ALPHABET:

    Letter_[xx] =(list (pyautogui.locateAllOnScreen(r'C:\Users\Letter_'+str[xx]+'.png',))

    Let[xx] = []

    for aa in Letter_[xx]:

        Let[xx].append(pyautogui.center(aa))
    for bb in Let[xx]:

        LETTERSONBOARD.append(bb)

    print (Let[xx])

Body:
The error TypeError: 'type' object is not subscriptable is an indicator that you are trying to use square brackets on an object that doesn't support that. Typically "subscription" is how you access dictionary values.

I can see in your code you use Letter_[xx], but I can't see where you defined Letter_ as a dictionary. You can try to fix it by adding Letter_ = {} before the top loop.

A few other hints:

You are filling up LETTERSONBOARD, but you seem to never use it.

You are creating plenty of lists and dictionaries. Think about what you actually really need. What information are you interested in once the whole code snippet is done running?

Consider using proper variable names that actually tell you what they contain. This will make your code MUCH easier to understand. Not just to others, but also to yourself.

Here's your code rewritten with better structure and variable names. Note that I did not test this.

ALPHABET = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
FoundLetter = namedtuple("FoundLetter", ["letter", "center_x", "center_y"])
found_letters = []
for letter in ALPHABET:
  letter_image = "C:\\Users\\Letter_{}.png".format(letter)
  for found_letter in pyautogui.locateAllOnScreen(letter_image):
    center = pyautogui.center(found_letter)
    finding = FoundLetter(letter, center.x, center.y)
    found_letters.append(finding)

Now found_letters contains a list of objects that offer the fields letter, center_x and center_y.


问:
How could I make a cell contain an entire array?
I am looking for a way to make a cell equal to an entire array in Google Apps Script and Google Sheets.

I have tried making the cell.setValue(array) but using this method the cell is equal to the first array item only.

```<code>var cell = SpreadsheetApp.getActiveSpreadsheet().getRange("A1").getValues();
var array = ["Item one", "Item two", "Item three"];
cell.setValue(array)
</code>```

I want the cell to equal "Item one, Item two, Item three" but the cell equals to "Item one" using that method.

答:
You could convert the array to a string beforehand with Array.join</p>

```<code>cell.setValue(array.join(", "));
</code>```

Body:
I am looking for a way to make a cell equal to an entire array in Google Apps Script and Google Sheets.

I have tried making the cell.setValue(array) but using this method the cell is equal to the first array item only.

var cell = SpreadsheetApp.getActiveSpreadsheet().getRange("A1").getValues();
var array = ["Item one", "Item two", "Item three"];
cell.setValue(array)

I want the cell to equal "Item one, Item two, Item three" but the cell equals to "Item one" using that method.

Body:
You could convert the array to a string beforehand with Array.join

cell.setValue(array.join(", "));


问:
capturing keys pressed on the keyboard in mfc application
I am new to mfc. I have created an mfc application, I am trying to capture if character keys were pressed.
I have added ON_WM_CHAR to the message map and have written an onChar function to perform some function when a particular character is pressed.

But even if any character is pressed, I do not reach my onChar function.

答: What class's OnChar have you overloaded? Most such input should typically be handled in a view class.</p>

ContentLicense: CC BY-SA 3.0


答:
You can use toString()

```<code>var array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// output: "1,2,a,1a"
</code>```

From: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/toString

Title: How could I make a cell contain an entire array?

Body:
You can use toString()

var array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// output: "1,2,a,1a"

From: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/toString


问:
ValueError: Input contains NaN, infinity or a value too large for dtype
Can anyone help me with my model?

I've performed EDA and data cleaning, but when i get to model prediction i get the following error. This happens for Lasso and Linear Regression

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

Can anyone help me with whats happening? How do i solve it?

Tried removing NaN values but still couldn't solve the problem.

```<code>#!/usr/bin/env python
# coding: utf-8

# In[1]:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# In[2]:

df = pd.read_csv('train.csv')

# In[3]:

display(df)

# In[4]:

df.describe()

# In[5]:

df.count().plot(kind='barh',figsize=(10,50))

# In[6]:

df.shape

# In[7]:

#Completing the variables with NaN values
df.columns
df.describe()

# In[8]:

df['MiscFeature']= df['MiscFeature'].fillna('None')
df['Fence'] = df['Fence'].fillna('None')
df['PoolQC'] = df['PoolQC'].fillna('None')
df['GarageCond'] = df['GarageCond'].fillna('None')
df['GarageQual'] = df['GarageQual'].fillna('None')
df['GarageFinish'] = df['GarageFinish'].fillna('None')
df['GarageYrBlt'] = df['GarageYrBlt'].fillna('None')
df['GarageQual'] = df['GarageQual'].fillna('None')
df['GarageType'] = df['GarageType'].fillna('None')
df['FireplaceQu'] = df['FireplaceQu'].fillna('None')
df['YearBuilt'] = df['YearBuilt'].fillna('None')
df['YearRemodAdd'] = df['YearRemodAdd'].fillna('None')
df['BsmtFinType2'] = df['BsmtFinType2'].fillna('None')
df['BsmtFinType1'] = df['BsmtFinType1'].fillna('None')
df['BsmtFinType2'] = df['BsmtFinType2'].fillna('None')
df['BsmtExposure'] = df['BsmtExposure'].fillna('None')
df['BsmtQual'] = df['BsmtQual'].fillna('None')
df['BsmtCond'] = df['BsmtCond'].fillna('None')
df['MasVnrType'] = df['MasVnrType'].fillna('None')
df['Alley'] = df['Alley'].fillna('None')

# In[9]:

df['MSSubClass'] = df['MSSubClass'].astype(str)
df['MSZoning'] = df['MSZoning'].astype(str)

# In[10]:

df['LotFrontage'] = df['LotFrontage'].fillna(df['LotFrontage'].mode()[0])

# In[11]:

df['BsmtFinSF1'] = df['BsmtFinSF1'].fillna(0)
df['BsmtFinSF2'] = df['BsmtFinSF2'].fillna(0)
df['BsmtUnfSF'] = df['BsmtUnfSF'].fillna(0)
df['MasVnrArea'] = df['MasVnrArea'].fillna(0)

# In[12]:

df.count().plot(kind='barh',figsize=(15,15))

# In[13]:

plt.figure(figsize=(30,15))
sns.heatmap(df.corr(), annot = True)

# In[14]:

df.corr()

# In[15]:

x = pd.get_dummies(df.drop("SalePrice", axis=1))
y = df['SalePrice']

# In[16]:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.33)

# In[17]:

from sklearn.linear_model import LinearRegression
model = LinearRegression()

# In[18]:

model.fit(X_train,y_train)

# In[19]:

model.score(X_train,y_train)

# In[20]:

result = model.predict(X_test)

# In[21]:

from sklearn import metrics

# In[22]:

print(np.sqrt(metrics.mean_squared_error(y_test,result)))
print(np.mean(y_test))
print(metrics.mean_absolute_error(y_test,result))

# In[23]:

compare = pd.DataFrame(result,y_test)

# In[24]:

error = np.mean(y_test-result)
print(error)

# In[25]:

#Now applying same model to test set

# In[26]:

dftest = pd.read_csv('test.csv')

# In[27]:

dftest.count().plot(kind='barh',figsize=(10,50))

# In[28]:

#Completing the variables with NaN values
dftest.describe()

# In[29]:

dftest['MiscFeature']= dftest['MiscFeature'].fillna('None')
dftest['Fence'] = dftest['Fence'].fillna('None')
dftest['PoolQC'] = dftest['PoolQC'].fillna('None')
dftest['GarageCond'] = dftest['GarageCond'].fillna('None')
dftest['GarageQual'] = dftest['GarageQual'].fillna('None')
dftest['GarageFinish'] = dftest['GarageFinish'].fillna('None')
dftest['GarageYrBlt'] = dftest['GarageYrBlt'].fillna('None')
dftest['GarageQual'] = dftest['GarageQual'].fillna('None')
dftest['GarageType'] = dftest['GarageType'].fillna('None')
dftest['FireplaceQu'] = dftest['FireplaceQu'].fillna('None')
dftest['YearBuilt'] = dftest['YearBuilt'].fillna('None')
dftest['YearRemodAdd'] = dftest['YearRemodAdd'].fillna('None')
dftest['BsmtFinType2'] = dftest['BsmtFinType2'].fillna('None')
dftest['BsmtFinType1'] = dftest['BsmtFinType1'].fillna('None')
dftest['BsmtFinType2'] = dftest['BsmtFinType2'].fillna('None')
dftest['BsmtExposure'] = dftest['BsmtExposure'].fillna('None')
dftest['BsmtQual'] = dftest['BsmtQual'].fillna('None')
dftest['BsmtCond'] = dftest['BsmtCond'].fillna('None')
dftest['MasVnrType'] = dftest['MasVnrType'].fillna('None')
dftest['Alley'] = dftest['Alley'].fillna('None')

# In[30]:

dftest['MSSubClass'] = dftest['MSSubClass'].astype(str)
dftest['MSZoning'] = dftest['MSZoning'].astype(str)

# In[31]:

dftest['LotFrontage'] = dftest['LotFrontage'].fillna(dftest['LotFrontage'].mode()[0])

# In[32]:

dftest['BsmtFinSF1'] = dftest['BsmtFinSF1'].fillna(0)
dftest['BsmtFinSF2'] = dftest['BsmtFinSF2'].fillna(0)
dftest['BsmtUnfSF'] = dftest['BsmtUnfSF'].fillna(0)
dftest['MasVnrArea'] = dftest['MasVnrArea'].fillna(0)

# In[33]:

#Confirming that all values are filled, no NaN values
dftest.count().plot(kind='barh',figsize=(15,15))

# In[34]:

xtest = pd.get_dummies(dftest)

# In[35]:

testresult = model.predict(xtest)

# In[ ]:
</code>```

答:
You cannot train/test your model if there's a None/Nan Value you need to remove them from the datafram

use dropna method in pandas (it return a new dataframe, doesn't affect the original one)

```<code>df=df.dropna(YOUR_DATA_FRAME)
</code>```

for more info check the docs for pandas link

Body:
Can anyone help me with my model?

I've performed EDA and data cleaning, but when i get to model prediction i get the following error. This happens for Lasso and Linear Regression

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

Can anyone help me with whats happening? How do i solve it?

Tried removing NaN values but still couldn't solve the problem.

#!/usr/bin/env python
# coding: utf-8

# In[1]:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# In[2]:

df = pd.read_csv('train.csv')

# In[3]:

display(df)

# In[4]:

df.describe()

# In[5]:

df.count().plot(kind='barh',figsize=(10,50))

# In[6]:

df.shape

# In[7]:

#Completing the variables with NaN values
df.columns
df.describe()

# In[8]:

df['MiscFeature']= df['MiscFeature'].fillna('None')
df['Fence'] = df['Fence'].fillna('None')
df['PoolQC'] = df['PoolQC'].fillna('None')
df['GarageCond'] = df['GarageCond'].fillna('None')
df['GarageQual'] = df['GarageQual'].fillna('None')
df['GarageFinish'] = df['GarageFinish'].fillna('None')
df['GarageYrBlt'] = df['GarageYrBlt'].fillna('None')
df['GarageQual'] = df['GarageQual'].fillna('None')
df['GarageType'] = df['GarageType'].fillna('None')
df['FireplaceQu'] = df['FireplaceQu'].fillna('None')
df['YearBuilt'] = df['YearBuilt'].fillna('None')
df['YearRemodAdd'] = df['YearRemodAdd'].fillna('None')
df['BsmtFinType2'] = df['BsmtFinType2'].fillna('None')
df['BsmtFinType1'] = df['BsmtFinType1'].fillna('None')
df['BsmtFinType2'] = df['BsmtFinType2'].fillna('None')
df['BsmtExposure'] = df['BsmtExposure'].fillna('None')
df['BsmtQual'] = df['BsmtQual'].fillna('None')
df['BsmtCond'] = df['BsmtCond'].fillna('None')
df['MasVnrType'] = df['MasVnrType'].fillna('None')
df['Alley'] = df['Alley'].fillna('None')

# In[9]:

df['MSSubClass'] = df['MSSubClass'].astype(str)
df['MSZoning'] = df['MSZoning'].astype(str)

# In[10]:

df['LotFrontage'] = df['LotFrontage'].fillna(df['LotFrontage'].mode()[0])

# In[11]:

df['BsmtFinSF1'] = df['BsmtFinSF1'].fillna(0)
df['BsmtFinSF2'] = df['BsmtFinSF2'].fillna(0)
df['BsmtUnfSF'] = df['BsmtUnfSF'].fillna(0)
df['MasVnrArea'] = df['MasVnrArea'].fillna(0)

# In[12]:

df.count().plot(kind='barh',figsize=(15,15))

# In[13]:

plt.figure(figsize=(30,15))
sns.heatmap(df.corr(), annot = True)

# In[14]:

df.corr()

# In[15]:

x = pd.get_dummies(df.drop("SalePrice", axis=1))
y = df['SalePrice']

# In[16]:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.33)

# In[17]:

from sklearn.linear_model import LinearRegression
model = LinearRegression()

# In[18]:

model.fit(X_train,y_train)

# In[19]:

model.score(X_train,y_train)

# In[20]:

result = model.predict(X_test)

# In[21]:

from sklearn import metrics

# In[22]:

print(np.sqrt(metrics.mean_squared_error(y_test,result)))
print(np.mean(y_test))
print(metrics.mean_absolute_error(y_test,result))

# In[23]:

compare = pd.DataFrame(result,y_test)

# In[24]:

error = np.mean(y_test-result)
print(error)

# In[25]:

#Now applying same model to test set

# In[26]:

dftest = pd.read_csv('test.csv')

# In[27]:

dftest.count().plot(kind='barh',figsize=(10,50))

# In[28]:

#Completing the variables with NaN values
dftest.describe()

# In[29]:

dftest['MiscFeature']= dftest['MiscFeature'].fillna('None')
dftest['Fence'] = dftest['Fence'].fillna('None')
dftest['PoolQC'] = dftest['PoolQC'].fillna('None')
dftest['GarageCond'] = dftest['GarageCond'].fillna('None')
dftest['GarageQual'] = dftest['GarageQual'].fillna('None')
dftest['GarageFinish'] = dftest['GarageFinish'].fillna('None')
dftest['GarageYrBlt'] = dftest['GarageYrBlt'].fillna('None')
dftest['GarageQual'] = dftest['GarageQual'].fillna('None')
dftest['GarageType'] = dftest['GarageType'].fillna('None')
dftest['FireplaceQu'] = dftest['FireplaceQu'].fillna('None')
dftest['YearBuilt'] = dftest['YearBuilt'].fillna('None')
dftest['YearRemodAdd'] = dftest['YearRemodAdd'].fillna('None')
dftest['BsmtFinType2'] = dftest['BsmtFinType2'].fillna('None')
dftest['BsmtFinType1'] = dftest['BsmtFinType1'].fillna('None')
dftest['BsmtFinType2'] = dftest['BsmtFinType2'].fillna('None')
dftest['BsmtExposure'] = dftest['BsmtExposure'].fillna('None')
dftest['BsmtQual'] = dftest['BsmtQual'].fillna('None')
dftest['BsmtCond'] = dftest['BsmtCond'].fillna('None')
dftest['MasVnrType'] = dftest['MasVnrType'].fillna('None')
dftest['Alley'] = dftest['Alley'].fillna('None')

# In[30]:

dftest['MSSubClass'] = dftest['MSSubClass'].astype(str)
dftest['MSZoning'] = dftest['MSZoning'].astype(str)

# In[31]:

dftest['LotFrontage'] = dftest['LotFrontage'].fillna(dftest['LotFrontage'].mode()[0])

# In[32]:

dftest['BsmtFinSF1'] = dftest['BsmtFinSF1'].fillna(0)
dftest['BsmtFinSF2'] = dftest['BsmtFinSF2'].fillna(0)
dftest['BsmtUnfSF'] = dftest['BsmtUnfSF'].fillna(0)
dftest['MasVnrArea'] = dftest['MasVnrArea'].fillna(0)

# In[33]:

#Confirming that all values are filled, no NaN values
dftest.count().plot(kind='barh',figsize=(15,15))

# In[34]:

xtest = pd.get_dummies(dftest)

# In[35]:

testresult = model.predict(xtest)

# In[ ]:

Body:
You cannot train/test your model if there's a None/Nan Value you need to remove them from the datafram

use dropna method in pandas (it return a new dataframe, doesn't affect the original one)

df=df.dropna(YOUR_DATA_FRAME)

for more info check the docs for pandas link


问:
Maatwebsite Excel load function not working
```<code>$file = $request->file('excel');
$reader = Excel::load($file->getRealPath())->get();
</code>```

The following error appears:

Call to undefined method Maatwebsite\Excel\Facades\Excel::load()

I am using Maatwebsite 3 in laravel 5.7

答:
The load method has been removed as quoted in the las post, however it has been already implemented in 3.1 version.

Excel::load() is removed and replaced by Excel::import($yourImport)

Checkout this link

Personally, I ended it up using Excel::toColletion($file) though.

Body:
$file = $request->file('excel');
$reader = Excel::load($file->getRealPath())->get();

The following error appears:

Call to undefined method Maatwebsite\Excel\Facades\Excel::load()

I am using Maatwebsite 3 in laravel 5.7


问:
How to load data from E-goi using REST API google script
I want to access data from e-goi API and in documentation I got a .jar file. There are no examples with RESP API so I don't know how access it directly.
As I'm new to this kind of program, I would like some help to access the data directly using REST API google script program.

I tried this code:

```<code>function myFunction() {
  var url = 'http://api.e-goi.com/v2/rest.php?apikey=04cc5ea9d2d266a376c07ff4f12e077be40bbf51&method=getUserData';
  var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
  //var data = JSON.parse(response);
  Logger.log(responAccording to the se);
}
</code>```

And I got this response:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Egoi_Api generator="zend" version="1.0"><getUserData><response>NO_USERNAME_AND_PASSWORD_AND_APIKEY</response><status>success</status></getUserData></Egoi_Api>
</code>```

According to the E-goi API, the method getUserData don't need username ou password, only the apikey that is already in the command.

What am I doing wrong?

答:
Java is not JavaScript. You can't simply run Java code inside Javascript.

It looks like you want to access the RESTful API using Google Apps Script, not use the Java wrapper provided by e-goi. This is possible using UrlFetch on the API provided; see Google's guide on External APIs for general information on how to make an API request, and e-goi's documentation for information specific to using their API. Especially note the required query parameters for each potential API method (e.g., API key) and how those can be included in your url in fetch()

Body:
I want to access data from e-goi API and in documentation I got a .jar file. There are no examples with RESP API so I don't know how access it directly.
As I'm new to this kind of program, I would like some help to access the data directly using REST API google script program.

I tried this code:

function myFunction() {
  var url = 'http://api.e-goi.com/v2/rest.php?apikey=04cc5ea9d2d266a376c07ff4f12e077be40bbf51&method=getUserData';
  var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
  //var data = JSON.parse(response);
  Logger.log(responAccording to the se);
}

And I got this response:

<?xml version="1.0" encoding="UTF-8"?>
<Egoi_Api generator="zend" version="1.0"><getUserData><response>NO_USERNAME_AND_PASSWORD_AND_APIKEY</response><status>success</status></getUserData></Egoi_Api>

According to the E-goi API, the method getUserData don't need username ou password, only the apikey that is already in the command.

What am I doing wrong?


问:
pgbouncer - auroraDB cluster not load balancing correctly
I as using AuroraDB cluster with 2 readers and pgBouncer to maintain a connection pool.

My application is very read intensive and fires a lot of select queries.

the problem I am facing is my 2 read replicas are not getting used completely in parallel.

I can see the trends where all connections get moved to 1 replica where other replica is serving 0 connections and after some time the situation shift when 2nd replica serves all connections and 1st serves 0.

I investigated this and found that auroraDB cluster load balancing is done on by time slicing 1-second intervals.

My guess is when pgBouncer creates connection pool all connection are created within 1 second window and all connections end up on 1 read replica.

is there any way I can correct this?

答:
The DB Endpoint is a Route 53 DNS and load balancing is done basically via DNS round robin, each time you resolve the DNS. When you use pgBouncer, is it resolving the DNS once and trying to open connections to the resolved IP? If yes, then this is expected that all your connections are resolved to the same instance. You could fix this conceptually in multiple ways (I'm not too familiar with pgBouncer), but you basically need to somehow make the library resolve the DNS explicitly for each connection, or explicitly add all the instance endpoints to the configuration. The latter is not recommended if you plan on issuing writes using this Connection pool. You don't have any control over who stays as the writer, so you may inadvertently end up sending your writes to a replica.

AuroraDB cluster load balancing is done on by time slicing 1-second intervals
  I'm not too sure where you read that. Could you share some references?


问:
system function flaws
We are using C in Linux. Is there any possibility that system() function can behave in an unexpected manner, especially when we handle signals?

We found that sometimes, the system() function blocks the execution or it throws SIGSEGV.

e.g:

```<code>system ( "/bin/mv a b" );
</code>```

Are there any known flaws in using system() that would explain this?

答:
The system() call is supposed to block until execution is finished. If it takes an hour to move a to b, the process or thread calling system() will block for an hour. Knowing this, strange behavior can be explained.

If you expect system() to return immediately, it probably means that you expect code that runs after calling it to have been entered by the time you see the strange behavior. It is very likely that, due to system() taking longer than expected, some area of memory wasn't allocated or initialized. This is likely the cause of the segmentation fault when another thread or process tried to access it.

In other words, if you didn't expect system() to block, you probably assumed that code coming after it would run much sooner than it actually did.

Debunking that would be a topic for another question. The answer to this one is no, you aren't seeing flaws in the system() function, it is behaving exactly as expected.

Title: system function flaws

Body:
We are using C in Linux. Is there any possibility that system() function can behave in an unexpected manner, especially when we handle signals?

We found that sometimes, the system() function blocks the execution or it throws SIGSEGV.

e.g:

system ( "/bin/mv a b" );

Are there any known flaws in using system() that would explain this?


问:
Python merging multiple files to single csv file efficient
I have a set of files and want to merge them to a single CSV file (one matrix).
Bute, there are some Problems.

The files are not CSV files

The files do not have the same columns

I do not know the columns

There are a lot of files (over 100,000)

Inside every file are the names of the columns that should get the value 1 in the matrix.
Example:

```<code>#File Alpha
dog
house
car

#File Beta
dog
cat

#resulting matrix
,dog,house,car,cat
Alpha,1,1,1,0
Beta,1,0,0,1
</code>```

After some research I came up with the following Idea:

```<code>import pandas
import os
import shutil

df = pandas.DataFrame()
df['dir'] = 0

directory_0 = os.fsencode("direc0")

for file in os.listdir(directory_0):
    filename = os.fsdecode(file)
    df.append(pandas.Series( name = filename))
    with open("direc10{}".format(filename), "r") as f:
        for line in f:
            if len(line[:-1]) > 0:
                if line[:-1] in df.columns:
                    df.loc[filename, line[:-1]] = 1
                else:
                    df[line[:-1]] = 0
                    df.loc[filename, line[:-1]] = 1
df.fillna(0, inplace=True)
df.to_csv("dataset.csv")
</code>```

Some Comments

There are two directories. The 'dir' column is for the number of the directory (0 or 1). I cut the code for the second directory because it is identical (just with another number for the directory)

line[:-1] because there is a "\n" I do not want

Problem
This code does the work, but it needs a way to long.

```<code>#Runtime for the above code
500 files after 17 seconds
1,000 files after 50 seconds
1,500 files after 111 seconds
2,000 files after 203 seconds
2,500 files after 324 seconds
3,000 files after 489 seconds
3,500 files after 695 seconds
4,000 files after 960 seconds
</code>```

Is there a way to do this way faster (100,000 files in a couple of hours)?

Thanks in advance :)

PS: Pls excuse my English, it is not my first Language

答:
100.000 rows are not the kind of size that is easily dealt with CSV files - you will loose a lot - keping this data structure in an SQL database would be far more efficient.

Also, what makes this be less efficient is that Pandas search for column names is linear, and when you get to a few thousand words, the if line[:-1] in df.columns run for each file line will start to take its burden.

Also, for ~100000 files, even os.listdir might be slow - pathlib.Path.iterdir might be faster.

Anyway, building this as a Python dictionary, which has O(1) time to get to the keys will be a lot faster. You can make that into a dataframe later, or record the information in a CSV file directly if it is really needed.

```<code>import pathlib

dir1 = pathlib.Path("direc0")  # Pathlib will also take care of filesystem filename encodings

data = {}

for filepath in dir1.iterdir():
    for line in filepath.open():
        line = line.strip()
        data.setdefault(line, set()).add(filepath.name)
</code>```

At this point you have all data in memory, with the words as keys and a set of the filenames that contain each word as value.

To write the CSV file directly, this code should suffice - since
all data is in memory and the code avoids linear search, this should be fast enough. The problem is if the data does not fit in memory in first place.

```<code>import csv
from collections import defaultdict

transposed = {}
for key, values in data.items():
    for value in values:
        transposed.set_default(value, set()).add(key)

with open("dataset.csv", "wt") as file:
    writer = csv.writer(file)
    headers = list(data.keys())

    writer.writerow(["file",] + headers)
    for key, values in transposed.items():
        writer.writerow([key,] + [int(word in values) for word in headers ])
</code>```

Body:
I have a set of files and want to merge them to a single CSV file (one matrix).
Bute, there are some Problems.

The files are not CSV files

The files do not have the same columns

I do not know the columns

There are a lot of files (over 100,000)

Inside every file are the names of the columns that should get the value 1 in the matrix.
Example:

#File Alpha
dog
house
car

#File Beta
dog
cat

#resulting matrix
,dog,house,car,cat
Alpha,1,1,1,0
Beta,1,0,0,1

After some research I came up with the following Idea:

import pandas
import os
import shutil

df = pandas.DataFrame()
df['dir'] = 0

directory_0 = os.fsencode("direc0")

for file in os.listdir(directory_0):
    filename = os.fsdecode(file)
    df.append(pandas.Series( name = filename))
    with open("direc10{}".format(filename), "r") as f:
        for line in f:
            if len(line[:-1]) > 0:
                if line[:-1] in df.columns:
                    df.loc[filename, line[:-1]] = 1
                else:
                    df[line[:-1]] = 0
                    df.loc[filename, line[:-1]] = 1
df.fillna(0, inplace=True)
df.to_csv("dataset.csv")

Some Comments

There are two directories. The 'dir' column is for the number of the directory (0 or 1). I cut the code for the second directory because it is identical (just with another number for the directory)

line[:-1] because there is a "\n" I do not want

Problem
This code does the work, but it needs a way to long.

#Runtime for the above code
500 files after 17 seconds
1,000 files after 50 seconds
1,500 files after 111 seconds
2,000 files after 203 seconds
2,500 files after 324 seconds
3,000 files after 489 seconds
3,500 files after 695 seconds
4,000 files after 960 seconds

Is there a way to do this way faster (100,000 files in a couple of hours)?

Thanks in advance :)

PS: Pls excuse my English, it is not my first Language

Body:
100.000 rows are not the kind of size that is easily dealt with CSV files - you will loose a lot - keping this data structure in an SQL database would be far more efficient.

Also, what makes this be less efficient is that Pandas search for column names is linear, and when you get to a few thousand words, the if line[:-1] in df.columns run for each file line will start to take its burden.

Also, for ~100000 files, even os.listdir might be slow - pathlib.Path.iterdir might be faster.

Anyway, building this as a Python dictionary, which has O(1) time to get to the keys will be a lot faster. You can make that into a dataframe later, or record the information in a CSV file directly if it is really needed.

import pathlib

dir1 = pathlib.Path("direc0")  # Pathlib will also take care of filesystem filename encodings

data = {}

for filepath in dir1.iterdir():
    for line in filepath.open():
        line = line.strip()
        data.setdefault(line, set()).add(filepath.name)

At this point you have all data in memory, with the words as keys and a set of the filenames that contain each word as value.

To write the CSV file directly, this code should suffice - since
all data is in memory and the code avoids linear search, this should be fast enough. The problem is if the data does not fit in memory in first place.

import csv
from collections import defaultdict

transposed = {}
for key, values in data.items():
    for value in values:
        transposed.set_default(value, set()).add(key)

with open("dataset.csv", "wt") as file:
    writer = csv.writer(file)
    headers = list(data.keys())

    writer.writerow(["file",] + headers)
    for key, values in transposed.items():
        writer.writerow([key,] + [int(word in values) for word in headers ])


问:
.catch is not resolving error and breaking the chain
I am trying to write a file. Some files are going to be written to incorrect paths.  For each file, I need to
1. log to the console that the write is starting.
2. Write the file
3A if it is done writing, log to the console finished.
3B if it is a bad path, log to the console that the file failed

Right now, if it fails it writes both things to the console.

I've tried nesting the .thens, I've tried just call backs.

```<code>async function beginWrite(filename){
    console.log(`Creating file ${filename}`)
}

async function writeComplete(filename){
    console.log(`Finished creating file ${filename}`)
}

async function writeFile(path, filename){
    fs.writeFile(path + '/' + filename, 'this is a file', (error) => {
        if(error) {console.log(`File ${filename} failed to write`)}
    });
}

async function logAndWrite(path, filename){
    beginWrite(filename)
    .then( () => {
        writeFile(path, filename)
    }
    )
    .then(writeComplete(filename))
    .catch( (e) => {
        return console.log(`File ${filename} failed to write`)
    })
}
</code>```

I expect

File 1 writing
File 1 complete
File 2 writing
File 2 failed to write
File 3 writing
File 3 Complete

答:
You can't simply sprinkle async over your function declarations and hope for magic to happen.

async is a way to deal with Promises. It requires that you await a Promise inside the async function, which in turn requires that you actually have a function that returns a Promise. You're not doing any of this.

First you need a function that returns a Promise. Node's native asynchronous functions use callbacks and return nothing, so if you want to use the native fs.writeFile() and return a Promise instead, you need to make a wrapper function. This process is called "promisification", and when done manually, it looks like this:

```<code>function writeFileAsync(file, data){
    return new Promise(resolve => {
        fs.writeFile(file, data, err => {
            if (err) throw err; else resolve();
        })
    });
}
</code>```

Node also has a utility to do the same thing in one step for any node-style asynchronous function (util.promisify(original)).

```<code>const writeFileAsync = util.promisify(fs.writeFile);
</code>```

Now that there is something we can await, we can make an async function that awaits it (note that you absolutely need the try/catch block):

```<code>async function test() {
    try {
        let filename = 'some/file';
        console.log(`Creating file ${filename}`)
        await writeFileAsync(filename, 'this is a file');
        console.log(`Finished creating file ${filename}`)
    } catch (err) {
        console.log(`File ${filename} failed to write`);
        console.log(err);
    }
}
</code>```

or we can use it with the equivalent regular .then() and .catch() semantics of Promises:

```<code>let filename = 'some/file';
console.log(`Creating file ${filename}`);
writeFileAsync(filename, 'this is a file')
    .then(() => {
        console.log(`Finished creating file ${filename}`
    })
    .catch((err) => {
        console.log(`File ${filename} failed to write`);
        console.log(err);
    });
</code>```

Body:
I am trying to write a file. Some files are going to be written to incorrect paths.  For each file, I need to
1. log to the console that the write is starting.
2. Write the file
3A if it is done writing, log to the console finished.
3B if it is a bad path, log to the console that the file failed

Right now, if it fails it writes both things to the console.

I've tried nesting the .thens, I've tried just call backs.

async function beginWrite(filename){
    console.log(`Creating file ${filename}`)
}

async function writeComplete(filename){
    console.log(`Finished creating file ${filename}`)
}

async function writeFile(path, filename){
    fs.writeFile(path + '/' + filename, 'this is a file', (error) => {
        if(error) {console.log(`File ${filename} failed to write`)}
    });
}

async function logAndWrite(path, filename){
    beginWrite(filename)
    .then( () => {
        writeFile(path, filename)
    }
    )
    .then(writeComplete(filename))
    .catch( (e) => {
        return console.log(`File ${filename} failed to write`)
    })
}

I expect

File 1 writing
File 1 complete
File 2 writing
File 2 failed to write
File 3 writing
File 3 Complete

Body:
You can't simply sprinkle async over your function declarations and hope for magic to happen.

async is a way to deal with Promises. It requires that you await a Promise inside the async function, which in turn requires that you actually have a function that returns a Promise. You're not doing any of this.

First you need a function that returns a Promise. Node's native asynchronous functions use callbacks and return nothing, so if you want to use the native fs.writeFile() and return a Promise instead, you need to make a wrapper function. This process is called "promisification", and when done manually, it looks like this:

function writeFileAsync(file, data){
    return new Promise(resolve => {
        fs.writeFile(file, data, err => {
            if (err) throw err; else resolve();
        })
    });
}

Node also has a utility to do the same thing in one step for any node-style asynchronous function (util.promisify(original)).

const writeFileAsync = util.promisify(fs.writeFile);

Now that there is something we can await, we can make an async function that awaits it (note that you absolutely need the try/catch block):

async function test() {
    try {
        let filename = 'some/file';
        console.log(`Creating file ${filename}`)
        await writeFileAsync(filename, 'this is a file');
        console.log(`Finished creating file ${filename}`)
    } catch (err) {
        console.log(`File ${filename} failed to write`);
        console.log(err);
    }
}

or we can use it with the equivalent regular .then() and .catch() semantics of Promises:

let filename = 'some/file';
console.log(`Creating file ${filename}`);
writeFileAsync(filename, 'this is a file')
    .then(() => {
        console.log(`Finished creating file ${filename}`
    })
    .catch((err) => {
        console.log(`File ${filename} failed to write`);
        console.log(err);
    });


问:
Django-vote implementation for comment up/down voting system
I am new to Django, and I am trying to implement up/downvotes in a comments app I am building, using django-vote: https://github.com/shanbay/django-vote
for the implementation. However, either I am not understanding the django-vote documentation correctly or my implementation is faulty. I've looked through the source code for django-vote on its github but to no avail.

I've tried tracing back the faults by having the code print to console at each step, and it seems like the django-vote app isnt actually logging the votes. If that is the case I may just try to build another one from scratch, but am not sure.

```<code> HTML for the vote buttons:
     <i class=" vote upvote increment fas fa-chevron-circle-up" data-userid ="{{ request.user.id }}" data-commentid="{{ comment.id }}" data-action='UP' ></i>

     <i class="vote downvote increment fas fa-chevron-circle-down" data-userid ="{{ request.user.id }}" data-commentid="{{ comment.id }}" data-action='DOWN'></i>

JS:
$(".increment").click(function(event){
  var v = $(this);
  var action = v.data('action');
  var commentID = v.data('commentid');
  var userID = v.data('userid');
  console.log("vote submitted");
  console.log(commentID);
  console.log(action);
  console.log(userID);
  $.ajax({
    url: "/comments/vote/",
    data: { 'csrfmiddlewaretoken' : '{{ csrf_token }}', commentID: commentID,
     action: action, userID : userID, },
    type: 'POST',
    success: function (data) {

      console.log(data);
     console.log("vote success")},
    error: function() {
      console.log('vote failure')
    }
  });

});
Django view function:
@login_required
@require_POST
def comment_vote(request):
    if request.method == 'POST':
        voting_user = request.POST.get('userID')
        comment_id = request.POST.get('commentID')
        voteAction = request.POST.get('action')
        comment = Comment.objects.get(pk=comment_id)

        if voteAction == 'UP':
            comment.votes.up(user_id= voting_user)
        elif voteAction == 'DOWN':
            comment.votes.down(voting_user)
        comment.total_score = comment.calculate_vote_score
        comment.save()
        data = {'user' : voting_user, 'vote' : voteAction,'comment' : comment_id, }
        return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type="application/json")
</code>```

答:
I'm not sure what the following line does, although I see what you want to accomplish:

```<code>comment.votes.up(user_id= voting_user)
</code>```

Assuming you are actually getting the data in your view, try this:

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

comment = Comment.objects.get(pk=comment_id)
if voteAction = 'UP':
    comment.update(vote_count_column = F('vote_count_column') + 1)
elif voteAction = 'DOWN':
    comment.update(vote_count_column = F('vote_count_column') - 1)
</code>```

where vote_count_column is an integer column that holds the vote count.

If that doesn't work, let me know.  I have more ideas.

Body:
I am new to Django, and I am trying to implement up/downvotes in a comments app I am building, using django-vote: https://github.com/shanbay/django-vote
for the implementation. However, either I am not understanding the django-vote documentation correctly or my implementation is faulty. I've looked through the source code for django-vote on its github but to no avail.

I've tried tracing back the faults by having the code print to console at each step, and it seems like the django-vote app isnt actually logging the votes. If that is the case I may just try to build another one from scratch, but am not sure.

 HTML for the vote buttons:

JS:
$(".increment").click(function(event){
  var v = $(this);
  var action = v.data('action');
  var commentID = v.data('commentid');
  var userID = v.data('userid');
  console.log("vote submitted");
  console.log(commentID);
  console.log(action);
  console.log(userID);
  $.ajax({
    url: "/comments/vote/",
    data: { 'csrfmiddlewaretoken' : '{{ csrf_token }}', commentID: commentID,
     action: action, userID : userID, },
    type: 'POST',
    success: function (data) {

      console.log(data);
     console.log("vote success")},
    error: function() {
      console.log('vote failure')
    }
  });

});
Django view function:
@login_required
@require_POST
def comment_vote(request):
    if request.method == 'POST':
        voting_user = request.POST.get('userID')
        comment_id = request.POST.get('commentID')
        voteAction = request.POST.get('action')
        comment = Comment.objects.get(pk=comment_id)

        if voteAction == 'UP':
            comment.votes.up(user_id= voting_user)
        elif voteAction == 'DOWN':
            comment.votes.down(voting_user)
        comment.total_score = comment.calculate_vote_score
        comment.save()
        data = {'user' : voting_user, 'vote' : voteAction,'comment' : comment_id, }
        return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type="application/json")

Body:
I'm not sure what the following line does, although I see what you want to accomplish:

comment.votes.up(user_id= voting_user)

Assuming you are actually getting the data in your view, try this:

from django.db.models import F

comment = Comment.objects.get(pk=comment_id)
if voteAction = 'UP':
    comment.update(vote_count_column = F('vote_count_column') + 1)
elif voteAction = 'DOWN':
    comment.update(vote_count_column = F('vote_count_column') - 1)

where vote_count_column is an integer column that holds the vote count.

If that doesn't work, let me know.  I have more ideas.


问:
IllegalArgumentException: Unable to locate adb in Android Studio v2.3
Does anyone know how to fix this?

```<code>IllegalArgumentException: Unable to locate adb
</code>```

I installed android studio v2.3 and it won't let me run my app saying the error.
I searched online and said to click the  Launch Standalone Sdk manager but I am unable to locate it.

答:
I had a similar problem a while ago, you can try some things like:

you install the avast antivirus

if that is not the problem then:

You have to download the ADB.EXE again via the page
and download according to your operating system

then copy the ADB.exe from that downloaded file

```<code>C:> Users> name> Downloads> platform-tools
</code>```

  -and copy it on the path where you have the platform-tools of your android Studio
in my case it is:

C:> Users> name> AppData> Local> Android> sdk> platform-tools

and that's all I hope to help you, regards :)

Body:
Does anyone know how to fix this?

IllegalArgumentException: Unable to locate adb

I installed android studio v2.3 and it won't let me run my app saying the error.
I searched online and said to click the  Launch Standalone Sdk manager but I am unable to locate it.

Body:
I had a similar problem a while ago, you can try some things like:

you install the avast antivirus

if that is not the problem then:

You have to download the ADB.EXE again via the page
and download according to your operating system

then copy the ADB.exe from that downloaded file

C:> Users> name> Downloads> platform-tools

  -and copy it on the path where you have the platform-tools of your android Studio
in my case it is:

C:> Users> name> AppData> Local> Android> sdk> platform-tools

and that's all I hope to help you, regards :)


问:
C#~How to read MultiLevelPointer?
I'm struggling a bit on this part...
I want to do this in CE!(that is read the value 20 in my c# app)

However my code is not working...

```<code>[DllImport("kernel32.dll")]
        public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int dwSize, ref IntPtr lpNumberOfBytesRead);

public int ReadInt32(IntPtr address, int[] pointers)
{
    /* FOR REFERENCE ONLY! PSEUDO-CODE
        ReadProcessMemory(..., ModuleBaseAddress + 0x010F418, Temporary, ..., ...); // -> 0x02A917F8
        ReadProcessMemory(..., 0x02A917F8+0x48, Temporary,  .....,.); // -> 0x02A9A488
        [02A9A488] = 20
     */

    IntPtr bytesRead = IntPtr.Zero;
    byte[] _buff = new byte[sizeof(int)];
    int offIndex = 0;
    IntPtr finalval = address;
    Console.WriteLine("[BASE] {0:x}", (int)address);
    foreach(int PointerOffs in pointers)
    {
        ReadProcessMemory(hProcess, address, _buff, _buff.Length, ref bytesRead);
        finalval += pointers[offIndex];

        Console.WriteLine("[Curr ADDRESS] {0:x}", finalval);
        offIndex++;
    }

    return BitConverter.ToInt32(_buff, 0);
}
</code>```

And this is how I access the method:

```<code> int currAmmo = (int) pReader.ReadInt32((IntPtr)LocalPlayer.BaseAddress, LocalPlayer.oMGAmmo);
            Console.Write("[AMMO] {0}\n", currAmmo);
</code>```

答:
Your function has enough problems to warrant a replacement, I tried to fix it but it was easier just to start fresh.  By utilizing a pre increment instead of a post increment you will de-reference the first pointer before adding an offset which is ideal.

public static int ReadInt32(IntPtr hProc, IntPtr ptr, int[] offsets)
{
    IntPtr addr = ptr;
    var buffer = new byte[4];

    for (int i = 0; i < offsets.Length; ++i)
    {
        ReadProcessMemory(hProc, addr, buffer, buffer.Length, out var read1);
        addr = IntPtr.Add(new IntPtr(BitConverter.ToInt32(buffer, 0)), offsets[i]);
    }

    ReadProcessMemory(hProc, addr, buffer, 4, out var read);

    return BitConverter.ToInt32(buffer, 0);

}
```

I learned C# today just to answer this question :)

Title: C#~How to read MultiLevelPointer?

Body:
I'm struggling a bit on this part...
I want to do this in CE!(that is read the value 20 in my c# app)

However my code is not working...

[DllImport("kernel32.dll")]
        public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int dwSize, ref IntPtr lpNumberOfBytesRead);

public int ReadInt32(IntPtr address, int[] pointers)
{
    /* FOR REFERENCE ONLY! PSEUDO-CODE
        ReadProcessMemory(..., ModuleBaseAddress + 0x010F418, Temporary, ..., ...); // -> 0x02A917F8
        ReadProcessMemory(..., 0x02A917F8+0x48, Temporary,  .....,.); // -> 0x02A9A488
        [02A9A488] = 20
     */

    IntPtr bytesRead = IntPtr.Zero;
    byte[] _buff = new byte[sizeof(int)];
    int offIndex = 0;
    IntPtr finalval = address;
    Console.WriteLine("[BASE] {0:x}", (int)address);
    foreach(int PointerOffs in pointers)
    {
        ReadProcessMemory(hProcess, address, _buff, _buff.Length, ref bytesRead);
        finalval += pointers[offIndex];

        Console.WriteLine("[Curr ADDRESS] {0:x}", finalval);
        offIndex++;
    }

    return BitConverter.ToInt32(_buff, 0);
}

And this is how I access the method:

 int currAmmo = (int) pReader.ReadInt32((IntPtr)LocalPlayer.BaseAddress, LocalPlayer.oMGAmmo);
            Console.Write("[AMMO] {0}\n", currAmmo);

Body:
Your function has enough problems to warrant a replacement, I tried to fix it but it was easier just to start fresh.  By utilizing a pre increment instead of a post increment you will de-reference the first pointer before adding an offset which is ideal.

public static int ReadInt32(IntPtr hProc, IntPtr ptr, int[] offsets)
{
    IntPtr addr = ptr;
    var buffer = new byte[4];

    for (int i = 0; i < offsets.Length; ++i)
    {
        ReadProcessMemory(hProc, addr, buffer, buffer.Length, out var read1);
        addr = IntPtr.Add(new IntPtr(BitConverter.ToInt32(buffer, 0)), offsets[i]);
    }

    ReadProcessMemory(hProc, addr, buffer, 4, out var read);

    return BitConverter.ToInt32(buffer, 0);

}

I learned C# today just to answer this question :)


问:
What's "requestCode" used for on PendingIntent?
Background:

I'm using PendingIntent for alarms via AlarmManager.

The problem:

At first I thought that in order to cancel previous ones, I must provide the exact requestCode that I've used before to start the alarm.

But then I've found out I was wrong, as the cancellation API says:

Remove any alarms with a matching Intent. Any alarm, of any type,
  whose Intent matches this one (as defined by filterEquals(Intent)),
  will be canceled.

looking at "filterEquals", the documentation says:

Determine if two intents are the same for the purposes of intent
  resolution (filtering). That is, if their action, data, type, class,
  and categories are the same. This does not compare any extra data
  included in the intents.

so I don't get what the "requestCode" is for...

The question:

What is "requestCode" used for?

What if I create multiple alarms with the same "requestCode" ? do they override each other?

答:
one important thing about requestCode that will seriously trouble your app is when using widgets.
widgets will not work after phone reboot if their requestCode are the same.
that means the pendingIndent you set on the remoteViews of your widget must be set unique requestCode, usually the widgetId accompanying a number.


问:
Cannot get the list of subscriptions from Azure AD using Microsoft Graph API
I am trying to get the list of notification subscriptions from Azure AD using Microsoft graph api.

I am trying it in a webjob application.

The funtions class in the Webjob project has a code like

```<code>  public static void CreateAndUpdateSubcriptions()
    {
        var config= new ConfigurationSettings
        {
            AppId = "*****",
            AppSecret = "***",
            Ngrok = "****",
            TenantId = "*****"
        };

        var graphServiceClient = GetGraphClient(config);//creates the graph client using client credential flow

        var subscriptions = graphServiceClient.Subscriptions
            .Request()
            .GetAsync().Result;

        List<Subscription> subscription = new List<Subscription>();

        foreach (var subscrip in subscriptions)
        {
            if (subscrip.NotificationUrl == config.Ngrok + "/api/notifications")
            {
                subscription.Add(subscrip);
            }
        }

        if (subscription.Count == 0)
        {
            var s = new Subscription
            {
                ChangeType = "updated",
                NotificationUrl = config.Ngrok + "/api/notifications",
                Resource = "groups",
                ExpirationDateTime = DateTime.UtcNow.AddMinutes(10),
                ClientState = "****"
            };
            s = graphServiceClient
                    .Subscriptions
                    .Request()
                    .AddAsync(sub).Result;

        }
        else
        {
            CheckSubscriptions(subscription, config);
        }
    }
</code>```

I have given the application the delegated permission(Subscription.Read.All).

But I am not getting any subscriptions back from the section of the code when I am running the code again(so there is a subscription which exists),

```<code>var subscriptions = graphServiceClient.Subscriptions
            .Request()
            .GetAsync().Result;
</code>```

I am not sure what I am doing wrong.

Any Help?

答:
You should give the application the application permission instead of delegated permission.

Refer to https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-permissions-and-consent#types-of-permissions

Also remember to click grant admin consent button.

Updates: refer to this document.

Body:
I am trying to get the list of notification subscriptions from Azure AD using Microsoft graph api.

I am trying it in a webjob application.

The funtions class in the Webjob project has a code like

  public static void CreateAndUpdateSubcriptions()
    {
        var config= new ConfigurationSettings
        {
            AppId = "*****",
            AppSecret = "***",
            Ngrok = "****",
            TenantId = "*****"
        };

        var graphServiceClient = GetGraphClient(config);//creates the graph client using client credential flow

        var subscriptions = graphServiceClient.Subscriptions
            .Request()
            .GetAsync().Result;

        List<Subscription> subscription = new List<Subscription>();

        foreach (var subscrip in subscriptions)
        {
            if (subscrip.NotificationUrl == config.Ngrok + "/api/notifications")
            {
                subscription.Add(subscrip);
            }
        }

        if (subscription.Count == 0)
        {
            var s = new Subscription
            {
                ChangeType = "updated",
                NotificationUrl = config.Ngrok + "/api/notifications",
                Resource = "groups",
                ExpirationDateTime = DateTime.UtcNow.AddMinutes(10),
                ClientState = "****"
            };
            s = graphServiceClient
                    .Subscriptions
                    .Request()
                    .AddAsync(sub).Result;

        }
        else
        {
            CheckSubscriptions(subscription, config);
        }
    }

I have given the application the delegated permission(Subscription.Read.All).

But I am not getting any subscriptions back from the section of the code when I am running the code again(so there is a subscription which exists),

var subscriptions = graphServiceClient.Subscriptions
            .Request()
            .GetAsync().Result;

I am not sure what I am doing wrong.

Any Help?


问:
how to migrate AWS RDS MySql engine database to AWS serverless?
I'm running a development db in aws rds MySql engine. I've lots of testing data in this. Now I want to use aws serverless db, but I also want to copy the data from old rds instance to the serverless without dump.

Can I do this like taking snapshot of old rds and restore to serverless db? I tried to do this but have no luck.
Can anyone guide me to the right direction please?

答: Creating a snapshot and restoring to a Serverless cluster should work. If it does not, can you please share snapshots or CLI examples? </p>


问:
Get Correct keyCode for keypad(numpad) keys
I'm getting codes [96..105] by calling String.fromCharCode(event.keyCode) when pressing keys [0..9](digits) on the keypad.
Though these codes correspond to characters: 'a b c d e f g h i'  instead of [0..9].

Question:

I have 3 inputs in the form. User allowed to enter only in the 1-st input. While user press keys on keyboard some function need to filter it and write it to 2-nd input if pressed key is digit otherwise it must write it to the 3-rd input. How it can be corrected?

My implementation in JSFiddle

答:
Use the keypress handler:

```<code>[somelement].onkeypress = function(e){
  e = e || event;
  console.log(String.fromCharCode(e.keyCode));
}
</code>```

See also: this W3C testdocument

if you want to use the keyup or keydown handler, you can subtract 48 from e.keyCode to get the number (so String.fromCharCode(e.keyCode-48))

Body:
Use the keypress handler:

[somelement].onkeypress = function(e){
  e = e || event;
  console.log(String.fromCharCode(e.keyCode));
}

See also: this W3C testdocument

if you want to use the keyup or keydown handler, you can subtract 48 from e.keyCode to get the number (so String.fromCharCode(e.keyCode-48))


问:
How can I add custom attributes to a "Product" type in with JSON-LD?
I have a real estate website which displays real estate properties for sale. For each page where a property is listed, I want to create JSON-LD code to display information about the property, using Schema.org.

I am not sure if there is a better type to use than Product for real estate listings here.

How can I add a custom attribute to describe the property?

Here is a JSON-LD structure for Product:

{
  "@context": "https://schema.org/",
  "@type": "Product",
  "name": "address of the property ",
  "image": [
    "https://example.com/photos/1x1/photo.jpg",
    "https://example.com/photos/4x3/photo.jpg",
    "https://example.com/photos/16x9/photo.jpg"
   ],
  "description": "description about the houese"
  }
}
```

I want to be able to add other info like

Primary Features

How many bedrooms it has

How many bathrooms it has

If it is a smart home or not

etc...

Interior Features

Fireplace

Fireplace location

etc...

Exterior Features

The Lots Size

Fets

etc...

How can I add these custom attribute that describes the property using Schema.org?

答:
If you want to provide data about real estate, you need to use a type that represents real estate. Probably Accommodation (Apartment, House, …) for your case.

If you want to convey that this real estate is a product, you need to provide the Product type in addition to the Accommodation type.

Then you can use properties from Accommodation as well as Product.

{
  "@context": "https://schema.org/",
  "@type": ["House", "Product"],

  "offers": {
    "@type": "Offer"
  },

  "numberOfRooms": 4

}
```

Custom properties about the real estate can be added with the additionalProperty property, and, if applicable, with the amenityFeature property.

Body:
I have a real estate website which displays real estate properties for sale. For each page where a property is listed, I want to create JSON-LD code to display information about the property, using Schema.org.

I am not sure if there is a better type to use than Product for real estate listings here.

How can I add a custom attribute to describe the property?

Here is a JSON-LD structure for Product:

{
  "@context": "https://schema.org/",
  "@type": "Product",
  "name": "address of the property ",
  "image": [
    "https://example.com/photos/1x1/photo.jpg",
    "https://example.com/photos/4x3/photo.jpg",
    "https://example.com/photos/16x9/photo.jpg"
   ],
  "description": "description about the houese"
  }
}

I want to be able to add other info like

Primary Features

How many bedrooms it has

How many bathrooms it has

If it is a smart home or not

etc...

Interior Features

Fireplace

Fireplace location

etc...

Exterior Features

The Lots Size

Fets

etc...

How can I add these custom attribute that describes the property using Schema.org?

Body:
If you want to provide data about real estate, you need to use a type that represents real estate. Probably Accommodation (Apartment, House, …) for your case.

If you want to convey that this real estate is a product, you need to provide the Product type in addition to the Accommodation type.

Then you can use properties from Accommodation as well as Product.

{
  "@context": "https://schema.org/",
  "@type": ["House", "Product"],

  "offers": {
    "@type": "Offer"
  },

  "numberOfRooms": 4

}

Custom properties about the real estate can be added with the additionalProperty property, and, if applicable, with the amenityFeature property.


问:
Bootstrap TypeAhead.js prevent invalid entry
I am using the bootstrap typeahead.js feature for autocomplete capability for 'state' lookup.  How can I best prevent individuals from typing all (and not successfully picking Alaska) before submitting the form?</p>

答:
Depending on your requirements you could enforce picking from valid options only and clearing any invalid input.

Start with creating a custom source which tracks search results:

```<code>    var sync = false;
    var current_results = [];
    var current_q = '';
    var selected_val = '';

    function search(q, sync) {
        current_q = q;
        window.sync = sync;
        engine.search(q, cust_sync);
    }

    function cust_sync(datums) {
      current_results = datums;
      sync(datums);
    }

    $('#typeahead').typeahead(
        {
          highlight: true,
          minLength: 0
        },
        {
            source: search // custom search engine
        }

    );
</code>```

Then bind select and change event handlers.

```<code>
    $('#typeahead').bind('typeahead:change', function(ev) {
        var current_val = $('#typeahead').val();
        // user moved cursor out of input without selecting from the menu
        if(current_val != selected_val){
            // current query has search results
            if(current_results.length)
                // change input to the first valid search result
                $('#typeahead').typeahead('val', current_results[0].name);
            // no results for this query - clear input
            else
                $('#typeahead').typeahead('val', '');
            }
    });

    $('#typeahead').bind('typeahead:select', function(ev, suggestion) {
        selected_val = $('#typeahead').val(); // keep track of a selected value
    });
</code>```

Body:
Depending on your requirements you could enforce picking from valid options only and clearing any invalid input.

Start with creating a custom source which tracks search results:

    var sync = false;
    var current_results = [];
    var current_q = '';
    var selected_val = '';

    function search(q, sync) {
        current_q = q;
        window.sync = sync;
        engine.search(q, cust_sync);
    }

    function cust_sync(datums) {
      current_results = datums;
      sync(datums);
    }

    $('#typeahead').typeahead(
        {
          highlight: true,
          minLength: 0
        },
        {
            source: search // custom search engine
        }

    );

Then bind select and change event handlers.

    $('#typeahead').bind('typeahead:change', function(ev) {
        var current_val = $('#typeahead').val();
        // user moved cursor out of input without selecting from the menu
        if(current_val != selected_val){
            // current query has search results
            if(current_results.length)
                // change input to the first valid search result
                $('#typeahead').typeahead('val', current_results[0].name);
            // no results for this query - clear input
            else
                $('#typeahead').typeahead('val', '');
            }
    });

    $('#typeahead').bind('typeahead:select', function(ev, suggestion) {
        selected_val = $('#typeahead').val(); // keep track of a selected value
    });


问:
How to redirect to stdin in bash but with a delay between each line?
The platform I am working is Ubuntu 18.04. I have a binary program (so I cannot change the program) say foo and it reads commands line by line from stdin. I have the commands in a file named 'commands' and I want to run foo with redirecting commands to its stdin. So far I know I can do this just by simply pipe the output of the file to foo like cat commands | foo.

However I would like to give the commands one by one with some delay e.g. 10 seconds. So foo may wait for the input on the stdin and I do not care. How can I do that in bash? So basically, I want to give the inputs like interactively but not actually interactive, it is automatically.

答:
With bash and a loop:</p>

```<code>while read -r line; do echo "$line"; sleep 10; done < commands | foo
</code>```

Body:
With bash and a loop:

while read -r line; do echo "$line"; sleep 10; done < commands | foo


问:
How to force telegram to update link preview?
Telegram show description meta tag as link preview.
I changed the description meta tag but the link preview of my website didn't changed.
How to force telegram to update link preview?</p>

答:
Sending the pure link to @webpagebot would not work so I used

```<code><meta property="og:url" content="https://mylink.com" />
</code>```

and it worked.

Body:
Sending the pure link to @webpagebot would not work so I used

<meta property="og:url" content="https://mylink.com" />

and it worked.


问:
Aurora Writer and Reader internal replication (replica lag) time
We are using Amazon RDS.

There are 2 RDS-server, 1) Writer 2) Reader.

I want to check the internal cloning time between writer and reader.

For ex.
From writer connection, one record has changed so at the same time if reader connection retrieves that record which is changed by the writer.

so when that change is reflected in the reader?

Or how much time is required by AWS RDS reader to get all changes made by the writer.

For more information check attached screen-shot for reader and writer form AWS-RDS.

答:
https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Monitoring.html

AuroraReplicaLag

For an Aurora Replica, the amount of lag when replicating updates from the primary instance, in milliseconds.

This is the metric that you should be looking at to track this. Its usually under 100ms.


问:
Javafx: TableView change row color based on column value
I have the following piece of code to update both the color of a column cell and its corresponding row:

```<code>    calltypel.setCellFactory(column -> {
        return new TableCell<CallLogs, String>() {
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);

                setText(empty ? "" : getItem().toString());
                setGraphic(null);

                TableRow currentRow = getTableRow();

                //This doesn't work
                if(item.equals("a")){
                    item.setTextFill(Color.RED);
                    currentRow.setTextFill(Color.PINK);
                    }
                else{
                    item.setTextFill(Color.GREEN);
                    currentRow.setTextFill(Color.BLUE);
                }

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

The code segment of 'if' condition doesn't work. I am unable to identify the correct references to objects and also what is the best way to do this.

Thanks!

答:
The correct approach is to use setRowFactory of the Table:

```<code>table.setRowFactory(tv -> new TableRow<CustomItem>() {
    @Override
    protected void updateItem(CustomItem item, boolean empty) {
        super.updateItem(item, empty);
        if (item == null || item.getValue() == null)
            setStyle("");
        else if (item.getValue() > 0)
            setStyle("-fx-background-color: #baffba;");
        else if (item.getValue() < 0)
            setStyle("-fx-background-color: #ffd7d1;");
        else
            setStyle("");
    }
});
</code>```

Body:
I have the following piece of code to update both the color of a column cell and its corresponding row:

    calltypel.setCellFactory(column -> {
        return new TableCell<CallLogs, String>() {
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);

                setText(empty ? "" : getItem().toString());
                setGraphic(null);

                TableRow currentRow = getTableRow();

                //This doesn't work
                if(item.equals("a")){
                    item.setTextFill(Color.RED);
                    currentRow.setTextFill(Color.PINK);
                    }
                else{
                    item.setTextFill(Color.GREEN);
                    currentRow.setTextFill(Color.BLUE);
                }

            }
        };
    });

The code segment of 'if' condition doesn't work. I am unable to identify the correct references to objects and also what is the best way to do this.

Thanks!

Body:
The correct approach is to use setRowFactory of the Table:

table.setRowFactory(tv -> new TableRow<CustomItem>() {
    @Override
    protected void updateItem(CustomItem item, boolean empty) {
        super.updateItem(item, empty);
        if (item == null || item.getValue() == null)
            setStyle("");
        else if (item.getValue() > 0)
            setStyle("-fx-background-color: #baffba;");
        else if (item.getValue() < 0)
            setStyle("-fx-background-color: #ffd7d1;");
        else
            setStyle("");
    }
});