问:
Spawning child traversals anonymously using Gremlin-python and graphexp
I'm trying to create a graph from scratch that i'm visualising in graphexp, but i'm struggling to undertand the anonymized traversals concept and how to create them

I'm using python 3.9 and gremlinpython 3.5.1

Creating the connection and graph:

```<code>from gremlin_python.process.anonymous_traversal import traversal

self.g = traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin', 'g'))
</code>```

I imported the statics so I could use the steps without the __ class:

```<code>statics.load_statics(globals())
</code>```

Creating a vertex if it doesnt exists:

```<code>def _add_vertex(self, name):
        return self.g.V().has('name', name).fold().coalesce(unfold(), addV().property('name',name)).next()
</code>```

Creating an edge if it doesnt exist between two vertices:

```<code>def _add_edge(self, v1, v2, weight, label):
        return self.g.V(v1).as_("fromVertex").V(v2).coalesce(inE(label).where(outV().as_(
            "fromVertex")), addE(label).property("weight", weight).from_("fromVertex")).next()
</code>```

But i'm getting this error in graphexp when clicking on a vertex

```<code>Error retrieving data
The child traversal of [GraphStep(vertex,[696560]), PropertyMapStep(value)] was not spawned anonymously - use the __ class rather than a TraversalSource to construct the child traversal
</code>```

The documentation is generally good but not very helpful for the anonymized traversals part. So how can I spawn anonymous child traversals using this method? and what does it really mean ?

答:
Starting with TinkerPop 3.5.x, using a g anywhere but at the start of a traversal will raise an error. It used to be possible to write something like:

g.V('1').addE('test').from(g.V('2'))

This actually can have some bad side effects, so in 3.5.x the parser now enforces that you must do one of:

g.V('1').addE('test').from(V('2'))

or

g.V('1').addE('test').from(__.V('2'))

That "double underscore" class __. is the so called anonymous traversal source. It is called that as it is not connected to a prior step by a dot, rather it is inside parens as a child traversal.

I would check your code to see if you are actually injecting a second g into your traversal.

Body:
I'm trying to create a graph from scratch that i'm visualising in graphexp, but i'm struggling to undertand the anonymized traversals concept and how to create them

I'm using python 3.9 and gremlinpython 3.5.1

Creating the connection and graph:

from gremlin_python.process.anonymous_traversal import traversal

self.g = traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin', 'g'))

I imported the statics so I could use the steps without the __ class:

statics.load_statics(globals())

Creating a vertex if it doesnt exists:

def _add_vertex(self, name):
        return self.g.V().has('name', name).fold().coalesce(unfold(), addV().property('name',name)).next()

Creating an edge if it doesnt exist between two vertices:

def _add_edge(self, v1, v2, weight, label):
        return self.g.V(v1).as_("fromVertex").V(v2).coalesce(inE(label).where(outV().as_(
            "fromVertex")), addE(label).property("weight", weight).from_("fromVertex")).next()

But i'm getting this error in graphexp when clicking on a vertex

Error retrieving data
The child traversal of [GraphStep(vertex,[696560]), PropertyMapStep(value)] was not spawned anonymously - use the __ class rather than a TraversalSource to construct the child traversal

The documentation is generally good but not very helpful for the anonymized traversals part. So how can I spawn anonymous child traversals using this method? and what does it really mean ?


来源: stackexchange

问:
Multiple Errors Relating Kotlin Version
After restarting my project with almost no changes I suddenly got this errorlog:

```<code>Incompatible classes were found in dependencies. Remove them from the classpath or use '-Xskip-metadata-version-check' to suppress errors
e: C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-common/1.5.31/43331609c7de811fed085e0dfd150874b157c32/kotlin-stdlib-common-1.5.31.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-jdk7/1.5.30/525f5a7fa6d7790a571c07dd24214ed2dda352fe/kotlin-stdlib-jdk7-1.5.30.jar!/META-INF/kotlin-stdlib-jdk7.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-jdk8/1.5.30/5fd47535cc85f9e24996f939c2de6583991481b0/kotlin-stdlib-jdk8-1.5.30.jar!/META-INF/kotlin-stdlib-jdk8.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-android/1.5.2/d246a704a55b7bddb79407cce4348890eaa341d9/kotlinx-coroutines-android-1.5.2.jar!/META-INF/kotlinx-coroutines-android.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-core-jvm/1.5.2/f4cc07a50437659e0043e7da762809a46932b6a0/kotlinx-coroutines-core-jvm-1.5.2.jar!/META-INF/kotlinx-coroutines-core.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/transforms-2/files-2.1/510d2c0b665cbe8abe1bcbf4bf8b6987/window-java-1.0.0-beta04/jars/classes.jar!/META-INF/window-java_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/transforms-2/files-2.1/7ad239db5bbf66449a1f587f3afa295b/jetified-window-1.0.0-beta04/jars/classes.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (20, 5): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (21, 13): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (25, 5): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (26, 14): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (28, 14): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

 C:/Users/Gerald/.gradle/caches/transforms-2/files-2.1/7ad239db5bbf66449a1f587f3afa295b/jetified-window-1.0.0-beta04/jars/classes.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (20, 5): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (21, 13): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (25, 5): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (26, 14): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (28, 14): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (33, 13): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class

</code>```

Flutter says I have to add a line in my android/build.gradle, after doing that, nothing happens
I have also tried clearing all the caches, same error.

```<code>buildscript {
    ext.kotlin_version = '1.6.10' // line to add
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.1'
        classpath 'com.google.gms:google-services:4.3.8'
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
    project.evaluationDependsOn(':app')
}

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

</code>```

I have also tried to downgrade 'com.android.tools.build:gradle:3.5.1' to 3.2.1 after reading a thread about it.
Error of trying that

```<code>Where:
Build file 'E:\GitHub\BauFuchs\baufuchs\android\app\build.gradle' line: 24

* What went wrong:
A problem occurred evaluating project ':app'.
> ASCII
</code>```

Line 24 of app build.gradle
apply plugin: 'com.android.application'
Thanks for your help I have to start working again I can't do anything

答:
Try upgrading gradle distribution to match kotlin version.
Open android/gradle/wrapper/gradle-wrapper.properties and replace distributionUrl to eg. distributionUrl=https://services.gradle.org/distributions/gradle-6.7.1-all.zip or newer.

Make sure to run flutter clean after applying the changes.

ContentLicense: CC BY-SA 4.0

Title: Multiple Errors Relating Kotlin Version

Body:
After restarting my project with almost no changes I suddenly got this errorlog:

Incompatible classes were found in dependencies. Remove them from the classpath or use '-Xskip-metadata-version-check' to suppress errors
e: C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-common/1.5.31/43331609c7de811fed085e0dfd150874b157c32/kotlin-stdlib-common-1.5.31.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-jdk7/1.5.30/525f5a7fa6d7790a571c07dd24214ed2dda352fe/kotlin-stdlib-jdk7-1.5.30.jar!/META-INF/kotlin-stdlib-jdk7.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-jdk8/1.5.30/5fd47535cc85f9e24996f939c2de6583991481b0/kotlin-stdlib-jdk8-1.5.30.jar!/META-INF/kotlin-stdlib-jdk8.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-android/1.5.2/d246a704a55b7bddb79407cce4348890eaa341d9/kotlinx-coroutines-android-1.5.2.jar!/META-INF/kotlinx-coroutines-android.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-coroutines-core-jvm/1.5.2/f4cc07a50437659e0043e7da762809a46932b6a0/kotlinx-coroutines-core-jvm-1.5.2.jar!/META-INF/kotlinx-coroutines-core.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/transforms-2/files-2.1/510d2c0b665cbe8abe1bcbf4bf8b6987/window-java-1.0.0-beta04/jars/classes.jar!/META-INF/window-java_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Gerald/.gradle/caches/transforms-2/files-2.1/7ad239db5bbf66449a1f587f3afa295b/jetified-window-1.0.0-beta04/jars/classes.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (20, 5): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (21, 13): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (25, 5): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (26, 14): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (28, 14): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

 C:/Users/Gerald/.gradle/caches/transforms-2/files-2.1/7ad239db5bbf66449a1f587f3afa295b/jetified-window-1.0.0-beta04/jars/classes.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (20, 5): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (21, 13): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (25, 5): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (26, 14): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (28, 14): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class
e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\maps_launcher-2.0.1\android\src\main\kotlin\com\example\maps_launcher\MapsLauncherPlugin.kt: (33, 13): Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

The class is loaded from C:/Users/Gerald/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.5.31/6628d61d0f5603568e72d2d5915d2c034b4f1c55/kotlin-stdlib-1.5.31.jar!/kotlin/Unit.class

Flutter says I have to add a line in my android/build.gradle, after doing that, nothing happens
I have also tried clearing all the caches, same error.

buildscript {
    ext.kotlin_version = '1.6.10' // line to add
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.1'
        classpath 'com.google.gms:google-services:4.3.8'
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
    project.evaluationDependsOn(':app')
}

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

I have also tried to downgrade 'com.android.tools.build:gradle:3.5.1' to 3.2.1 after reading a thread about it.
Error of trying that

Where:
Build file 'E:\GitHub\BauFuchs\baufuchs\android\app\build.gradle' line: 24

* What went wrong:
A problem occurred evaluating project ':app'.
> ASCII

Line 24 of app build.gradle
apply plugin: 'com.android.application'
Thanks for your help I have to start working again I can't do anything


问:
How can I change the margin of the element with a variable in JavaScript?
I am quite a beginner and trying to learn JavaScript. I am trying to improve an example for Popup.

I want to adjust the left margin of the popup so I can center the element to the text.
I added the CSS for reference but I am trying to do it in JS.

Basically the problem is if I put the code as below it works.

```<code>popup.style.marginLeft = "165px";
</code>```

But if I define it with variable and put it like below, it won't work.

```<code>popup.style.marginLeft = widthPopup;
</code>```

I don't know if I am missing anything. I added the all code below for reference.

    function myFunction() {
      var popup = document.getElementById("myPopup");
      popup.classList.toggle("show");

// what I tried to do for the solution
//      let widthPopup = document.createTextNode(popup.clientWidth / -2+"px");
//      console.log(widthPopup);
//      popup.style.marginLeft = widthPopup;
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  font-family: "lato";
  font-weight: 300;
  font-size: 17px;
}

/* Popup container */
.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  margin: 15em;
}

/* The actual popup (appears on top) */
.popup .popuptext {
  visibility: hidden;
  width: 30ch;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  padding: 20px;
}

/* Popup arrow */
.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
/*# sourceMappingURL=main.css.map */</code>```

Click me!
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus, modi magnam tenetur quo labore, nostrum debitis, facere velit nam suscipit error hic? Suscipit ab aspernatur eos rerum, odit quas, voluptatem velit amet quia, nesciunt possimus. Placeat ad suscipit quae ipsum vero voluptatem laboriosam! Labore perspiciatis accusantium reiciendis ex inventore temporibus! Est itaque a adipisci neque mollitia voluptas, tempora praesentium qui? Fuga facilis, ea, aliquam esse nostrum id architecto sit ipsum voluptates vel aspernatur voluptatibus. Molestiae adipisci libero eligendi expedita totam facilis obcaecati officiis voluptatibus magnam quia praesentium exercitationem perspiciatis ipsam impedit suscipit in, corrupti minima enim dolorum vel! Debitis, quaerat.

```

Thank you for any help!

答:
Assign a margin value in a variable using

```<code>let marginValue = popup.clientWidth / -2+"px";
</code>```

then set that variable to the margin-left attribute for the popup.

function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
  let marginValue = popup.clientWidth / -2+"px";
  popup.style.marginLeft = marginValue;
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  font-family: "lato";
  font-weight: 300;
  font-size: 17px;
}

/* Popup container */
.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  margin: 15em;
}

/* The actual popup (appears on top) */
.popup .popuptext {
  visibility: hidden;
  width: 30ch;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  padding: 20px;
}

/* Popup arrow */
.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}</code>```

Click me!
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus, modi magnam tenetur quo labore, nostrum debitis, facere velit nam suscipit error hic? Suscipit ab aspernatur eos rerum, odit quas, voluptatem velit amet quia, nesciunt possimus. Placeat ad suscipit quae ipsum vero voluptatem laboriosam! Labore perspiciatis accusantium reiciendis ex inventore temporibus! Est itaque a adipisci neque mollitia voluptas, tempora praesentium qui? Fuga facilis, ea, aliquam esse nostrum id architecto sit ipsum voluptates vel aspernatur voluptatibus. Molestiae adipisci libero eligendi expedita totam facilis obcaecati officiis voluptatibus magnam quia praesentium exercitationem perspiciatis ipsam impedit suscipit in, corrupti minima enim dolorum vel! Debitis, quaerat.

```

Body:
I am quite a beginner and trying to learn JavaScript. I am trying to improve an example for Popup.

I want to adjust the left margin of the popup so I can center the element to the text.
I added the CSS for reference but I am trying to do it in JS.

Basically the problem is if I put the code as below it works.

popup.style.marginLeft = "165px";

But if I define it with variable and put it like below, it won't work.

popup.style.marginLeft = widthPopup;

I don't know if I am missing anything. I added the all code below for reference.

    function myFunction() {
      var popup = document.getElementById("myPopup");
      popup.classList.toggle("show");

// what I tried to do for the solution
//      let widthPopup = document.createTextNode(popup.clientWidth / -2+"px");
//      console.log(widthPopup);
//      popup.style.marginLeft = widthPopup;
    }

* {
  font-family: "lato";
  font-weight: 300;
  font-size: 17px;
}

/* Popup container */
.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  margin: 15em;
}

/* The actual popup (appears on top) */
.popup .popuptext {
  visibility: hidden;
  width: 30ch;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  padding: 20px;
}

/* Popup arrow */
.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
/*# sourceMappingURL=main.css.map */

Click me!
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus, modi magnam tenetur quo labore, nostrum debitis, facere velit nam suscipit error hic? Suscipit ab aspernatur eos rerum, odit quas, voluptatem velit amet quia, nesciunt possimus. Placeat ad suscipit quae ipsum vero voluptatem laboriosam! Labore perspiciatis accusantium reiciendis ex inventore temporibus! Est itaque a adipisci neque mollitia voluptas, tempora praesentium qui? Fuga facilis, ea, aliquam esse nostrum id architecto sit ipsum voluptates vel aspernatur voluptatibus. Molestiae adipisci libero eligendi expedita totam facilis obcaecati officiis voluptatibus magnam quia praesentium exercitationem perspiciatis ipsam impedit suscipit in, corrupti minima enim dolorum vel! Debitis, quaerat.

Thank you for any help!

Body:
Assign a margin value in a variable using

let marginValue = popup.clientWidth / -2+"px";

then set that variable to the margin-left attribute for the popup.

function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
  let marginValue = popup.clientWidth / -2+"px";
  popup.style.marginLeft = marginValue;
  }

* {
  font-family: "lato";
  font-weight: 300;
  font-size: 17px;
}

/* Popup container */
.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  margin: 15em;
}

/* The actual popup (appears on top) */
.popup .popuptext {
  visibility: hidden;
  width: 30ch;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  padding: 20px;
}

/* Popup arrow */
.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

<div class="popup" onclick="myFunction()">Click me!
    <span class="popuptext" id="myPopup">Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus, modi magnam tenetur quo labore, nostrum debitis, facere velit nam suscipit error hic? Suscipit ab aspernatur eos rerum, odit quas, voluptatem velit amet quia, nesciunt possimus. Placeat ad suscipit quae ipsum vero voluptatem laboriosam! Labore perspiciatis accusantium reiciendis ex inventore temporibus! Est itaque a adipisci neque mollitia voluptas, tempora praesentium qui? Fuga facilis, ea, aliquam esse nostrum id architecto sit ipsum voluptates vel aspernatur voluptatibus. Molestiae adipisci libero eligendi expedita totam facilis obcaecati officiis voluptatibus magnam quia praesentium exercitationem perspiciatis ipsam impedit suscipit in, corrupti minima enim dolorum vel! Debitis, quaerat.</span>
</div>


问:
handleSubmit is not defined
I'm working on a project and it keeps telling me "handleSubmit" nor defined although it is already defined.

This is my FormSubmit component (Function component)

```<code>    return (
    <Card>
      <form onSubmit={handleSubmit}>
        <h2 style={{color:'black'}}> How would you rate your service with us </h2>
        <RatingSelect select={(rating)=>setRating(rating)}/>
        <div className="input-group">
          <input type="text" onChange={getText} placeholder="Write a Review" value={text}/>
          {/* <button type="submit"> Send </button> */}
          <Button type='submit' version='primary' isDisabled={btnDisabled}/>
        </div>
        {message?<div className="message">{message}</div>:null}
      </form>
    </Card>
  );
</code>```

and this is a function

```<code>    const handleSubmit=()=>{
          e.preventDefault();
          console.log(e);
        }
</code>```

答:
You are not passing e into the handleSubmit function, yet you are trying to refer to it in the body of the function.

Try this:

```<code>const handleSubmit = (e) => {
      e.preventDefault();
      console.log(e);
    }
</code>```

Title: handleSubmit is not defined

Body:
I'm working on a project and it keeps telling me "handleSubmit" nor defined although it is already defined.

This is my FormSubmit component (Function component)

    return (
    <Card>
      <form onSubmit={handleSubmit}>

 How would you rate your service with us

        <RatingSelect select={(rating)=>setRating(rating)}/>

          <input type="text" onChange={getText} placeholder="Write a Review" value={text}/>
          {/* <button type="submit"> Send </button> */}
          <Button type='submit' version='primary' isDisabled={btnDisabled}/>

        {message?
{message}
:null}
      </form>
    </Card>
  );

and this is a function

    const handleSubmit=()=>{
          e.preventDefault();
          console.log(e);
        }

Body:
You are not passing e into the handleSubmit function, yet you are trying to refer to it in the body of the function.

Try this:

const handleSubmit = (e) => {
      e.preventDefault();
      console.log(e);
    }


问:
Where do I put an authenticated API request in Ruby on Rails?
I am building a sports app as a side project to help learn Ruby on Rails and about API's, but after a lot of searching around, I haven't found any clear instructions on where (or what) I am supposed to paste the API request in Rails.

The sample link for the API I want to use looks like this..

```<code>https://soccer.sportmonks.com/api/v2.0/leagues?api_token={API_TOKEN}
"data": [
          {
            "id": 271,
            "active": true,
            "type": "domestic",
            "legacy_id": 43,
            "country_id": 320,
            "logo_path": "https://cdn.sportmonks.com/images/soccer/leagues/271.png",
            "name": "Superliga",
            "is_cup": false,
            "current_season_id": 17328,
            "current_round_id": 199450,
            "current_stage_id": 77447994,
            "live_standings": true,
            "coverage": {
                "predictions": true,
                "topscorer_goals": true,
                "topscorer_assists": true,
                "topscorer_cards": true
            }
          }
        ]
</code>```

I understand a lot of what I'm looking at there, the need for the API token, and how it can be customized, but I'm confused as to where in my Rails files this would be posted? In the HTML structure? In the Javascript folder? How do I take this from the source API website and put it on mine?

I've been looking around for a while but all I see are instructions on how to build your own API, not use someone else's on your webpage.

Any resources or help would be greatly appreciated. I love the idea of the flexibility of API's from a theoretical perspective and look forward to working with them, I just need to figure out where or what I should be looking to cut/paste.

Edit: here is an example github of what it's supposed to look like, but I still don't see where I actually input the exact location of the link. https://github.com/vnnoder/sportmonks-ruby

答:
You could install their gem, so you don't need to worry about requests syntax.

For the API token, you could put in an initializer, so the sportmonks API is initialized.

initializers/sportmonks.rb

Sportmonks.configure do |config|
  # PS: it's not ideal to put your raw API key here for security purposes.
  # You should use environment variables for production projects.
  # For testing purposes it is fine.
  config.api_token = "your API KEY here"
end
```
<p>So now, when you start your rails server, then the gem is going to be usable.</p>
<p>To test the gem, you can start a <code>rails console</code> and you can simply do</p>
<pre class="lang-rb prettyprint-override"><code>Sportmonks.leagues
</code>```

And you will have a list of all the leagues.

Body:
I am building a sports app as a side project to help learn Ruby on Rails and about API's, but after a lot of searching around, I haven't found any clear instructions on where (or what) I am supposed to paste the API request in Rails.

The sample link for the API I want to use looks like this..

https://soccer.sportmonks.com/api/v2.0/leagues?api_token={API_TOKEN}
"data": [
          {
            "id": 271,
            "active": true,
            "type": "domestic",
            "legacy_id": 43,
            "country_id": 320,
            "logo_path": "https://cdn.sportmonks.com/images/soccer/leagues/271.png",
            "name": "Superliga",
            "is_cup": false,
            "current_season_id": 17328,
            "current_round_id": 199450,
            "current_stage_id": 77447994,
            "live_standings": true,
            "coverage": {
                "predictions": true,
                "topscorer_goals": true,
                "topscorer_assists": true,
                "topscorer_cards": true
            }
          }
        ]

I understand a lot of what I'm looking at there, the need for the API token, and how it can be customized, but I'm confused as to where in my Rails files this would be posted? In the HTML structure? In the Javascript folder? How do I take this from the source API website and put it on mine?

I've been looking around for a while but all I see are instructions on how to build your own API, not use someone else's on your webpage.

Any resources or help would be greatly appreciated. I love the idea of the flexibility of API's from a theoretical perspective and look forward to working with them, I just need to figure out where or what I should be looking to cut/paste.

Edit: here is an example github of what it's supposed to look like, but I still don't see where I actually input the exact location of the link. https://github.com/vnnoder/sportmonks-ruby

Body:
You could install their gem, so you don't need to worry about requests syntax.

For the API token, you could put in an initializer, so the sportmonks API is initialized.

initializers/sportmonks.rb

Sportmonks.configure do |config|
  # PS: it's not ideal to put your raw API key here for security purposes.
  # You should use environment variables for production projects.
  # For testing purposes it is fine.
  config.api_token = "your API KEY here"
end

So now, when you start your rails server, then the gem is going to be usable.

To test the gem, you can start a rails console and you can simply do

Sportmonks.leagues

And you will have a list of all the leagues.


问:
firebase SSR problem, "App requesting permission to access your google account" pops up instead of website
I have attempted to make a react SSR website using create-React basics through the "razzle" helper tool.

the app originally worked with this:

```<code>'use strict'
const functions = require('firebase-functions');
const app = require('./server/build/server.bundle.js').default;

exports.app = functions.https.onRequest(app)
</code>```

but when I changed it to this:

```<code>'use strict'
const functions = require('firebase-functions');
const App = require('./server/build/server.bundle.js').default;

const React = require('react')
const express = require('express');
const fs = require('fs');
const app = express();
const {RenderToString} = require('react-dom/server');

const index = fs.readFileSync(__dirname +'/index.html', 'utf8');

app.get ('**', (req, res) => {
    const html = RenderToString(App);
    const finalHtml = index.replace('<!-- ::APP:: -->', html)
    res.set('Cache-Control', 'public, max-age=600, sMax-age=1200');
    res.send(finalHtml);
})

exports.shell = functions.https.onRequest(app);
</code>```

instead of the website i got

An application is requesting permission to access your Google Account.
Please select an account that you would like to use.

and upon attempting entry with the firebase admin gmail account:

Error: Forbidden
Your client does not have permission to get URL /app/ from this server.

What have I done wrong, and how do I fix this?

The original function which worked for SSR was removed, and the new one exports.shell was added sucessfully.

答:
You can be forwarded to the same page with message "App requesting permission to access your google account" when your Firebase Function is deployed to another region than "us-central1", because:

Important: Firebase Hosting supports Cloud Functions in us-central1
only.

Body:
I have attempted to make a react SSR website using create-React basics through the "razzle" helper tool.

the app originally worked with this:

'use strict'
const functions = require('firebase-functions');
const app = require('./server/build/server.bundle.js').default;

exports.app = functions.https.onRequest(app)

but when I changed it to this:

'use strict'
const functions = require('firebase-functions');
const App = require('./server/build/server.bundle.js').default;

const React = require('react')
const express = require('express');
const fs = require('fs');
const app = express();
const {RenderToString} = require('react-dom/server');

const index = fs.readFileSync(__dirname +'/index.html', 'utf8');

app.get ('**', (req, res) => {
    const html = RenderToString(App);
    const finalHtml = index.replace('', html)
    res.set('Cache-Control', 'public, max-age=600, sMax-age=1200');
    res.send(finalHtml);
})

exports.shell = functions.https.onRequest(app);

instead of the website i got

An application is requesting permission to access your Google Account.
Please select an account that you would like to use.

and upon attempting entry with the firebase admin gmail account:

Error: Forbidden
Your client does not have permission to get URL /app/ from this server.

What have I done wrong, and how do I fix this?

The original function which worked for SSR was removed, and the new one exports.shell was added sucessfully.


问:
How to add optional chaining to JSON object?
I am trying to compare a value within a JSON object with a variable:

```<code>if (resp.userdetails.name == username) {
// do something
}
</code>```

The problem is that not all resp objects have userdetails, so I get this error message sometimes:

Cannot read properties of undefined (reading 'name')

I have tried to use ? to say it might be optional (or not exist):

```<code>if (resp.userdetails?.name == username)
</code>```

But I get an Unexpected token error in that case.

Can someone please tell me how I can update my if statement to say userdetails may not always be in the response, but if it is, then check name is equal to username?

答:
If you installed lodash into your project, then you can use

```<code>_.get(resp,"userdetails.name")
</code>```

as documented.

If you haven't installed lodash, then I strongly suggest you install from npm because lodash is the best and the most widely used utility package.

Body:
I am trying to compare a value within a JSON object with a variable:

if (resp.userdetails.name == username) {
// do something
}

The problem is that not all resp objects have userdetails, so I get this error message sometimes:

Cannot read properties of undefined (reading 'name')

I have tried to use ? to say it might be optional (or not exist):

if (resp.userdetails?.name == username)

But I get an Unexpected token error in that case.

Can someone please tell me how I can update my if statement to say userdetails may not always be in the response, but if it is, then check name is equal to username?

Body:
If you installed lodash into your project, then you can use

_.get(resp,"userdetails.name")

as documented.

If you haven't installed lodash, then I strongly suggest you install from npm because lodash is the best and the most widely used utility package.


问:
How to install multiple .deb files but in specific order with single linux command
I have 4 debian installer :

```<code>abc.deb
jkl.deb
pqr.deb
xyz.deb
</code>```

I want to install jkl and xyz first, and then I want to install abc.deb and pqr.deb. So the sequence/order the .deb files should be installed should be : jkl.deb , xyz.deb, abc.deb, pqr.deb.

PS:

When I am trying to run apt-get install ./*.deb it is picking the .deb files in random (or maybe alphabetically) order.

So I did apt-get install ./jkl.deb ./xyz.deb ./abc.deb ./pqr.deb but still I am seeing that pqr.deb is Setting up first before abc.deb

Can someone let me know how can i install these four deb in specific order by single linux command ?

答:
As far as I know, the installation of packages follows an alphabetical order along with dependencies. So, if you try to install package X and Y but they have A and B as dependencies, the installation order would be: A, B, X and Y.
In your case, you might have to use the following syntax:</p>
```<code>apt install X && apt install Y
</code>```

Body:
I have 4 debian installer :

abc.deb
jkl.deb
pqr.deb
xyz.deb

I want to install jkl and xyz first, and then I want to install abc.deb and pqr.deb. So the sequence/order the .deb files should be installed should be : jkl.deb , xyz.deb, abc.deb, pqr.deb.

PS:

When I am trying to run apt-get install ./*.deb it is picking the .deb files in random (or maybe alphabetically) order.

So I did apt-get install ./jkl.deb ./xyz.deb ./abc.deb ./pqr.deb but still I am seeing that pqr.deb is Setting up first before abc.deb

Can someone let me know how can i install these four deb in specific order by single linux command ?

Body:
As far as I know, the installation of packages follows an alphabetical order along with dependencies. So, if you try to install package X and Y but they have A and B as dependencies, the installation order would be: A, B, X and Y.
In your case, you might have to use the following syntax:

apt install X && apt install Y


问:
DataDog trace JMS
I'am using the "dd-trace-ot" version 0.93.0 lib to trace my methods using DataDog.

I'am using spring JMS to consume messages. What i want is to search for the service in DataDog and see the JMS message consume as a trace, but i can only see HTTP requests.

I have a serice that from a HTTP request posts a message in the queue so another service can consume it. In this case, as the trace is started from the HTTP request i'am able to see the entire chain, the start of the request and the message consume. But if i go the service that consume the message i can't see a trace from the JMS.

Another thing is that in the case above, in the flame graph the service that consumes has the subtitle "jms" and not the service name (the service names i correct in the span tags).

How can i make DataDog shows the span as a trace in the service?

答:
Datadog will not do this automaticly using @Trace.
What i had to do is create a span by hand on the JMS annotated method and set the tag "service.name".</p>
```<code>@JmsListerner(...)
@Trace
public void receiveMessage(Message message) {
    var span = GlobalTracer.get().activeSpan();

    if (span != null) {
        span.setTag(DDTags.SERVICE_NAME, "servie-name"); // this is the same as "service.name"
    }

    try {
        ...
    } finally {
        if (span != null)  span.finish();
    }

}
</code>```

Title: DataDog trace JMS

Body:
Datadog will not do this automaticly using @Trace.
What i had to do is create a span by hand on the JMS annotated method and set the tag "service.name".

@JmsListerner(...)
@Trace
public void receiveMessage(Message message) {
    var span = GlobalTracer.get().activeSpan();

    if (span != null) {
        span.setTag(DDTags.SERVICE_NAME, "servie-name"); // this is the same as "service.name"
    }

    try {
        ...
    } finally {
        if (span != null)  span.finish();
    }

}


问:
No matching distribution found for botocore<1.22.0,>=1.21.0 (from awsebcli)
CircleCi returns the following error:

No matching distribution found for botocore <1.22.0,> = 1.21.0 (from awsebcli).

My config.yml file installs the following dependencies:

sudo apt-get -y -qq update

sudo apt-get install python3-pip python-dev build-essential

sudo pip3 install --upgrade setuptools

sudo pip3 install awsebcli --upgrade pip3 install awscli

答:
If you are working on a docker container provided by aws:  FROM amazon/aws-cli the python version is: 2.7.18

In that case, if you see this error:

```<code>ERROR: After October 2020 you may experience errors when installing or updating packages. This is because pip will change the way that it resolves dependency conflicts.
</code>```

I used this to fix it:

```<code>pip install awsebcli botocore==1.19.63 --upgrade --use-feature=2020-resolver
</code>```

1.19.63 could be different in your case

Body:
If you are working on a docker container provided by aws:  FROM amazon/aws-cli the python version is: 2.7.18

In that case, if you see this error:

ERROR: After October 2020 you may experience errors when installing or updating packages. This is because pip will change the way that it resolves dependency conflicts.

I used this to fix it:

pip install awsebcli botocore==1.19.63 --upgrade --use-feature=2020-resolver

1.19.63 could be different in your case


问:
css not updating after re-redering component in redux react
I am trying to create a webpage using React.
used redux for data access.

My problem is that when I click on any product, it shows me a perfect page, but if I go back and then again click on another product, my page shows me the data of the new product, but it does not change the photo height in CSS.

home page

product 1product 2(its doesnt changing first image height)

```<code>export const productDetailsReducer = (state = { product: {} }, action) => {

switch (action.type) {
    case PRODUCT_DETAILS_REQUEST:
        return {
            loading: true,
            ...state     <------i am sending the previous state
        }
    case PRODUCT_DETAILS_SUCCESS:
        return {
            loading: false,
            product: action.payload,
        }
    case PRODUCT_DETAILS_FAIL:
        return {
            loading: false,
            error: action.payload
        }
    case CLEAR_ERRORS:
        return {
            ...state,
            error: null
        }

    default:
        return state
}
</code>```

答:
You must first iterate, and then provide the changes.

        return {
            ...state     <------ iterate
            loading: true, <----- set new values
        }
```
<p>In addition, you should always iterate, just to make sure, you're not changing the whole state.</p>
<pre class="lang-js prettyprint-override"><code>export const productDetailsReducer = (state = { product: {} }, action) => {

switch (action.type) {
    case PRODUCT_DETAILS_REQUEST:
        return {
            ...state
            loading: true,
        }
    case PRODUCT_DETAILS_SUCCESS:
        return {
            ...state,
            loading: false,
            product: action.payload,
        }
    case PRODUCT_DETAILS_FAIL:
        return {
            ...state,
            loading: false,
            error: action.payload
        }
    case CLEAR_ERRORS:
        return {
            ...state,
            error: null
        }

    default:
        return state
}
</code>```

Body:
I am trying to create a webpage using React.
used redux for data access.

My problem is that when I click on any product, it shows me a perfect page, but if I go back and then again click on another product, my page shows me the data of the new product, but it does not change the photo height in CSS.

home page

product 1product 2(its doesnt changing first image height)

export const productDetailsReducer = (state = { product: {} }, action) => {

switch (action.type) {
    case PRODUCT_DETAILS_REQUEST:
        return {
            loading: true,
            ...state     <------i am sending the previous state
        }
    case PRODUCT_DETAILS_SUCCESS:
        return {
            loading: false,
            product: action.payload,
        }
    case PRODUCT_DETAILS_FAIL:
        return {
            loading: false,
            error: action.payload
        }
    case CLEAR_ERRORS:
        return {
            ...state,
            error: null
        }

    default:
        return state
}

Body:
You must first iterate, and then provide the changes.

        return {
            ...state     <------ iterate
            loading: true, <----- set new values
        }

In addition, you should always iterate, just to make sure, you're not changing the whole state.

export const productDetailsReducer = (state = { product: {} }, action) => {

switch (action.type) {
    case PRODUCT_DETAILS_REQUEST:
        return {
            ...state
            loading: true,
        }
    case PRODUCT_DETAILS_SUCCESS:
        return {
            ...state,
            loading: false,
            product: action.payload,
        }
    case PRODUCT_DETAILS_FAIL:
        return {
            ...state,
            loading: false,
            error: action.payload
        }
    case CLEAR_ERRORS:
        return {
            ...state,
            error: null
        }

    default:
        return state
}


问:
curl to get a 200 instead of 308
i have a shell script to curl an url and test if it's ok.
On web browser i have no problem, i have the content i'm waiting for.

but after running this shell :

```<code>#!/bin/bash

URL="www.mypersonalURL.com/"
STATUS=$(curl -s -o /dev/null -w "%{http_code}\n" $URL)
if [ $STATUS == 200 ] ; then
   echo "$URL is up, returned $STATUS"
else
   echo "$URL is not up, returned $STATUS"
fi
</code>```

i always get a 308 code, what to do to make the redirection go forward and land on a 200 ?

答:
You are not following the redirect in your curl statement. Add -L to your curl.

URL="www.mypersonalURL.com/"
STATUS=$(curl -L -s -o /dev/null -w "%{http_code}\n" $URL)
```

Title: curl to get a 200 instead of 308

Body:
i have a shell script to curl an url and test if it's ok.
On web browser i have no problem, i have the content i'm waiting for.

but after running this shell :

#!/bin/bash

URL="www.mypersonalURL.com/"
STATUS=$(curl -s -o /dev/null -w "%{http_code}\n" $URL)
if [ $STATUS == 200 ] ; then
   echo "$URL is up, returned $STATUS"
else
   echo "$URL is not up, returned $STATUS"
fi

i always get a 308 code, what to do to make the redirection go forward and land on a 200 ?


问:
Convert to regular date, time and AM or PM
I am trying to convert a date that is returned to me with it in this format:

2022-02-09T14:43:32

I am trying to get it to look like this

2/9/2022 2:43PM

I tried this but it says it is not a valid format.

```<code>workRow["ShiftStart"] = DateTime.ParseExact(theTempsDataSet.Tables[0].Rows[i]["shiftStartTime"].ToString(), "dd/mm/yyyy hh:mmtt", CultureInfo.InvariantCulture).ToString();
</code>```

答:
You just have to use the right datetime format :

DateTime date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500); Console.WriteLine(date1.ToString("MM/dd/yyyy hh:mm tt",CultureInfo.CreateSpecificCulture("en-US")));

Read:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#tSpecifier

Body:
I am trying to convert a date that is returned to me with it in this format:

2022-02-09T14:43:32

I am trying to get it to look like this

2/9/2022 2:43PM

I tried this but it says it is not a valid format.

workRow["ShiftStart"] = DateTime.ParseExact(theTempsDataSet.Tables[0].Rows[i]["shiftStartTime"].ToString(), "dd/mm/yyyy hh:mmtt", CultureInfo.InvariantCulture).ToString();


问:
Maven 3 dependency resolution fails until maven-metadata-local.xml files are deleted [maven-invoker-plugin related]
In one of my Maven projects, dependency resolution will succeed once, then fail for later build attempts:

```<code>[WARNING] The POM for commons-logging:commons-logging:jar:1.1.1 is missing, no dependency information available
[WARNING] The POM for commons-httpclient:commons-httpclient:jar:3.1 is missing, no dependency information available
[WARNING] The POM for javax.mail:mail:jar:1.4.4 is missing, no dependency information available
</code>```

…and so on, until I delete the maven-metadata-local.xml files corresponding to the failing artifacts (e.g. ~/.m2/repository/commons-logging/commons-logging/maven-metadata-local.xml).  After those files are deleted, the next mvn invocation proceeds properly; the metadata files are restored by that invocation (presumably as part of the process of checking my upstream repositories/mirrors for updated artifacts), and I am again presented with the above errors until I again delete the metadata files.

This impacts multiple projects, though it appears to be limited to a particular set of dependencies.  I suppose I could go nuclear and blow away my local repo, but I'd like to understand what the problem is.

Thoughts?

Update: It looks like it's the maven-invoker-plugin (which these builds are using for general-purpose integration testing) that is producing these maven-metadata-local.xml files.  I'm not using an integration-testing-only local repo as described here, simply because doing so causes the re-downloading of all transitive dependencies (unless you want to maintain an integration-specific settings.xml file!!!).  I've used the invoker plugin with a variety of other projects in this way with good results -- certainly never encountering a wedged local repository in the process like this.

Update 2 OK, this is repeatable, even after starting with a completely fresh local repository.  This is on OS X, Java 1.6.0_24 with Maven 3.0.3; note that Maven 2.2.1 does NOT exhibit this problem.

Here's one of the projects in question: the 1.3.0-compat branch of rummage.  To reproduce:

```<code>> mvn clean test
# no error -- can run this and other builds that don't involve maven-invoker-plugin all day w/o problems
> mvn clean integration-test
# FAIL: "Could not resolve dependencies", with warnings as noted above
> mvn clean test
# FAIL: "Could not resolve dependencies", with warnings as noted above
</code>```

Once the local repository is borked (by the generation of the maven-metadata-local.xml files, AFAICT), no builds will get past the dependency resolution stage.

Running mvn -X reveals lines like this for each artifact that is later apparently not found:

```<code>[DEBUG] Verifying availability of /Users/chas/.m2/repository/javax/mail/mail/1.4.4/mail-1.4.4.jar from []
</code>```

Of course, /Users/chas/.m2/repository/javax/mail/mail/1.4.4/mail-1.4.4.jar et al. does exist, as does /Users/chas/.m2/repository/javax/mail/mail/1.4.4/mail-1.4.4.pom.  Totally puzzled.  At this point, I'm assuming this is a bug in Maven 3 (or some underlying library), now that I see that 2.2.1 is clean.

Update 3 Bug report filed with Maven project.

答: This issue is resolved in aether 1.12, one rev above the aether 1.11 library that ships with Maven 3.0.3.  Replacing aether 1.11 with 1.12 in one's Maven install results in expected behaviour (as noted in the bug I filed).  Here's hoping Maven 3.0.4 is released with aether 1.12 ASAP. :-)</p>

ContentLicense: CC BY-SA 3.0

Body:
In one of my Maven projects, dependency resolution will succeed once, then fail for later build attempts:

[WARNING] The POM for commons-logging:commons-logging:jar:1.1.1 is missing, no dependency information available
[WARNING] The POM for commons-httpclient:commons-httpclient:jar:3.1 is missing, no dependency information available
[WARNING] The POM for javax.mail:mail:jar:1.4.4 is missing, no dependency information available

…and so on, until I delete the maven-metadata-local.xml files corresponding to the failing artifacts (e.g. ~/.m2/repository/commons-logging/commons-logging/maven-metadata-local.xml).  After those files are deleted, the next mvn invocation proceeds properly; the metadata files are restored by that invocation (presumably as part of the process of checking my upstream repositories/mirrors for updated artifacts), and I am again presented with the above errors until I again delete the metadata files.

This impacts multiple projects, though it appears to be limited to a particular set of dependencies.  I suppose I could go nuclear and blow away my local repo, but I'd like to understand what the problem is.

Thoughts?

Update: It looks like it's the maven-invoker-plugin (which these builds are using for general-purpose integration testing) that is producing these maven-metadata-local.xml files.  I'm not using an integration-testing-only local repo as described here, simply because doing so causes the re-downloading of all transitive dependencies (unless you want to maintain an integration-specific settings.xml file!!!).  I've used the invoker plugin with a variety of other projects in this way with good results -- certainly never encountering a wedged local repository in the process like this.

Update 2 OK, this is repeatable, even after starting with a completely fresh local repository.  This is on OS X, Java 1.6.0_24 with Maven 3.0.3; note that Maven 2.2.1 does NOT exhibit this problem.

Here's one of the projects in question: the 1.3.0-compat branch of rummage.  To reproduce:

> mvn clean test
# no error -- can run this and other builds that don't involve maven-invoker-plugin all day w/o problems
> mvn clean integration-test
# FAIL: "Could not resolve dependencies", with warnings as noted above
> mvn clean test
# FAIL: "Could not resolve dependencies", with warnings as noted above

Once the local repository is borked (by the generation of the maven-metadata-local.xml files, AFAICT), no builds will get past the dependency resolution stage.

Running mvn -X reveals lines like this for each artifact that is later apparently not found:

[DEBUG] Verifying availability of /Users/chas/.m2/repository/javax/mail/mail/1.4.4/mail-1.4.4.jar from []

Of course, /Users/chas/.m2/repository/javax/mail/mail/1.4.4/mail-1.4.4.jar et al. does exist, as does /Users/chas/.m2/repository/javax/mail/mail/1.4.4/mail-1.4.4.pom.  Totally puzzled.  At this point, I'm assuming this is a bug in Maven 3 (or some underlying library), now that I see that 2.2.1 is clean.

Update 3 Bug report filed with Maven project.


问:
How to create a table with multiple classification in R
I am having problems in create a report table with a data frame like this:

```<code>   id sex    age    location
   1   m   0-17       Miami
   2   f  18-64 Los Angeles
   3   f over64     Ontario
   4   m  18-64       Paris
   5   m  18-64     Ontario
   6   m over64       Miami
   7   f over64       Miami
   8   f  18-64 Los Angeles
   9   m  18-64       Other
  10   m over64       Other
</code>```

my desired table should look like this:
Deired Table

Any idea how to do it.

答:
I think if you look through the packages gt and gtsummary, you'll find what you're looking for. For example, this is close to the example you provided as your desired output.

```<code>library(gtsummary)
library(gt)

df1 <- read.table(header = T,
                  text = "Id Sex Age Location # notice I capitalized names
1 m 0-17 Miami
2 f 18-64 Los.Angeles
3 f over64 Ontario
4 m 18-64 Paris
5 m 18-64 Ontario
6 m over64 Miami
7 f over64 Miami
8 f 18-64 Los.Angeles
9 m 18-64 Other
10 m over64 Other", sep = " ")

tbl_summary(df1[,2:4]) %>% add_n() %>% bold_labels
</code>```

This is the output table.

If you want to customize it, pipe in as_gt() and then use any of the functions in the gt package to customize it further.

Body:
I am having problems in create a report table with a data frame like this:

   id sex    age    location
   1   m   0-17       Miami
   2   f  18-64 Los Angeles
   3   f over64     Ontario
   4   m  18-64       Paris
   5   m  18-64     Ontario
   6   m over64       Miami
   7   f over64       Miami
   8   f  18-64 Los Angeles
   9   m  18-64       Other
  10   m over64       Other

my desired table should look like this:
Deired Table

Any idea how to do it.

Body:
I think if you look through the packages gt and gtsummary, you'll find what you're looking for. For example, this is close to the example you provided as your desired output.

library(gtsummary)
library(gt)

df1 <- read.table(header = T,
                  text = "Id Sex Age Location # notice I capitalized names
1 m 0-17 Miami
2 f 18-64 Los.Angeles
3 f over64 Ontario
4 m 18-64 Paris
5 m 18-64 Ontario
6 m over64 Miami
7 f over64 Miami
8 f 18-64 Los.Angeles
9 m 18-64 Other
10 m over64 Other", sep = " ")

tbl_summary(df1[,2:4]) %>% add_n() %>% bold_labels

This is the output table.

If you want to customize it, pipe in as_gt() and then use any of the functions in the gt package to customize it further.


答:
Try this:</p>
```<code>print(np.concatenate([emb['name'] for emb in embs]))
</code>```

Title: Concatenate numpy arrays to a single array

Body:
I am trying to merge the two <class 'numpy.ndarray'> into a single array.

Code that I tried:

for emb in embs:
   print(np.concatenate( emb['name'], axis=0 ))

Input:

[[-0.05646843 -0.00381141 -0.05721215 0.06029008]
 [-0.02690301  0.04218878  0.00404305 0.05841358]]
[[-0.02675129  0.03649405 -0.04379312 -0.04826404]
 [ 0.01131434  0.0581139   0.00785002  -0.02065904]]

Output:

[[-0.05646843 -0.00381141 -0.05721215 0.06029008]
 [-0.02690301  0.04218878  0.00404305 0.05841358]
 [-0.02675129  0.03649405 -0.04379312 -0.04826404]
 [ 0.01131434  0.0581139   0.00785002  -0.02065904]]

Any leads would be appreciated.

Body:
Try this:

print(np.concatenate([emb['name'] for emb in embs]))


问:
Remove duplicates records in a MySQL table with key but not primary key
I need to remove duplicate records (just to keep one copy) from a MySQL table in MyISAM format. I have read many questions in Stackoverflow about similar issues but always the people use an ID field as unique id or similar and I haven't this field because my "Key" could be duplicated. I want to remove rows with the 'Fecha' and 'Equip' duplicated.

```<code>CREATE TABLE `pfc` (
`Fecha` datetime NOT NULL,
`Equip` int(10) unsigned NOT NULL,
`Value` double NOT NULL,
KEY `Fecha` (`Fecha`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AVG_ROW_LENGTH=21 ROW_FORMAT=FIXED;
</code>```

An example table data:

```<code>Fecha              | Equip | Value
06/02/2011 0:00:11 |  22   |  29.0
06/02/2011 0:22:11 |  22   |  45.3
06/02/2011 0:00:11 |  22   |  29.0
</code>```

The result should be:

```<code>Fecha              | Equip | Value
06/02/2011 0:00:11 |  22   |  29.0
06/02/2011 0:22:11 |  22   |  45.3
</code>```

This structure is not possible to change. I cannot use PRIMARY KEY or UNIQUE INDEX solutions. To create a temporal table without duplicates and then rename would be a poor solutions also, because the KEY and another parameters will be lost.

Thanks

答:
Just as a test, try this to see if it is what you want  </p>

```<code>CREATE TABLE new_pfc AS
SELECT * FROM pfc GROUP BY fecha, equip
</code>```

Body:
I need to remove duplicate records (just to keep one copy) from a MySQL table in MyISAM format. I have read many questions in Stackoverflow about similar issues but always the people use an ID field as unique id or similar and I haven't this field because my "Key" could be duplicated. I want to remove rows with the 'Fecha' and 'Equip' duplicated.

CREATE TABLE `pfc` (
`Fecha` datetime NOT NULL,
`Equip` int(10) unsigned NOT NULL,
`Value` double NOT NULL,
KEY `Fecha` (`Fecha`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AVG_ROW_LENGTH=21 ROW_FORMAT=FIXED;

An example table data:

Fecha              | Equip | Value
06/02/2011 0:00:11 |  22   |  29.0
06/02/2011 0:22:11 |  22   |  45.3
06/02/2011 0:00:11 |  22   |  29.0

The result should be:

Fecha              | Equip | Value
06/02/2011 0:00:11 |  22   |  29.0
06/02/2011 0:22:11 |  22   |  45.3

This structure is not possible to change. I cannot use PRIMARY KEY or UNIQUE INDEX solutions. To create a temporal table without duplicates and then rename would be a poor solutions also, because the KEY and another parameters will be lost.

Thanks

Body:
Just as a test, try this to see if it is what you want

CREATE TABLE new_pfc AS
SELECT * FROM pfc GROUP BY fecha, equip


答: ParseExact should have date format to parse date from file. So, it should have "yyyy-MM-ddTHH:ss:mm" date format. After parsing it will be in DateTime type. To convert it back to string, you can call .ToString("dd/mm/yyyy hh:mmtt") on that. Where "dd/mm/yyyy hh:mmtt" is your custom date format

Title: Convert to regular date, time and AM or PM


问:
Invalid character in header content ["Host"] Postman
When i try to test api with localhost:[port] it gives the invalid character in header ["Host"] console error. I am using dotnet core webApi. I cross checked the CORS configuration from api end it is fine. The issue is on the Postman side.
Postman version: v8.7.0

答:
I thought the issue was in a variable I was using because the error was telling me there's an invalid character in my host https://localhost:4431 which is exactly the value of my variable.

I figured out the invalid character was actually not in my variable but in the rest of the URL in my request.

Turns out, when copying endpoint names from the Swagger of my API, I was also copying an invisible character %E2%80%8B. I saw it when checking the API's console RequestPath:/%E2%80%8BmyEndpoint

Removing this invisible character solved the issue


问:
How to run shell command after gunicorn service? this is for docker enterypoint.sh file
Below is my docker enterypoint.sh file code

```<code>#!/bin/bash
set -e

python3 test1.py

gunicorn -b 0.0.0.0:8000 "app:app" --workers=1 --threads=10 --timeout=3600

node /home/test2.js
</code>```

I want to run test2.js nodejs app after gunicorn service starts because test2.js required to connect with localhost:8000. Please help me with a solution for this

答:
Think the ideal solution will be to deploy 2 different containers using docker-compose, one for gunicorn and another one for test2.js nodejs app.

But could run test2.js nodejs script after starting gunicorn service using below code by inserting "&" at the end of gunicorn line

```<code>#!/bin/bash
set -e

python3 test1.py

gunicorn -b 0.0.0.0:8000 "app:app" --workers=1 --threads=10 --timeout=3600 &

node /home/test2.js
</code>```

Body:
Below is my docker enterypoint.sh file code

#!/bin/bash
set -e

python3 test1.py

gunicorn -b 0.0.0.0:8000 "app:app" --workers=1 --threads=10 --timeout=3600

node /home/test2.js

I want to run test2.js nodejs app after gunicorn service starts because test2.js required to connect with localhost:8000. Please help me with a solution for this

Body:
Think the ideal solution will be to deploy 2 different containers using docker-compose, one for gunicorn and another one for test2.js nodejs app.

But could run test2.js nodejs script after starting gunicorn service using below code by inserting "&" at the end of gunicorn line

#!/bin/bash
set -e

python3 test1.py

gunicorn -b 0.0.0.0:8000 "app:app" --workers=1 --threads=10 --timeout=3600 &

node /home/test2.js


问:
Round Double to 1 decimal place kotlin: from 0.044999 to 0.1
I have a Double variable that is 0.0449999 and I would like to round it to 1 decimal place 0.1 .

I am using Kotlin but the Java solution is also helpful.

val number:Double = 0.0449999

I tried getting 1 decimal place with these two solutions:

val solution = Math.round(number * 10.0) / 10.0

val solution = String.format("%.1f", number)

The problem is that I get 0.0 in both cases because it rounds the number from 0.04 to 0.0. It doesn't take all decimals and round it.

I would like to obtain 0.1: 0.045 -> 0.05 -> 0.1

答:
For new comers

Using String.format for decimal precision can lead to problems for different languages.

Use the following code to convert Double to as many decimal places as you want.

```<code>val price = 6.675668

//to convert to 2 decimal places
totalTime = Math.round(totalTime * 100.0) / 100.00
// totalTime = 6.68

//to convert to 4 decimal places
totalTime = Math.round(totalTime * 10000.0) / 10000.00
// totalTime = 6.6757
</code>```

Body:
For new comers

Using String.format for decimal precision can lead to problems for different languages.

Use the following code to convert Double to as many decimal places as you want.

val price = 6.675668

//to convert to 2 decimal places
totalTime = Math.round(totalTime * 100.0) / 100.00
// totalTime = 6.68

//to convert to 4 decimal places
totalTime = Math.round(totalTime * 10000.0) / 10000.00
// totalTime = 6.6757


问:
Pass same arguments to another function in Dart?
I'm trying to create a util class which has helper functions that create example objects for use in unit tests.  For each object I have, I'm simply providing a createXYZExample function where all of the named optional arguments are given default values and the functions simply return a new instance of the object, created with all of the same arguments. Here's an example:

```<code>class MyClass{
  String param1;
  String param2;
  String param3;
  MyClass({this.param1, this.param2, this.param3});
}

MyClass createMyClassExample({
  String param1 = 'default Param1',
  String param2 = 'default Param2',
  String param3 = 'default Param3',
}) => MyClass(
  param1: param1,
  param2: param2,
  param3: param3
);
</code>```

You can see that my 'createMyClassExample' function has a lot of boiler plate in repeating the params, this becomes even more painful for classes with a large number of optional parameters.  Is there some way to do something like this?

```<code>MyClass createMyClassExample({
  String param1 = 'default Param1',
  String param2 = 'default Param2',
  String param3 = 'default Param3',
}) => MyClass(arguments);
</code>```

If not, is there some better way to do this so I'm not having to add so much repeated code for the arguments?

答:
I if understand you correctly, you need some method like copyWith:

```<code>class MyClass {
  String param1;
  String param2;
  String param3;
  MyClass({
    required this.param1,
    required this.param2,
    required this.param3,
  });

  MyClass copyWith({
    String? param1,
    String? param2,
    String? param3,
  }) =>
      MyClass(
        param1: param1 ?? this.param1,
        param2: param2 ?? this.param2,
        param3: param3 ?? this.param3,
      );
}

final myClass = MyClass(
  param1: 'default Param1',
  param2: 'default Param2',
  param3: 'default Param3',
);

final myClass2 = myClass.copyWith(
  param1: 'new param1',
);

final myClass3 = myClass.copyWith(
  param2: 'new param2',
  param3: 'new param3',
);
</code>```

Body:
I'm trying to create a util class which has helper functions that create example objects for use in unit tests.  For each object I have, I'm simply providing a createXYZExample function where all of the named optional arguments are given default values and the functions simply return a new instance of the object, created with all of the same arguments. Here's an example:

class MyClass{
  String param1;
  String param2;
  String param3;
  MyClass({this.param1, this.param2, this.param3});
}

MyClass createMyClassExample({
  String param1 = 'default Param1',
  String param2 = 'default Param2',
  String param3 = 'default Param3',
}) => MyClass(
  param1: param1,
  param2: param2,
  param3: param3
);

You can see that my 'createMyClassExample' function has a lot of boiler plate in repeating the params, this becomes even more painful for classes with a large number of optional parameters.  Is there some way to do something like this?

MyClass createMyClassExample({
  String param1 = 'default Param1',
  String param2 = 'default Param2',
  String param3 = 'default Param3',
}) => MyClass(arguments);

If not, is there some better way to do this so I'm not having to add so much repeated code for the arguments?

Body:
I if understand you correctly, you need some method like copyWith:

class MyClass {
  String param1;
  String param2;
  String param3;
  MyClass({
    required this.param1,
    required this.param2,
    required this.param3,
  });

  MyClass copyWith({
    String? param1,
    String? param2,
    String? param3,
  }) =>
      MyClass(
        param1: param1 ?? this.param1,
        param2: param2 ?? this.param2,
        param3: param3 ?? this.param3,
      );
}

final myClass = MyClass(
  param1: 'default Param1',
  param2: 'default Param2',
  param3: 'default Param3',
);

final myClass2 = myClass.copyWith(
  param1: 'new param1',
);

final myClass3 = myClass.copyWith(
  param2: 'new param2',
  param3: 'new param3',
);


问:
Apache Airflow get execution time difference between two DAG runs
I'm currently trying to figure out how to use two dag runs' execution time to get their time difference to prevent from the DAG processing the same file multiple times. Any idea how could I check this?</p>

答:
You could use croniter, a library packaged with Airflow to do this:

>>> from airflow import DAG
>>> from datetime import timedelta, datetime
>>> from croniter import croniter
>>>
>>> dag_a = DAG(
...     dag_id="A",
...     schedule_interval="00 10 * * *",
... )
>>>
>>> dag_b = DAG(
...     dag_id="B",
...     schedule_interval="00 14 * * *",
... )
>>>
>>> now = datetime.now()
>>> cron_a = croniter(dag_a.schedule_interval, now)
>>> cron_b = croniter(dag_b.schedule_interval, now)
>>> time_difference = cron_b.get_prev(datetime) - cron_a.get_prev(datetime)
>>> time_difference
datetime.timedelta(0, 14400)
>>> time_difference.seconds
14400 # 4 hours
```


问:
error with the result of a replication procedure
I have a problem with the following procedure:

```<code>library(igraph)
k <- cbind(c(.2,.2),c(.2,0))

sbm_centr <- replicate(
  2000,
  sample_sbm(49, pref.matrix = k, block.sizes = c(24, 25)) %>%
    centr_degree(.)$centralization
)
</code>```

The issue is that the function generates a result with two arguments (in addition to the ID of each replication), so the procedure reports an error: Error in .$centr_degree(.) : 3 arguments passed to '$' requiring 2"

I tried, unsuccessfully, to save one of the arguments with the following expression: centr_degree(.)$centralization[1])

But the list contains only 0s. Thanks in advance for your comments.

答:
Either block the code with {}

```<code>library(dplyr)
library(igraph)
library(purrr)
sbm_centr <- replicate(
  2000,
  sample_sbm(49, pref.matrix = k, block.sizes = c(24, 25)) %>%
    {centr_degree(.)$centralization}
)
</code>```

or use list element extractions in a pipe with pluck

```<code>sbm_centr <- replicate(2000,
   sample_sbm(49, pref.matrix = k, block.sizes = c(24, 25)) %>%
      centr_degree(.) %>%
      pluck("centralization"))
</code>```

-output

```<code>> str(sbm_centr)
 num [1:2000] 0.158 0.188 0.128 0.153 0.165 ...
</code>```

Body:
I have a problem with the following procedure:

library(igraph)
k <- cbind(c(.2,.2),c(.2,0))

sbm_centr <- replicate(
  2000,
  sample_sbm(49, pref.matrix = k, block.sizes = c(24, 25)) %>%
    centr_degree(.)$centralization
)

The issue is that the function generates a result with two arguments (in addition to the ID of each replication), so the procedure reports an error: Error in .$centr_degree(.) : 3 arguments passed to '$' requiring 2"

I tried, unsuccessfully, to save one of the arguments with the following expression: centr_degree(.)$centralization[1])

But the list contains only 0s. Thanks in advance for your comments.

Body:
Either block the code with {}

library(dplyr)
library(igraph)
library(purrr)
sbm_centr <- replicate(
  2000,
  sample_sbm(49, pref.matrix = k, block.sizes = c(24, 25)) %>%
    {centr_degree(.)$centralization}
)

or use list element extractions in a pipe with pluck

sbm_centr <- replicate(2000,
   sample_sbm(49, pref.matrix = k, block.sizes = c(24, 25)) %>%
      centr_degree(.) %>%
      pluck("centralization"))

-output

> str(sbm_centr)
 num [1:2000] 0.158 0.188 0.128 0.153 0.165 ...


答:
use >= operator

example

```<code>delete from users where id >= 754
</code>```

Title: Delete ranges of id's

Body:
I have this huge SQL query which I would like to reduce:

DELETE
FROM users
WHERE id in (754, 755, 756, 757, 758, 759, 795, 796, 797, 798, 799, 765,
766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794);

I tried:

DELETE
FROM users
WHERE id => 754 AND id <= 759
AND id => 795 AND id <= 799
AND id => 765 AND id <= 794;

But I get error:

ERROR: syntax error at or near "=>"
Position: 42

Do you know how I can fix this issue?

Body:
use >= operator

example

delete from users where id >= 754


问:
SQL Statement using Database name pulled from a select statement
Here is my scenario
ParentDB has table with JournalDB Names (I have the select to return the latest JournalDB Name)

JournalDBName = select top 1 DBName from ParentDB.dbo.JournalNames order by ObjectID desc
```
<p>Trying to run 2nd Select statement where I can "USE" the JournalDBName
similar to</p>
<pre class="lang-sql prettyprint-override"><code>USE "JournalDBName"
select
Data1,
Data2,
from JournalRecordLog
</code>```

I'm stuck on passing JournalDBName for "USE" to the 2nd statement.

Any help is appreciated

答:
You need to use dynamic SQL:</p>
```<code>DECLARE @db   sysname,
        @exec nvarchar(1000),
        @sql  nvarchar(max);

SELECT TOP (1) @db = DBName
  FROM ParentDB.dbo.JournalNames
  ORDER BY ObjectID DESC;

SET @exec = QUOTENAME(@db) + N'.sys.sp_executesql';

SET @sql = N'SELECT Data1, Data2 FROM dbo.JournalRecordLog;';

EXEC @exec @sql;
</code>```

Body:
Here is my scenario
ParentDB has table with JournalDB Names (I have the select to return the latest JournalDB Name)

JournalDBName = select top 1 DBName from ParentDB.dbo.JournalNames order by ObjectID desc

Trying to run 2nd Select statement where I can "USE" the JournalDBName
similar to

USE "JournalDBName"
select
Data1,
Data2,
from JournalRecordLog

I'm stuck on passing JournalDBName for "USE" to the 2nd statement.

Any help is appreciated

Body:
You need to use dynamic SQL:

DECLARE @db   sysname,
        @exec nvarchar(1000),
        @sql  nvarchar(max);

SELECT TOP (1) @db = DBName
  FROM ParentDB.dbo.JournalNames
  ORDER BY ObjectID DESC;

SET @exec = QUOTENAME(@db) + N'.sys.sp_executesql';

SET @sql = N'SELECT Data1, Data2 FROM dbo.JournalRecordLog;';

EXEC @exec @sql;


问:
How to parallelize a python code that has two different pandas dataframes?
I have two dataframes and have a code to extract some data from one of the dataframes and add to the other dataframe:

```<code>sales= pd.read_excel("data.xlsx", sheet_name = 'sales', header = 0)
born= pd.read_excel("data.xlsx", sheet_name = 'born', header = 0)

bornuni = born.number.unique()
for babies in bornuni:
    datafame = born[born["id"]==number]
    for i, r in sales.iterrows():
        if r["number"] == babies:
            sales.loc[i,'ini_weight'] = datafame["weight"].iloc[0]
            sales.loc[i,'ini_date'] = datafame["date of birth"].iloc[0]
        else:
            pass
</code>```

this is pretty inefficient with bigger data sets so I want to parallelize  this code but I don´t have a clue how to do it. Any help would be great. Here is a link to a mock dataset.

答:
So before worrying about parallelizing, I can't help but notice that you're using lots of for loops to deal with the dataframes. Dataframes are pretty fast when you use their vectorized capabilities.

I see a lot of inefficient use of pandas here, so maybe we first fix that and then worry about throwing more CPU cores at it.

It seems to me you want to accomplish the following:

For each unique baby id number in the born dataframe, you want to update the ini_weight and ini_date fields of the corresponding entry in the sales dataframe.

There's a good chance that you can use some dataframe merging / joining to help you with that, as well as using the pivot table functionality:

https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html
https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html

I strongly suggest you take a look at those, try using the ideas from these articles, and then reframe your question in terms of these operations, because as you correctly notice, looping over all the rows repeatedly to find the row with some matching index is very inefficient.

Body:
I have two dataframes and have a code to extract some data from one of the dataframes and add to the other dataframe:

sales= pd.read_excel("data.xlsx", sheet_name = 'sales', header = 0)
born= pd.read_excel("data.xlsx", sheet_name = 'born', header = 0)

bornuni = born.number.unique()
for babies in bornuni:
    datafame = born[born["id"]==number]
    for i, r in sales.iterrows():
        if r["number"] == babies:
            sales.loc[i,'ini_weight'] = datafame["weight"].iloc[0]
            sales.loc[i,'ini_date'] = datafame["date of birth"].iloc[0]
        else:
            pass

this is pretty inefficient with bigger data sets so I want to parallelize  this code but I don´t have a clue how to do it. Any help would be great. Here is a link to a mock dataset.


问:
Convert decimal mark when reading numbers as input
I have a CSV file with data reading that I want to read into Python. I get lists that contain strings like "2,5". Now doing float("2,5") does not work, because it has the wrong decimal mark.

How do I read this into Python as 2.5?

答:
You may do it the locale-aware way:

```<code>import locale

# Set to users preferred locale:
locale.setlocale(locale.LC_ALL, '')
# Or a specific locale:
locale.setlocale(locale.LC_NUMERIC, "en_DK.UTF-8")

print locale.atof("3,14")
</code>```

Read this section before using this method.

Body:
You may do it the locale-aware way:

import locale

# Set to users preferred locale:
locale.setlocale(locale.LC_ALL, '')
# Or a specific locale:
locale.setlocale(locale.LC_NUMERIC, "en_DK.UTF-8")

print locale.atof("3,14")

Read this section before using this method.


问:
How to set current datetime in gremlin console?
How to set current DateTime in the gremlin console?

I need to add an audit field created_on with current_timestamp as default value

Eg:

```<code>g.addV('student').property('name', 'Thirumal').property('created_on', datetime())
</code>```

In, the above query, I am getting an error on datetime(). What is the syntax to add default date time?

答:
In the Gremlin Console, you can use new Date() if you do not have a version that supports datetime(). Note that datetime() was recently added to Gremlin so you may not have the version that contains it yet. I believe it was added in the 3.5.2 release. Also please see this discussion

Without datetime() you can still do

```<code>gremlin> g.addV('test').property('date', new Date())
==>v[61287]

gremlin> g.V(61287).valueMap()
==>[date:[Thu Feb 10 10:02:18 CST 2022]]
</code>```

UPDATED based on comments:

If you are using Amazon Neptune, the database provides its own version of the datetime function that expects an ISO 8601 compliant date string. So you can do something like this:

g.addV('test').property('date', datetime('2022-02-10'))
```
<p>If you are using Neptune's Jupyter notebooks, to set the current date, you can create a date in a cell above (using Python) of the form</p>
```my_date = # some date calculation that yields an ISO string.
```
<p>or, more concretely:</p>
```import datetime
d=datetime.datetime.now()
my_date = d.strftime('%Y-%m-%d')
```
<p>and inject that string like this:</p>
<pre class="lang-java prettyprint-override"><code>g.addV('test').property('date', datetime('${my_date}'))
</code>```

Body:
How to set current DateTime in the gremlin console?

I need to add an audit field created_on with current_timestamp as default value

Eg:

g.addV('student').property('name', 'Thirumal').property('created_on', datetime())

In, the above query, I am getting an error on datetime(). What is the syntax to add default date time?

Body:
In the Gremlin Console, you can use new Date() if you do not have a version that supports datetime(). Note that datetime() was recently added to Gremlin so you may not have the version that contains it yet. I believe it was added in the 3.5.2 release. Also please see this discussion

Without datetime() you can still do

gremlin> g.addV('test').property('date', new Date())
==>v[61287]

gremlin> g.V(61287).valueMap()
==>[date:[Thu Feb 10 10:02:18 CST 2022]]

UPDATED based on comments:

If you are using Amazon Neptune, the database provides its own version of the datetime function that expects an ISO 8601 compliant date string. So you can do something like this:

g.addV('test').property('date', datetime('2022-02-10'))

If you are using Neptune's Jupyter notebooks, to set the current date, you can create a date in a cell above (using Python) of the form

my_date = # some date calculation that yields an ISO string.

or, more concretely:

import datetime
d=datetime.datetime.now()
my_date = d.strftime('%Y-%m-%d')

and inject that string like this:

g.addV('test').property('date', datetime('${my_date}'))


问:
Why does CSharpExtensions.ClassifyConversion return an explicit reference conversion for object / string?
The CSharpExtensions.ClassifyConversion(Compilation, ITypeSymbol, ITypeSymbol) method returns an explicit reference conversion if called with the special type object as source and the special type string as destination argument:

var objectTypeSymbol = context.Compilation.GetSpecialType(SpecialType.System_Object);
var stringTypeSymbol = context.Compilation.GetSpecialType(SpecialType.System_String);
var conversion = context.Compilation.ClassifyConversion(objectTypeSymbol, stringTypeSymbol);
```

As far as I know C# doesn't specify a built in object to string conversion: C# language reference. Why does it return an explicit reference conversion and what does it imply? How would the c# syntax of such a conversion look like? If ClassifyConversion is called with an empty user defined class as source argument and the string special type  as destination argument, NoConversion is returned as expected.

答:
What you're seeing is just a bog-standard cast of object to string, IE:

public string M(object o)
    => (string)o;
```

IE: At runtime, check if o is an instance of string. If it is, return it as string. If it isn't, throw InvalidCastException.

Specifically you're seeing this case from §10.3.5 Explicit reference conversions:

From object and dynamic to any other reference_type.

You don't see the conversion with your user-defined class because it's more specific than object (and as such is known to never have a reference conversion to string.)

Body:
The CSharpExtensions.ClassifyConversion(Compilation, ITypeSymbol, ITypeSymbol) method returns an explicit reference conversion if called with the special type object as source and the special type string as destination argument:

var objectTypeSymbol = context.Compilation.GetSpecialType(SpecialType.System_Object);
var stringTypeSymbol = context.Compilation.GetSpecialType(SpecialType.System_String);
var conversion = context.Compilation.ClassifyConversion(objectTypeSymbol, stringTypeSymbol);

As far as I know C# doesn't specify a built in object to string conversion: C# language reference. Why does it return an explicit reference conversion and what does it imply? How would the c# syntax of such a conversion look like? If ClassifyConversion is called with an empty user defined class as source argument and the string special type  as destination argument, NoConversion is returned as expected.

Body:
What you're seeing is just a bog-standard cast of object to string, IE:

public string M(object o)
    => (string)o;

IE: At runtime, check if o is an instance of string. If it is, return it as string. If it isn't, throw InvalidCastException.

Specifically you're seeing this case from §10.3.5 Explicit reference conversions:

From object and dynamic to any other reference_type.

You don't see the conversion with your user-defined class because it's more specific than object (and as such is known to never have a reference conversion to string.)


问:
React Axios Uncaught (in promise)
Currently I am trying to receive data from an API with Axios, which gives me an Uncaught (in promise). There is no further information in the error message.

Dashboard.tsx:

```<code>Axios.get("/WeatherForecast/Get").then(response => {
        console.log("success");
        console.log(response);
    }).catch((exception) => {
        console.log(exception);
    });
</code>```

axiosConfig.ts:

```<code>import axios from "axios";
import { URL_API } from "./config/config";

export const configAxios = () => {
axios.defaults.baseURL = URL_API;

axios.interceptors.response.use(function (response) {
    if (response.data) {
        // return success
        if (response.data.status === 200 || response.data.status === 201) {
            return response;
        }
        // reject errors & warnings
        return Promise.reject(response);
    }

    // default fallback
    return Promise.reject(response);
}, function (error) {
    // if the server throws an error (404, 500 etc.)
    return Promise.reject(error);
});
}
</code>```

Response in console:

答:
Update your interceptor to target response.status instead of response.data.status. Per the response schema response.data will provide you the numeric status code that you can do you conditional checks against:

```<code>import axios from "axios";
import { URL_API } from "./config/config";

export const configAxios = () => {
  axios.defaults.baseURL = URL_API;

  axios.interceptors.response.use(
    function (response) {
      if (response.data) {
        // return success
        if (response.status === 200 || response.status === 201) {
          return response;
        }
        // reject errors & warnings
        return Promise.reject(response);
      }

      // default fallback
      return Promise.reject(response);
    },
    function (error) {
      // if the server throws an error (404, 500 etc.)
      return Promise.reject(error);
    }
  );
};
</code>```

Title: React Axios Uncaught (in promise)

Body:
Currently I am trying to receive data from an API with Axios, which gives me an Uncaught (in promise). There is no further information in the error message.

Dashboard.tsx:

Axios.get("/WeatherForecast/Get").then(response => {
        console.log("success");
        console.log(response);
    }).catch((exception) => {
        console.log(exception);
    });

axiosConfig.ts:

import axios from "axios";
import { URL_API } from "./config/config";

export const configAxios = () => {
axios.defaults.baseURL = URL_API;

axios.interceptors.response.use(function (response) {
    if (response.data) {
        // return success
        if (response.data.status === 200 || response.data.status === 201) {
            return response;
        }
        // reject errors & warnings
        return Promise.reject(response);
    }

    // default fallback
    return Promise.reject(response);
}, function (error) {
    // if the server throws an error (404, 500 etc.)
    return Promise.reject(error);
});
}

Response in console:

Body:
Update your interceptor to target response.status instead of response.data.status. Per the response schema response.data will provide you the numeric status code that you can do you conditional checks against:

import axios from "axios";
import { URL_API } from "./config/config";

export const configAxios = () => {
  axios.defaults.baseURL = URL_API;

  axios.interceptors.response.use(
    function (response) {
      if (response.data) {
        // return success
        if (response.status === 200 || response.status === 201) {
          return response;
        }
        // reject errors & warnings
        return Promise.reject(response);
      }

      // default fallback
      return Promise.reject(response);
    },
    function (error) {
      // if the server throws an error (404, 500 etc.)
      return Promise.reject(error);
    }
  );
};