问:
Unable to use graql on commandline
So I am using grakn core 1.5.7 on Ubuntu 18.04.

I want to use graql command.With older versions of grakn it was quite good to have a graql executable available.Here is the command i am using from inside my grakn folder.

```<code>graql console --keyspace prec --file ./schema.gql
</code>```

However in newer versions on and after 1.5.7,I cannot find the same.

I had a look on the bugs section of grakn and i found this to be close but not much related issue. Following which i tried replacing graql to grakn but now i am getting this error

```<code>io.grpc.StatusRuntimeException: UNIMPLEMENTED: Method not found: session.SessionService/open
    at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:233)
    at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:214)
    at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:139)
    at grakn.protocol.session.SessionServiceGrpc$SessionServiceBlockingStub.open(SessionServiceGrpc.java:273)
    at grakn.client.GraknClient$Session.<init>(GraknClient.java:165)
    at grakn.client.GraknClient$Session.<init>(GraknClient.java:136)
    at grakn.client.GraknClient.session(GraknClient.java:123)
    at grakn.core.console.ConsoleSession.<init>(ConsoleSession.java:90)
    at grakn.core.console.GraknConsole.run(GraknConsole.java:99)
    at grakn.core.console.GraknConsole.main(GraknConsole.java:140)
</code>```

Cannot understand what is the resolution for the same

答:
So Thanks to help by grakn team , I resolved the issue by doing the following steps:

replace graql with grakn (for versions 1.5 and above)

stop grakn server by ./grakn server stop

run jps on commandline to identify if there are any processes still running for the grakn server

use the process id from step 3 and kill those processes by kill -9

Now do grakn server start

now run your grakn console commands, they will work.

Title: Unable to use graql on commandline

Body:
So I am using grakn core 1.5.7 on Ubuntu 18.04.

I want to use graql command.With older versions of grakn it was quite good to have a graql executable available.Here is the command i am using from inside my grakn folder.

graql console --keyspace prec --file ./schema.gql

However in newer versions on and after 1.5.7,I cannot find the same.

I had a look on the bugs section of grakn and i found this to be close but not much related issue. Following which i tried replacing graql to grakn but now i am getting this error

io.grpc.StatusRuntimeException: UNIMPLEMENTED: Method not found: session.SessionService/open
    at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:233)
    at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:214)
    at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:139)
    at grakn.protocol.session.SessionServiceGrpc$SessionServiceBlockingStub.open(SessionServiceGrpc.java:273)
    at grakn.client.GraknClient$Session.<init>(GraknClient.java:165)
    at grakn.client.GraknClient$Session.<init>(GraknClient.java:136)
    at grakn.client.GraknClient.session(GraknClient.java:123)
    at grakn.core.console.ConsoleSession.<init>(ConsoleSession.java:90)
    at grakn.core.console.GraknConsole.run(GraknConsole.java:99)
    at grakn.core.console.GraknConsole.main(GraknConsole.java:140)

Cannot understand what is the resolution for the same


来源: stackexchange

问:
"RNCSafeAreaView" was not found in the UIManager
I try to open a bundle, but when the android is running it shows the next message

2020-01-05 23:15:45.366 26210-26210/com.note.principal
  W/.note.principa: Accessing hidden field
  Landroid/view/View;->mAccessibilityDelegate:Landroid/view/View$AccessibilityDelegate;
  (light greylist, reflection) 2020-01-05 23:15:45.470
  26210-26242/com.note.principal E/ReactNativeJS: Invariant Violation:
  requireNativeComponent: "RNCSafeAreaView" was not found in the
  UIManager.

```<code>This error is located at:
    in RNCSafeAreaView
    in Unknown
    in Unknown
    in n
    in Unknown
    in Unknown
    in C
    in P
    in u
    in RCTView
    in RCTView
    in h 2020-01-05 23:15:45.494 26210-26242/com.note.principal E/ReactNativeJS: Invariant Violation: requireNativeComponent:
</code>```

"RNCSafeAreaView" was not found in the UIManager.

```<code>This error is located at:
    in P
    in u
    in RCTView
    in RCTView
    in h 2020-01-05 23:15:45.502 26210-26242/com.note.principal E/ReactNativeJS: Invariant Violation: requireNativeComponent:
</code>```

"RNCSafeAreaView" was not found in the UIManager.

```<code>This error is located at:
    in P
    in u
    in RCTView
    in RCTView
    in h 2020-01-05 23:15:45.794 26210-26244/com.note.principal E/unknown:ReactNative: Invariant Violation: requireNativeComponent:
</code>```

"RNCSafeAreaView" was not found in the UIManager.

```<code>This error is located at:
    in RNCSafeAreaView
    in Unknown
    in Unknown
    in n
    in Unknown
    in Unknown
    in C
    in P
    in u
    in RCTView
    in RCTView
    in h, stack:
exports@175:1634
get@163:682
Al@89:70673
Ml@89:70108
Ul@89:67144
Ul@-1
Pl@89:65839
Pl@-1
<unknown>@89:25495
unstable_runWithPriority@168:3915
sn@89:25442
cn@89:25377
kl@89:64831
la@89:87813
render@89:90592
exports@342:541
run@334:1305
runApplication@334:2287
value@25:3685
<unknown>@25:841
value@25:2939
value@25:813
value@-1 2020-01-05 23:15:45.832 26210-26244/com.note.principal E/unknown:ReactNative: Invariant Violation: requireNativeComponent:
</code>```

"RNCSafeAreaView" was not found in the UIManager.

```<code>This error is located at:
    in P
    in u
    in RCTView
    in RCTView
    in h, stack:
exports@175:1634
get@163:682
Al@89:70673
Ml@89:70108
Ul@89:67144
Ul@-1
Pl@89:65839
Pl@-1
<unknown>@89:25495
unstable_runWithPriority@168:3915
sn@89:25442
cn@89:25377
kl@89:64831
la@89:87813
render@89:90592
exports@342:541
run@334:1305
runApplication@334:2287
value@25:3685
<unknown>@25:841
value@25:2939
value@25:813
value@-1 2020-01-05 23:15:45.856 26210-26244/com.note.principal E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
Process: com.note.principal, PID: 26210
com.facebook.react.common.JavascriptException: Invariant Violation: requireNativeComponent: "RNCSafeAreaView" was not found in
</code>```

the UIManager.

```<code>This error is located at:
    in P
    in u
    in RCTView
    in RCTView
    in h, stack:
exports@175:1634
get@163:682
Al@89:70673
Ml@89:70108
Ul@89:67144
Ul@-1
Pl@89:65839
Pl@-1
<unknown>@89:25495
unstable_runWithPriority@168:3915
sn@89:25442
cn@89:25377
kl@89:64831
la@89:87813
render@89:90592
exports@342:541
run@334:1305
runApplication@334:2287
value@25:3685
<unknown>@25:841
value@25:2939
value@25:813
value@-1

    at com.facebook.react.modules.core.ExceptionsManagerModule.reportException(ExceptionsManagerModule.java:71)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:371)
    at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:150)
    at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:26)
    at android.os.Looper.loop(Looper.java:193)
    at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:225)
    at java.lang.Thread.run(Thread.java:764) 2020-01-05 23:15:45.862 26210-26244/com.note.principal I/Process: Sending signal.
</code>```

PID: 26210 SIG: 9

The package of project is

```<code>{
  "name": "Notes",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "bundle_android": "react-native bundle --entry-file index.js --platform android --dev false --bundle-output ./bundles/android/index.android.bundle",
    "bundle_ios": "react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ./bundles/ios/main.jsbundle",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/masked-view": "^0.1.5",
    "prop-types": "^15.7.2",
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-gesture-handler": "^1.5.3",
    "react-native-linear-gradient": "^2.5.6",
    "react-native-safe-area-context": "^0.6.2",
    "react-navigation": "^4.0.10",
    "react-navigation-stack": "^2.0.8"
  },
  "devDependencies": {
    "@babel/core": "^7.7.7",
    "@babel/runtime": "^7.7.7",
    "@react-native-community/eslint-config": "^0.0.6",
    "babel-jest": "^24.9.0",
    "eslint": "^6.8.0",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.57.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

The project of gradle

```<code>include ':app'
rootProject.name='Notes'

include ':hermes-engine'
project(':hermes-engine').projectDir = new File(rootProject.projectDir, '../node_modules/hermes-engine/android/')

include ':react-native-gesture-handler'
project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-gesture-handler/android')

include ':react-native-linear-gradient'
project(':react-native-linear-gradient').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-linear-gradient/android')

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
        mavenLocal()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }
    }
}

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

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    buildToolsVersion "28.0.3"
    defaultConfig {
        applicationId ""
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

project.ext.react = [
        enableHermes: false,
]

def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false)

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation "com.facebook.react:react-native:+"
    implementation 'com.android.support:support-annotations:27.1.1'
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-linear-gradient')

    if (enableHermes) {
        implementation project(':hermes-engine')
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}
</code>```

This is the code of activity

```<code>package com.note

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.facebook.react.ReactInstanceManager
import com.facebook.react.ReactRootView
import com.facebook.react.common.LifecycleState
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler
import com.facebook.react.shell.MainReactPackage
import com.facebook.soloader.SoLoader
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage
import com.BV.LinearGradient.LinearGradientPackage

class ReactActivity : AppCompatActivity(), DefaultHardwareBackBtnHandler {

    private val OVERLAY_PERMISSION_REQ_CODE = 1

    private lateinit var mReactRootView: ReactRootView
    private lateinit var mReactInstanceManager: ReactInstanceManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SoLoader.init(this, false)
        mReactRootView = ReactRootView(this)
        mReactInstanceManager = ReactInstanceManager.builder()
            .setApplication(application)
            .setCurrentActivity(this)
            .setApplication(application)
            .setBundleAssetName("aaaaaa.android.bundle")
            .addPackage(MainReactPackage())
            .addPackage(RNGestureHandlerPackage())
            .addPackage(LinearGradientPackage())
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build()
        // The string here (e.g. "MyReactNativeApp") has to match
        // the string in AppRegistry.registerComponent() in index.js
        mReactRootView.startReactApplication(mReactInstanceManager, "Notes", null)

        setContentView(mReactRootView)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                val intent = Intent(
                        Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:$packageName")
                )
                startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE)
            }
        }
    }

    override fun invokeDefaultOnBackPressed() {
        super.onBackPressed()
    }

    override fun onBackPressed() {
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onBackPressed()
        } else {
            super.onBackPressed()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(this)) {
                    // SYSTEM_ALERT_WINDOW permission not granted
                }
            }
        }
        mReactInstanceManager?.onActivityResult(this,requestCode, resultCode, data)
    }
}
</code>```

someone knows what is the solution?

答:
I encountered the same error. In order to solve it make sure to install react-native-safe-area-context.

npm install react-native-safe-area-context

Then if you are using React Native 0.61.X make sure to do a pod install.
It will link everything together.

If you are using React Native < 0.6 then you need to do the linking manually with react-native link react-native-safe-area-context

ContentLicense: CC BY-SA 4.0

Body:
I try to open a bundle, but when the android is running it shows the next message

2020-01-05 23:15:45.366 26210-26210/com.note.principal
  W/.note.principa: Accessing hidden field
  Landroid/view/View;->mAccessibilityDelegate:Landroid/view/View$AccessibilityDelegate;
  (light greylist, reflection) 2020-01-05 23:15:45.470
  26210-26242/com.note.principal E/ReactNativeJS: Invariant Violation:
  requireNativeComponent: "RNCSafeAreaView" was not found in the
  UIManager.

This error is located at:
    in RNCSafeAreaView
    in Unknown
    in Unknown
    in n
    in Unknown
    in Unknown
    in C
    in P
    in u
    in RCTView
    in RCTView
    in h 2020-01-05 23:15:45.494 26210-26242/com.note.principal E/ReactNativeJS: Invariant Violation: requireNativeComponent:

"RNCSafeAreaView" was not found in the UIManager.

This error is located at:
    in P
    in u
    in RCTView
    in RCTView
    in h 2020-01-05 23:15:45.502 26210-26242/com.note.principal E/ReactNativeJS: Invariant Violation: requireNativeComponent:

"RNCSafeAreaView" was not found in the UIManager.

This error is located at:
    in P
    in u
    in RCTView
    in RCTView
    in h 2020-01-05 23:15:45.794 26210-26244/com.note.principal E/unknown:ReactNative: Invariant Violation: requireNativeComponent:

"RNCSafeAreaView" was not found in the UIManager.

This error is located at:
    in RNCSafeAreaView
    in Unknown
    in Unknown
    in n
    in Unknown
    in Unknown
    in C
    in P
    in u
    in RCTView
    in RCTView
    in h, stack:
exports@175:1634
get@163:682
Al@89:70673
Ml@89:70108
Ul@89:67144
Ul@-1
Pl@89:65839
Pl@-1
<unknown>@89:25495
unstable_runWithPriority@168:3915
sn@89:25442
cn@89:25377
kl@89:64831
la@89:87813
render@89:90592
exports@342:541
run@334:1305
runApplication@334:2287
value@25:3685
<unknown>@25:841
value@25:2939
value@25:813
value@-1 2020-01-05 23:15:45.832 26210-26244/com.note.principal E/unknown:ReactNative: Invariant Violation: requireNativeComponent:

"RNCSafeAreaView" was not found in the UIManager.

This error is located at:
    in P
    in u
    in RCTView
    in RCTView
    in h, stack:
exports@175:1634
get@163:682
Al@89:70673
Ml@89:70108
Ul@89:67144
Ul@-1
Pl@89:65839
Pl@-1
<unknown>@89:25495
unstable_runWithPriority@168:3915
sn@89:25442
cn@89:25377
kl@89:64831
la@89:87813
render@89:90592
exports@342:541
run@334:1305
runApplication@334:2287
value@25:3685
<unknown>@25:841
value@25:2939
value@25:813
value@-1 2020-01-05 23:15:45.856 26210-26244/com.note.principal E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
Process: com.note.principal, PID: 26210
com.facebook.react.common.JavascriptException: Invariant Violation: requireNativeComponent: "RNCSafeAreaView" was not found in

the UIManager.

This error is located at:
    in P
    in u
    in RCTView
    in RCTView
    in h, stack:
exports@175:1634
get@163:682
Al@89:70673
Ml@89:70108
Ul@89:67144
Ul@-1
Pl@89:65839
Pl@-1
<unknown>@89:25495
unstable_runWithPriority@168:3915
sn@89:25442
cn@89:25377
kl@89:64831
la@89:87813
render@89:90592
exports@342:541
run@334:1305
runApplication@334:2287
value@25:3685
<unknown>@25:841
value@25:2939
value@25:813
value@-1

    at com.facebook.react.modules.core.ExceptionsManagerModule.reportException(ExceptionsManagerModule.java:71)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:371)
    at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:150)
    at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:26)
    at android.os.Looper.loop(Looper.java:193)
    at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:225)
    at java.lang.Thread.run(Thread.java:764) 2020-01-05 23:15:45.862 26210-26244/com.note.principal I/Process: Sending signal.

PID: 26210 SIG: 9

The package of project is

{
  "name": "Notes",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "bundle_android": "react-native bundle --entry-file index.js --platform android --dev false --bundle-output ./bundles/android/index.android.bundle",
    "bundle_ios": "react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ./bundles/ios/main.jsbundle",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/masked-view": "^0.1.5",
    "prop-types": "^15.7.2",
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-gesture-handler": "^1.5.3",
    "react-native-linear-gradient": "^2.5.6",
    "react-native-safe-area-context": "^0.6.2",
    "react-navigation": "^4.0.10",
    "react-navigation-stack": "^2.0.8"
  },
  "devDependencies": {
    "@babel/core": "^7.7.7",
    "@babel/runtime": "^7.7.7",
    "@react-native-community/eslint-config": "^0.0.6",
    "babel-jest": "^24.9.0",
    "eslint": "^6.8.0",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.57.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

The project of gradle

include ':app'
rootProject.name='Notes'

include ':hermes-engine'
project(':hermes-engine').projectDir = new File(rootProject.projectDir, '../node_modules/hermes-engine/android/')

include ':react-native-gesture-handler'
project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-gesture-handler/android')

include ':react-native-linear-gradient'
project(':react-native-linear-gradient').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-linear-gradient/android')

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
        mavenLocal()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }
    }
}

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

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    buildToolsVersion "28.0.3"
    defaultConfig {
        applicationId ""
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

project.ext.react = [
        enableHermes: false,
]

def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false)

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation "com.facebook.react:react-native:+"
    implementation 'com.android.support:support-annotations:27.1.1'
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-linear-gradient')

    if (enableHermes) {
        implementation project(':hermes-engine')
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

This is the code of activity

package com.note

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.facebook.react.ReactInstanceManager
import com.facebook.react.ReactRootView
import com.facebook.react.common.LifecycleState
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler
import com.facebook.react.shell.MainReactPackage
import com.facebook.soloader.SoLoader
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage
import com.BV.LinearGradient.LinearGradientPackage

class ReactActivity : AppCompatActivity(), DefaultHardwareBackBtnHandler {

    private val OVERLAY_PERMISSION_REQ_CODE = 1

    private lateinit var mReactRootView: ReactRootView
    private lateinit var mReactInstanceManager: ReactInstanceManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SoLoader.init(this, false)
        mReactRootView = ReactRootView(this)
        mReactInstanceManager = ReactInstanceManager.builder()
            .setApplication(application)
            .setCurrentActivity(this)
            .setApplication(application)
            .setBundleAssetName("aaaaaa.android.bundle")
            .addPackage(MainReactPackage())
            .addPackage(RNGestureHandlerPackage())
            .addPackage(LinearGradientPackage())
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build()
        // The string here (e.g. "MyReactNativeApp") has to match
        // the string in AppRegistry.registerComponent() in index.js
        mReactRootView.startReactApplication(mReactInstanceManager, "Notes", null)

        setContentView(mReactRootView)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                val intent = Intent(
                        Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:$packageName")
                )
                startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE)
            }
        }
    }

    override fun invokeDefaultOnBackPressed() {
        super.onBackPressed()
    }

    override fun onBackPressed() {
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onBackPressed()
        } else {
            super.onBackPressed()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(this)) {
                    // SYSTEM_ALERT_WINDOW permission not granted
                }
            }
        }
        mReactInstanceManager?.onActivityResult(this,requestCode, resultCode, data)
    }
}

someone knows what is the solution?


问:
All possible exact sums from multiple arrays
I've been given the following problem and my code has become a horrible mess and I'm quite stuck.

You are given an allowance to spend at some shops (something like $15, just some positive integer)
You may only spend this money under two conditions:

1) You buy exactly one item from each shop.

2) You spend all of your money (nothing left over, and no debt)

Find all possible ways you could have purchased items to satisfy the above.

In actuality, you're given a budget int and some array like

9 and [[1,2,3],[0,5],[2,3,8]]

where each inner array lists the prices of items in the a shop. There can be arbitrarily many shops with arbitrarily many items. Costs cannot be negative, but they can be free!

The expected solution here would be:

[[1,5,3],[2,5,2],[1,0,8]]

As each array contains one item from each shop, each totals 9, and all possibilities are present.
Just to make it more difficult, speed is paramount.

The following is my code that has descended into madness and a near complete lack of functionality:

def Stepper(bud,LOL):
    n=len(LOL)
    lasts=[]
    indices=[0 for j in range(n)]
    focus=0
    funds=[0 for j in range(n+1)]
    funds[0]=bud
    sols=[]
    moveable=[]
    for j in range(n):
        length=len(LOL[j])
        if(length==0):
            return []
        lasts.append(length-1)
        if(moveable==[]):
            if(length==1):
                funds[j+1]=funds[j]-LOL[j][0]
            else:
                moveable.append(j)
                focus=j
    while(moveable!=[]):
        while(LOL[focus][indices[focus]] > funds[focus]):
            indices[focus]+=1
        if(indices[focus]==lasts[focus]):
            if(moveable[-1]==focus):
                moveable.remove(focus)
            if(moveable==[]):
                if(focus<n-1):
                    moveable.append(focus+1)
        funds[focus+1]=funds[focus]-LOL[focus][indices[focus]]
        #print(n,lasts,indices,focus,moveable,funds,sols)
        if((funds[focus+1]!=0) and (focus<n-1)):
                focus+=1
                indices[focus]=0
        else:
            if(funds[focus+1]==0):
                for j in range(focus+1,n):
                    indices[j]=lasts[j]
                sols.append(list(indices))
            if(moveable[-1]==n-1):
                moveable.remove(n-1)
            if(moveable!=[]):
                focus=moveable[-1]
                indices[focus]+=1
                if(indices[focus]==lasts[focus]):
                    if(moveable[-1]==focus):
                        moveable.remove(focus)
                    if(moveable==[]):
                        if(focus<n-1):
                            moveable.append(focus+1)
                funds[focus+1]=funds[focus]-LOL[focus][indices[focus]]
                focus+=1
                indices[focus]=0
    return(sols)
```

where bud is the budget and LOL is the list of lists (the shops and prices)

答:
This is a combinatorics problem. Which item from shop 1 combines with which item from shop 2 and which single items from shops 3...n to add up to some number?

Python's standard library has a function which can generate all these combinations for you, saving you the nested for loops. It's the handy itertools.product:

>>> import itertools
>>> budget = 9
>>> shops = [[1, 2, 3], [0, 5], [2, 3, 8]]
>>> list(itertools.product(*shops))
[(1, 0, 2),
 (1, 0, 3),
 (1, 0, 8),
 (1, 5, 2),
 (1, 5, 3),
 (1, 5, 8),
 (2, 0, 2),
 (2, 0, 3),
 (2, 0, 8),
 (2, 5, 2),
 (2, 5, 3),
 (2, 5, 8),
 (3, 0, 2),
 (3, 0, 3),
 (3, 0, 8),
 (3, 5, 2),
 (3, 5, 3),
 (3, 5, 8)]
```

<p>Next we want to get rid of all the combinations which do not satisfy our condition (that the prices exactly add up to the total budget). Let's use the built-in <code>filter</code> function to get our solution:</p>

```>>> list(filter(lambda prices: sum(prices) == budget, itertools.product(*shops))
[(1, 0, 8), (1, 5, 3), (2, 5, 2)]
```

Body:
I've been given the following problem and my code has become a horrible mess and I'm quite stuck.

You are given an allowance to spend at some shops (something like $15, just some positive integer)
You may only spend this money under two conditions:

1) You buy exactly one item from each shop.

2) You spend all of your money (nothing left over, and no debt)

Find all possible ways you could have purchased items to satisfy the above.

In actuality, you're given a budget int and some array like

9 and [[1,2,3],[0,5],[2,3,8]]

where each inner array lists the prices of items in the a shop. There can be arbitrarily many shops with arbitrarily many items. Costs cannot be negative, but they can be free!

The expected solution here would be:

[[1,5,3],[2,5,2],[1,0,8]]

As each array contains one item from each shop, each totals 9, and all possibilities are present.
Just to make it more difficult, speed is paramount.

The following is my code that has descended into madness and a near complete lack of functionality:

def Stepper(bud,LOL):
    n=len(LOL)
    lasts=[]
    indices=[0 for j in range(n)]
    focus=0
    funds=[0 for j in range(n+1)]
    funds[0]=bud
    sols=[]
    moveable=[]
    for j in range(n):
        length=len(LOL[j])
        if(length==0):
            return []
        lasts.append(length-1)
        if(moveable==[]):
            if(length==1):
                funds[j+1]=funds[j]-LOL[j][0]
            else:
                moveable.append(j)
                focus=j
    while(moveable!=[]):
        while(LOL[focus][indices[focus]] > funds[focus]):
            indices[focus]+=1
        if(indices[focus]==lasts[focus]):
            if(moveable[-1]==focus):
                moveable.remove(focus)
            if(moveable==[]):
                if(focus<n-1):
                    moveable.append(focus+1)
        funds[focus+1]=funds[focus]-LOL[focus][indices[focus]]
        #print(n,lasts,indices,focus,moveable,funds,sols)
        if((funds[focus+1]!=0) and (focus<n-1)):
                focus+=1
                indices[focus]=0
        else:
            if(funds[focus+1]==0):
                for j in range(focus+1,n):
                    indices[j]=lasts[j]
                sols.append(list(indices))
            if(moveable[-1]==n-1):
                moveable.remove(n-1)
            if(moveable!=[]):
                focus=moveable[-1]
                indices[focus]+=1
                if(indices[focus]==lasts[focus]):
                    if(moveable[-1]==focus):
                        moveable.remove(focus)
                    if(moveable==[]):
                        if(focus<n-1):
                            moveable.append(focus+1)
                funds[focus+1]=funds[focus]-LOL[focus][indices[focus]]
                focus+=1
                indices[focus]=0
    return(sols)

where bud is the budget and LOL is the list of lists (the shops and prices)

Body:
This is a combinatorics problem. Which item from shop 1 combines with which item from shop 2 and which single items from shops 3...n to add up to some number?

Python's standard library has a function which can generate all these combinations for you, saving you the nested for loops. It's the handy itertools.product:

>>> import itertools
>>> budget = 9
>>> shops = [[1, 2, 3], [0, 5], [2, 3, 8]]
>>> list(itertools.product(*shops))
[(1, 0, 2),
 (1, 0, 3),
 (1, 0, 8),
 (1, 5, 2),
 (1, 5, 3),
 (1, 5, 8),
 (2, 0, 2),
 (2, 0, 3),
 (2, 0, 8),
 (2, 5, 2),
 (2, 5, 3),
 (2, 5, 8),
 (3, 0, 2),
 (3, 0, 3),
 (3, 0, 8),
 (3, 5, 2),
 (3, 5, 3),
 (3, 5, 8)]

Next we want to get rid of all the combinations which do not satisfy our condition (that the prices exactly add up to the total budget). Let's use the built-in filter function to get our solution:

>>> list(filter(lambda prices: sum(prices) == budget, itertools.product(*shops))
[(1, 0, 8), (1, 5, 3), (2, 5, 2)]


问:
Saving an image
I'm making a drawing program in C# for Windows Phone.

This is for Windows Phone, so a bunch of stuff doesn't work that would work in C#.

At the start of opening a .XAML page, I have a blank Canvas. The user draws on the Canvas, then clicks Save. When he/she clicks Save, I want the program to be able to save the image on the Canvas.

I have the following code so far:

```<code>        IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
        StreamReader sr = null;

        sr = new StreamReader(new IsolatedStorageFileStream("Data\\imagenum.txt", FileMode.Open, isf));
        test = sr.ReadLine();
        sr.Close();

        int.TryParse(test, out test2);

        test2 = test2 + 1;

        IsolatedStorageFile isf2 = IsolatedStorageFile.GetUserStoreForApplication();
        isf2.CreateDirectory("Data");
        StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream("Data\\imagenum.txt", FileMode.Create, isf2));
        sw.WriteLine(test2);
        //This writes the content of textBox1 to the StreamWriter. The StreamWriter writes the text to the file.
        sw.Close();
</code>```

This code finds what an appropriate name for the image would be.

I've also found various other code snippets on the web:

```<code>            // Construct a bitmap from the button image resource.
        test = "Images/" + test + ".jpg";
        using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
        {
            WriteableBitmap bmImage = new WriteableBitmap(image);
            if (!store.DirectoryExists("Images"))
            {
                store.CreateDirectory("Images");
            }
            using (IsolatedStorageFileStream isoStream =
            store.OpenFile(@"Images\" + test + ".jpg", FileMode.OpenOrCreate))
            {
                Extensions.SaveJpeg(
                bmImage,
                isoStream,
                bmImage.PixelWidth,
                bmImage.PixelHeight,
                0,
                100);
            }
        }
</code>```

The above is an ugly mess of code from tutorials on MSDN and my own badly scraped together code.

(It doesn't work, for semi-obvious reasons)

How would I save the canvas to IsolatedStorage, as an image?

答:
Your first section where you appear to be writing the last used number to a text file in IsolatedStorage seems like a lot of work to do something relatively simple.  You can replace that whole section with this:

```<code>IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
int imageNumber = 0;
settings.TryGetValue<int>("PreviousImageNumber", out imageNumber);
imageNumber++;
</code>```

You can save the image to IsolatedStorage like this:

```<code>using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
    if (!isf.DirectoryExists("Images"))
    {
        isf.CreateDirectory("Images");
    }
    IsolatedStorageFileStream fstream = isf.CreateFile(string.Format("Images\\{0}.jpg",imageNumber));

    WriteableBitmap wbmp = new WriteableBitmap(image);
    Extensions.SaveJpeg(wbmp, fstream, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
    fstream.Close();
}
</code>```

But it would probably make more sense to save the image to their MediaLibrary like this:

```<code>MediaLibrary library = new MediaLibrary();
WriteableBitmap wbmp = new WriteableBitmap(image);

MemoryStream ms = new MemoryStream();
Extensions.SaveJpeg(wbmp, ms, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
library.SavePicture(string.Format("Images\\{0}.jpg",imageNumber), ms);
</code>```

Either way, you can then save the imageNumber back to the IsolatedStorageSettings like this:

```<code>settings["PreviousImageNumber"] = imageNumber;
settings.Save();
</code>```

I had assumed the image used above was set somewhere else in your code.  I haven't saved a Canvas to an image before, but some quick searching turned up this blog where an example is given using the WriteableBitmap which indicates you can just replace the image variable with your canvas element:

```<code>WriteableBitmap wbmp = new WriteableBitmap(yourCanvas, null);
</code>```

The article also indicates that the Canvas' background will be ignored and replaced with a black image but that you can overcome this by first adding a rectangle to the Canvas with whatever background you want.  Again, I haven't tried this.  If this doesn't work you should consider posting another question specifically related to transforming a Canvas to an Image since this is really a separate issue from your original question about saving images.

ContentLicense: CC BY-SA 3.0

Title: Saving an image

Body:
I'm making a drawing program in C# for Windows Phone.

This is for Windows Phone, so a bunch of stuff doesn't work that would work in C#.

At the start of opening a .XAML page, I have a blank Canvas. The user draws on the Canvas, then clicks Save. When he/she clicks Save, I want the program to be able to save the image on the Canvas.

I have the following code so far:

        IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
        StreamReader sr = null;

        sr = new StreamReader(new IsolatedStorageFileStream("Data\\imagenum.txt", FileMode.Open, isf));
        test = sr.ReadLine();
        sr.Close();

        int.TryParse(test, out test2);

        test2 = test2 + 1;

        IsolatedStorageFile isf2 = IsolatedStorageFile.GetUserStoreForApplication();
        isf2.CreateDirectory("Data");
        StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream("Data\\imagenum.txt", FileMode.Create, isf2));
        sw.WriteLine(test2);
        //This writes the content of textBox1 to the StreamWriter. The StreamWriter writes the text to the file.
        sw.Close();

This code finds what an appropriate name for the image would be.

I've also found various other code snippets on the web:

            // Construct a bitmap from the button image resource.
        test = "Images/" + test + ".jpg";
        using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
        {
            WriteableBitmap bmImage = new WriteableBitmap(image);
            if (!store.DirectoryExists("Images"))
            {
                store.CreateDirectory("Images");
            }
            using (IsolatedStorageFileStream isoStream =
            store.OpenFile(@"Images\" + test + ".jpg", FileMode.OpenOrCreate))
            {
                Extensions.SaveJpeg(
                bmImage,
                isoStream,
                bmImage.PixelWidth,
                bmImage.PixelHeight,
                0,
                100);
            }
        }

The above is an ugly mess of code from tutorials on MSDN and my own badly scraped together code.

(It doesn't work, for semi-obvious reasons)

How would I save the canvas to IsolatedStorage, as an image?

Body:
Your first section where you appear to be writing the last used number to a text file in IsolatedStorage seems like a lot of work to do something relatively simple.  You can replace that whole section with this:

IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
int imageNumber = 0;
settings.TryGetValue<int>("PreviousImageNumber", out imageNumber);
imageNumber++;

You can save the image to IsolatedStorage like this:

using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
    if (!isf.DirectoryExists("Images"))
    {
        isf.CreateDirectory("Images");
    }
    IsolatedStorageFileStream fstream = isf.CreateFile(string.Format("Images\\{0}.jpg",imageNumber));

    WriteableBitmap wbmp = new WriteableBitmap(image);
    Extensions.SaveJpeg(wbmp, fstream, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
    fstream.Close();
}

But it would probably make more sense to save the image to their MediaLibrary like this:

MediaLibrary library = new MediaLibrary();
WriteableBitmap wbmp = new WriteableBitmap(image);

MemoryStream ms = new MemoryStream();
Extensions.SaveJpeg(wbmp, ms, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
library.SavePicture(string.Format("Images\\{0}.jpg",imageNumber), ms);

Either way, you can then save the imageNumber back to the IsolatedStorageSettings like this:

settings["PreviousImageNumber"] = imageNumber;
settings.Save();

I had assumed the image used above was set somewhere else in your code.  I haven't saved a Canvas to an image before, but some quick searching turned up this blog where an example is given using the WriteableBitmap which indicates you can just replace the image variable with your canvas element:

WriteableBitmap wbmp = new WriteableBitmap(yourCanvas, null);

The article also indicates that the Canvas' background will be ignored and replaced with a black image but that you can overcome this by first adding a rectangle to the Canvas with whatever background you want.  Again, I haven't tried this.  If this doesn't work you should consider posting another question specifically related to transforming a Canvas to an Image since this is really a separate issue from your original question about saving images.


问:
sentiments dataset in R throwing error with AFINN lexicon
Trying to access the sentiments data set for the "AFINN" lexicon using the function get_sentiments("afinn")

R code :

```<code>library(textdata)
get_sentiments("afinn")
</code>```

Throwing below error message

```<code>Do you want to download:
Name: AFINN-111 Error in menu(choices = c("Yes", "No"),title = title):
menu() cannot be used non-interactively
</code>```

答:
I have the similar issue when i run it on Jupyter but Colab is working fine. You may run it on RGui where interactive() should return TRUE which enable you to type "Yes" into the "Selection" so that the download can be completed.

Is R running interactively

Body:
Trying to access the sentiments data set for the "AFINN" lexicon using the function get_sentiments("afinn")

R code :

library(textdata)
get_sentiments("afinn")

Throwing below error message

Do you want to download:
Name: AFINN-111 Error in menu(choices = c("Yes", "No"),title = title):
menu() cannot be used non-interactively


问:
.Net Core: encrypting to a-z characters only
I am using following encryption class

```<code>public static class Extensions
{
    static string key = "jdsg432387#";
    static byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 };
    public static string Encrypt(this string plainText)
    {
        byte[] EncryptKey = { };
        EncryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByte = Encoding.UTF8.GetBytes(plainText);
        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(EncryptKey, IV), CryptoStreamMode.Write);
        cStream.Write(inputByte, 0, inputByte.Length);
        cStream.FlushFinalBlock();
        return Convert.ToBase64String(mStream.ToArray());
    }

    public static string Decrypt(this string encryptedText)
    {
        byte[] DecryptKey = { };
        byte[] inputByte = new byte[encryptedText.Length];

        DecryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        inputByte = Convert.FromBase64String(encryptedText);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(DecryptKey, IV), CryptoStreamMode.Write);
        cs.Write(inputByte, 0, inputByte.Length);
        cs.FlushFinalBlock();
        System.Text.Encoding encoding = System.Text.Encoding.UTF8;
        return encoding.GetString(ms.ToArray());
    }
}
</code>```

however it generates special characters(e.g. +, =) in encrypted result string

how do I limit the encrypted result string in a-z characters only?

答:
you can convert string to hex

```<code>public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
{
     Byte[] stringBytes = encoding.GetBytes(input);
    StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
    foreach (byte b in stringBytes)
     {
         sbBytes.AppendFormat("{0:X2}", b);
    }
    return sbBytes.ToString();
}
</code>```

and to decrypt  hex to string

```<code>public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
{
     int numberChars = hexInput.Length;
    byte[] bytes = new byte[numberChars / 2];
     for (int i = 0; i < numberChars; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
     }
     return encoding.GetString(bytes);
}
</code>```

Body:
I am using following encryption class

public static class Extensions
{
    static string key = "jdsg432387#";
    static byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 };
    public static string Encrypt(this string plainText)
    {
        byte[] EncryptKey = { };
        EncryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByte = Encoding.UTF8.GetBytes(plainText);
        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(EncryptKey, IV), CryptoStreamMode.Write);
        cStream.Write(inputByte, 0, inputByte.Length);
        cStream.FlushFinalBlock();
        return Convert.ToBase64String(mStream.ToArray());
    }

    public static string Decrypt(this string encryptedText)
    {
        byte[] DecryptKey = { };
        byte[] inputByte = new byte[encryptedText.Length];

        DecryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        inputByte = Convert.FromBase64String(encryptedText);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(DecryptKey, IV), CryptoStreamMode.Write);
        cs.Write(inputByte, 0, inputByte.Length);
        cs.FlushFinalBlock();
        System.Text.Encoding encoding = System.Text.Encoding.UTF8;
        return encoding.GetString(ms.ToArray());
    }
}

however it generates special characters(e.g. +, =) in encrypted result string

how do I limit the encrypted result string in a-z characters only?

Body:
you can convert string to hex

public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
{
     Byte[] stringBytes = encoding.GetBytes(input);
    StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
    foreach (byte b in stringBytes)
     {
         sbBytes.AppendFormat("{0:X2}", b);
    }
    return sbBytes.ToString();
}

and to decrypt  hex to string

public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
{
     int numberChars = hexInput.Length;
    byte[] bytes = new byte[numberChars / 2];
     for (int i = 0; i < numberChars; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
     }
     return encoding.GetString(bytes);
}


问:
How to create HTML element for JavaScript and not for HTML
I have this simplified code:

const chancesData = ["facebook","twitter","google"];
        let inputsArr = [];
        const inputsArrFill = chancesData.map((cur, index) => {
          const input = (document.createElement("input").value =
            chancesData[index]);
          inputsArr.push(input); //I want the pushed value to be something like this "<input value"facebook">"
          return inputsArr;
          //so the returned array (should) be something like this:
          //["<input value"facebook">","<input value"twitter">","<input value"google">"]
        });
        console.dir(inputsArrFill);
  ```
</div>
</div>
</p>

<p>as you can see if you opened this coed in your console, the returned array looks like this:</p>

```['facebook', 'twiiter', 'google']
```

<p>I want it to look like this:</p>

```['<input value="facebook">','<input value="twitter">','<input value="google">']
```

答:
You can use setAttribute to put the value into the HTML markup, then retrieve it with outerHTML:

const chancesData = ["facebook", "twitter", "google"];
const inputsArrFill = chancesData.map(str => {
  const input = document.createElement("input");
  input.setAttribute('value', str);
  return input.outerHTML;
});
console.dir(inputsArrFill);```
</div>
</div>
</p>

<p>But it'd be easier to use ordinary string concatenation:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const chancesData = ["facebook", "twitter", "google"];
const inputsArrFill = chancesData.map(str => `<input value="${str}">`);
console.dir(inputsArrFill);</code>```

Body:
I have this simplified code:

const chancesData = ["facebook","twitter","google"];
        let inputsArr = [];
        const inputsArrFill = chancesData.map((cur, index) => {
          const input = (document.createElement("input").value =
            chancesData[index]);
          inputsArr.push(input); //I want the pushed value to be something like this "<input value"facebook">"
          return inputsArr;
          //so the returned array (should) be something like this:
          //["<input value"facebook">","<input value"twitter">","<input value"google">"]
        });
        console.dir(inputsArrFill);

as you can see if you opened this coed in your console, the returned array looks like this:

['facebook', 'twiiter', 'google']

I want it to look like this:

['<input value="facebook">','<input value="twitter">','<input value="google">']

Body:
You can use setAttribute to put the value into the HTML markup, then retrieve it with outerHTML:

const chancesData = ["facebook", "twitter", "google"];
const inputsArrFill = chancesData.map(str => {
  const input = document.createElement("input");
  input.setAttribute('value', str);
  return input.outerHTML;
});
console.dir(inputsArrFill);

But it'd be easier to use ordinary string concatenation:

const chancesData = ["facebook", "twitter", "google"];
const inputsArrFill = chancesData.map(str => `<input value="${str}">`);
console.dir(inputsArrFill);


问:
How to initialize a const std vector in old c++?
My C++ compiler identification is GNU 4.4.1

I think since c++ 11 you can initialize a vector this way:

```<code>const std::vector<int> myVector = {1, 2, 3};
const std::vector<int> myVector2{1, 2, 3};
</code>```

Unfortunately, I am not using c++ 11 so myVector can just be initilized by constructor.
I need to create a vector that will never be modified. It has to be shared by differents functions within a class so it may be static as well, or even a class member.
Is there a way to make my vector be initiliazed when it gets defined in c++98, as the examples from above, or something equivalent?

答:
@vll's answer is probably better, but you can also do:

```<code>int temp[] = {1, 2, 3};
const std::vector<int> myVector(temp, temp + sizeof(temp)/sizeof(temp[0]));
</code>```

It does however create two copies instead of one, and it pollutes the namespace with the name of the array.

Body:
My C++ compiler identification is GNU 4.4.1

I think since c++ 11 you can initialize a vector this way:

const std::vector<int> myVector = {1, 2, 3};
const std::vector<int> myVector2{1, 2, 3};

Unfortunately, I am not using c++ 11 so myVector can just be initilized by constructor.
I need to create a vector that will never be modified. It has to be shared by differents functions within a class so it may be static as well, or even a class member.
Is there a way to make my vector be initiliazed when it gets defined in c++98, as the examples from above, or something equivalent?

Body:
@vll's answer is probably better, but you can also do:

int temp[] = {1, 2, 3};
const std::vector<int> myVector(temp, temp + sizeof(temp)/sizeof(temp[0]));

It does however create two copies instead of one, and it pollutes the namespace with the name of the array.


问:
Difference between print(<variable_name>) and <variable_name> in python shell?
When i was going through the codes i found an interesting thing, if we initialize a variable in python shell, and we print that variable we get the value, if we use type the variable and press enter we get the same value. I could't figure out the reason behind it?? Can anyone help....</p>

```<code>>a = 5
>print(a)
>5
>a
5
</code>```

答: print will work in the shell AND in a script while giving the variable name is just a syntactic sugar for the shell.

Body:
When i was going through the codes i found an interesting thing, if we initialize a variable in python shell, and we print that variable we get the value, if we use type the variable and press enter we get the same value. I could't figure out the reason behind it?? Can anyone help....

>a = 5
>print(a)
>5
>a
5


问:
C# how to check exact time difference in if condition
I have this if condition where I need to do some stuff if the difference is 15 min or so

```<code>if (DateTime.UtcNow - x.Timestamp == TimeSpan.FromMinutes(15))
{
    //Do something
}
</code>```

The above condition never satisfies when I check with == but when I do >= it gets into the condition but that's not what I need, I want 15 min or so difference.

Can someone explain this behavior?

Sample Data:

x = 2/17/2020 8:45:17 PM

答:
Option 1:

If x.Timestamp is something you can reset (not a server-/client-side readonly value), then use >= (or > as = is less likely to ever happen) and reset x.Timestamp to the current time. Also, check this answer for determining relative time.

Option 2:

If you just want to raise a function in every 15 minutes, you have the answer here.

Note that 3 different timers exist, if you will need one that operate within seconds or milliseconds, you may want to avoid overlapping: which is (only?) possible with System.Timers.Timer via its Enabled property.

Option 3:

If you want to raise a function inside a while loop in every 15 minutes, I propose to use a StopWatch.

```<code>var watch = new StopWatch();
watch.Start();
while(...)
{
    if (watch.Elapsed > TimeSpan.FromMinutes(15))
    {
        // do your stuff
        watch.Restart();
    }
}
</code>```

Body:
I have this if condition where I need to do some stuff if the difference is 15 min or so

if (DateTime.UtcNow - x.Timestamp == TimeSpan.FromMinutes(15))
{
    //Do something
}

The above condition never satisfies when I check with == but when I do >= it gets into the condition but that's not what I need, I want 15 min or so difference.

Can someone explain this behavior?

Sample Data:

x = 2/17/2020 8:45:17 PM

Body:
Option 1:

If x.Timestamp is something you can reset (not a server-/client-side readonly value), then use >= (or > as = is less likely to ever happen) and reset x.Timestamp to the current time. Also, check this answer for determining relative time.

Option 2:

If you just want to raise a function in every 15 minutes, you have the answer here.

Note that 3 different timers exist, if you will need one that operate within seconds or milliseconds, you may want to avoid overlapping: which is (only?) possible with System.Timers.Timer via its Enabled property.

Option 3:

If you want to raise a function inside a while loop in every 15 minutes, I propose to use a StopWatch.

var watch = new StopWatch();
watch.Start();
while(...)
{
    if (watch.Elapsed > TimeSpan.FromMinutes(15))
    {
        // do your stuff
        watch.Restart();
    }
}


问:
How to implement Update subquery in sql server 2017 I want to update one column using multiple select but its showing subquery error
```<code>UPDATE temp_hourly_stats SET peak_location_percentage =(
(SELECT TOP(1) peak_location_count as peak_location_count FROM temp_hourly_stats where time_range = (select concat( DATEPART(hh, DATEADD(hh,-1,CURRENT_TIMESTAMP)) ,'-', DATEPART(hh, CURRENT_TIMESTAMP))as time_range) order by id desc)UNION
(SELECT TOP(1) total_count as total_count FROM temp_hourly_stats where time_range = (select concat( DATEPART(hh, DATEADD(hh,-1,CURRENT_TIMESTAMP)) ,'-', DATEPART(hh, CURRENT_TIMESTAMP))as time_range) order by id desc)Union
(select (peak_location_count*100)/total_count as peak_loc_percentage))
</code>```

The error I am getting is this:-
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

答:
Can you please use IN operator instead of "=" operator in update query.

Like this

UPDATE temp_hourly_stats SET peak_location_percentage IN(
(SELECT TOP(1) peak_location_count as peak_location_count FROM temp_hourly_stats where time_range = (select concat( DATEPART(hh, DATEADD(hh,-1,CURRENT_TIMESTAMP)) ,'-', DATEPART(hh, CURRENT_TIMESTAMP))as time_range) order by id desc)UNION
(SELECT TOP(1) total_count as total_count FROM temp_hourly_stats where time_range = (select concat( DATEPART(hh, DATEADD(hh,-1,CURRENT_TIMESTAMP)) ,'-', DATEPART(hh, CURRENT_TIMESTAMP))as time_range) order by id desc)Union
(select (peak_location_count*100)/total_count as peak_loc_percentage))

Body:
UPDATE temp_hourly_stats SET peak_location_percentage =(
(SELECT TOP(1) peak_location_count as peak_location_count FROM temp_hourly_stats where time_range = (select concat( DATEPART(hh, DATEADD(hh,-1,CURRENT_TIMESTAMP)) ,'-', DATEPART(hh, CURRENT_TIMESTAMP))as time_range) order by id desc)UNION
(SELECT TOP(1) total_count as total_count FROM temp_hourly_stats where time_range = (select concat( DATEPART(hh, DATEADD(hh,-1,CURRENT_TIMESTAMP)) ,'-', DATEPART(hh, CURRENT_TIMESTAMP))as time_range) order by id desc)Union
(select (peak_location_count*100)/total_count as peak_loc_percentage))

The error I am getting is this:-
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.


问:
list the file and its base directory
I have some files in my folder /home/sample/* * /*.pdf and *.doc and * .xls etc ('**' means some sub-sub directory.

I need the shell script or linux command to list the files in following manner.

```<code>pdf_docs/xx.pdf
documents/xx.doc
excel/xx.xls
</code>```

pdf_docs, documents and excel are directories, which is located in various depth in /home/sample. like

```<code>/home/sample/12091/pdf_docs/xx.pdf
/home/sample/documents/xx.doc
/home/excel/V2hm/1001/excel/xx.xls
</code>```

答:
You don't need to call out to an external program to chop the pathname like you're looking for:

```<code>$ filename=/home/sample/12091/pdf_docs/xx.pdf
$ echo ${filename%/*/*}
/home/sample/12091
$ echo ${filename#${filename%/*/*}?}
pdf_docs/xx.pdf
</code>```

So,

```<code>find /home/sample -name \*.doc -o -name \*.pdf -o -name \*.xls -print0 |
while read -r -d '' pathname; do
  echo "${pathname#${pathname%/*/*}?}"
done
</code>```

Title: list the file and its base directory

Body:
I have some files in my folder /home/sample/* * /*.pdf and *.doc and * .xls etc ('**' means some sub-sub directory.

I need the shell script or linux command to list the files in following manner.

pdf_docs/xx.pdf
documents/xx.doc
excel/xx.xls

pdf_docs, documents and excel are directories, which is located in various depth in /home/sample. like

/home/sample/12091/pdf_docs/xx.pdf
/home/sample/documents/xx.doc
/home/excel/V2hm/1001/excel/xx.xls

Body:
You don't need to call out to an external program to chop the pathname like you're looking for:

$ filename=/home/sample/12091/pdf_docs/xx.pdf
$ echo ${filename%/*/*}
/home/sample/12091
$ echo ${filename#${filename%/*/*}?}
pdf_docs/xx.pdf

So,

find /home/sample -name \*.doc -o -name \*.pdf -o -name \*.xls -print0 |
while read -r -d '' pathname; do
  echo "${pathname#${pathname%/*/*}?}"
done


问:
Django authenticate def not triggering logged_in_success and logged_in_fail signal
When i do authentication by  function

from django.contrib.auth import authenticate

Djnago is not triggering success/fail signal, if i use the function

from django.contrib.auth import login

it will trigger as expected . basically i want to trigger the signal from following function

```<code>user = authenticate(username=username, password=password)
</code>```

now i added extra line to my code

```<code>login(request, user)
</code>```

after adding this , i am getting signal here

```<code>from django.contrib.auth.signals import (
    user_logged_in,
    user_login_failed,
)
</code>```

How can i get signal just from authenticate def ? i am using this for API

答:
authenticate merely checks provided credentials and returns an User instance on success (docs). It does not perform the actual logging in. That's done by the login function (docs). They are supposed to be used as you have.

user_logged_in signal is sent by login on success and user_login_failed is sent by authenticate when authentication fails.

Body:
When i do authentication by  function

from django.contrib.auth import authenticate

Djnago is not triggering success/fail signal, if i use the function

from django.contrib.auth import login

it will trigger as expected . basically i want to trigger the signal from following function

user = authenticate(username=username, password=password)

now i added extra line to my code

login(request, user)

after adding this , i am getting signal here

from django.contrib.auth.signals import (
    user_logged_in,
    user_login_failed,
)

How can i get signal just from authenticate def ? i am using this for API


问:
Simple working Example of json.net in VB.net
I have the following simplified JSON string from a provider,  its been a long time since I used Visual Studio and vb.Net,  so I'm very rusty!

```<code>{
"Venue": {
    "ID": 3145,
    "Name": "Big Venue, Clapton",
    "NameWithTown": "Big Venue, Clapton, London",
    "NameWithDestination": "Big Venue, Clapton, London",
    "ListingType": "A",
    "Address": {
        "Address1": "Clapton Raod",
        "Address2": "",
        "Town": "Clapton",
        "County": "Greater London",
        "Postcode": "PO1 1ST",
        "Country": "United Kingdom",
        "Region": "Europe"
    },
    "ResponseStatus": {
        "ErrorCode": "200",
        "Message": "OK"
    }
}
}
</code>```

I want to use JSON.Net to turn this in to something I can work with,  I have read examples etc and JSON.net looks like the answer,  but I'm getting no where.

My .Net code (Me.TextBox1.Text contains the JSON shown above)

```<code>Imports Newtonsoft.Json

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim obj As JSON_result
    obj = JsonConvert.DeserializeObject(Of JSON_result)(Me.TextBox1.Text)

    MsgBox(obj.ID)
End Sub
End Class

Public Class JSON_result
    Public ID As Integer
    Public Name As String
    Public NameWithTown As String
    Public NameWithDestination As String
    Public ListingType As String
 End Class
</code>```

Can someone explain why obj.ID always ends up as 0 please,  and why none of the other properties of my class are populated and what I need to do to fix this, no errors are reported.

答:
In Place of using this

```<code>MsgBox(json.SelectToken("Venue").SelectToken("ID"))
</code>```

You can also use

```<code>MsgBox(json.SelectToken("Venue.ID"))
</code>```

Body:
I have the following simplified JSON string from a provider,  its been a long time since I used Visual Studio and vb.Net,  so I'm very rusty!

{
"Venue": {
    "ID": 3145,
    "Name": "Big Venue, Clapton",
    "NameWithTown": "Big Venue, Clapton, London",
    "NameWithDestination": "Big Venue, Clapton, London",
    "ListingType": "A",
    "Address": {
        "Address1": "Clapton Raod",
        "Address2": "",
        "Town": "Clapton",
        "County": "Greater London",
        "Postcode": "PO1 1ST",
        "Country": "United Kingdom",
        "Region": "Europe"
    },
    "ResponseStatus": {
        "ErrorCode": "200",
        "Message": "OK"
    }
}
}

I want to use JSON.Net to turn this in to something I can work with,  I have read examples etc and JSON.net looks like the answer,  but I'm getting no where.

My .Net code (Me.TextBox1.Text contains the JSON shown above)

Imports Newtonsoft.Json

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim obj As JSON_result
    obj = JsonConvert.DeserializeObject(Of JSON_result)(Me.TextBox1.Text)

    MsgBox(obj.ID)
End Sub
End Class

Public Class JSON_result
    Public ID As Integer
    Public Name As String
    Public NameWithTown As String
    Public NameWithDestination As String
    Public ListingType As String
 End Class

Can someone explain why obj.ID always ends up as 0 please,  and why none of the other properties of my class are populated and what I need to do to fix this, no errors are reported.

Body:
In Place of using this

MsgBox(json.SelectToken("Venue").SelectToken("ID"))

You can also use

MsgBox(json.SelectToken("Venue.ID"))


问:
Rename columns with pandas
I am attempting to change column names with the following code:

```<code>import pandas as pd

jeopardy = pd.read_csv('/Users/adamshaw/Desktop/Coding/jeopardy_starting/jeopardy.csv')

jeopardy = jeopardy.rename(columns={' Air Date': 'Air_Date',
                                    ' Round': 'Round'}, inplace=True)

print(jeopardy)
</code>```

I am getting the following output:

```<code>>>> None
</code>```

How do I properly rename the columns?

these are the columns

```<code>Show Number    int64
 Air Date      object
 Round         object
 Category      object
 Value         object
 Question      object
 Answer        object
</code>```

答:
You are using the inplace=True option when renaming your columns. This returns nothing (None type) which you are assigning to the jeopardy variable.

Try removing the inplace=True or don't reassign it to jeopardy. So either

```<code>jeopardy = jeopardy.rename(columns={' Air Date': 'Air_Date',
                                    ' Round': 'Round'})
</code>```

or

```<code>jeopardy.rename(columns={' Air Date': 'Air_Date',
                         ' Round': 'Round'}, inplace=True)
</code>```

Title: Rename columns with pandas

Body:
I am attempting to change column names with the following code:

import pandas as pd

jeopardy = pd.read_csv('/Users/adamshaw/Desktop/Coding/jeopardy_starting/jeopardy.csv')

jeopardy = jeopardy.rename(columns={' Air Date': 'Air_Date',
                                    ' Round': 'Round'}, inplace=True)

print(jeopardy)

I am getting the following output:

>>> None

How do I properly rename the columns?

these are the columns

Show Number    int64
 Air Date      object
 Round         object
 Category      object
 Value         object
 Question      object
 Answer        object

Body:
You are using the inplace=True option when renaming your columns. This returns nothing (None type) which you are assigning to the jeopardy variable.

Try removing the inplace=True or don't reassign it to jeopardy. So either

jeopardy = jeopardy.rename(columns={' Air Date': 'Air_Date',
                                    ' Round': 'Round'})

or

jeopardy.rename(columns={' Air Date': 'Air_Date',
                         ' Round': 'Round'}, inplace=True)


问:
Find string in string
I trying to write function that searching string in some string.
exmaple:
"qwerty" => key to search
"qasazqertyqwerty"
the program return 1 because qwerty found in the string.

my code function is:

```<code>int normal(char *str, char *str2)
{
    int temp=0;
    while(*str)
    {
        while(*str2)
        {
            if(*str == *str2)
            {
                temp+=1;
            }
            else if(temp == strlen(str2))
            {
                printf("%d", temp/strlen(str2));
            }
            str2++;
            str++;
        }
    }
return 0;
}
</code>```

What the hell the problem in the program(logically)?

答: The correct answer is obviously to use strtstr. But if you're still wondering why your code doesn't work, it is because your calling strlen on str2 which you are incrementing. You should compute it first at the beginning of the function and then compare temp with it when you're done comparing chararcters.

Title: Find string in string

Body:
I trying to write function that searching string in some string.
exmaple:
"qwerty" => key to search
"qasazqertyqwerty"
the program return 1 because qwerty found in the string.

my code function is:

int normal(char *str, char *str2)
{
    int temp=0;
    while(*str)
    {
        while(*str2)
        {
            if(*str == *str2)
            {
                temp+=1;
            }
            else if(temp == strlen(str2))
            {
                printf("%d", temp/strlen(str2));
            }
            str2++;
            str++;
        }
    }
return 0;
}

What the hell the problem in the program(logically)?


问:
Replace dots in filename Python
im trying to replace all dots (and accents, but's already done) in filename with underscore except extension dot of course.
I saw a lot of solutions but mainly with bash. Cant find for python. Probably I should use regex but dont have much experience here. Below my code:</p>

```<code>path2 = 'xx'
dicto = {"ą":"a",
         "ś":"s",
         "ę":"e",
         "ć":"c",
         "ż":"z",
         "ź":"z",
         "ó":"o",
         "ł":"l",
         "ń":"n"}

def find_replace(string, dictionary):
    for item in string:
        if item in dictionary.keys():
            string = string.replace(item, dictionary[item])
    return string

def change_name(path=path2):
    for root, dirs, files in os.walk(path):
        for filename in files:
            if not filename.startswith('~'):
                os.rename(os.path.join(root,filename), os.path.join(root,find_replace(filename, dicto)))

change_name()

</code>```

答: Check out os.path.splitext and replace dots only in the first part of the filename.</p>

Title: Replace dots in filename Python

Body:
im trying to replace all dots (and accents, but's already done) in filename with underscore except extension dot of course.
I saw a lot of solutions but mainly with bash. Cant find for python. Probably I should use regex but dont have much experience here. Below my code:

path2 = 'xx'
dicto = {"ą":"a",
         "ś":"s",
         "ę":"e",
         "ć":"c",
         "ż":"z",
         "ź":"z",
         "ó":"o",
         "ł":"l",
         "ń":"n"}

def find_replace(string, dictionary):
    for item in string:
        if item in dictionary.keys():
            string = string.replace(item, dictionary[item])
    return string

def change_name(path=path2):
    for root, dirs, files in os.walk(path):
        for filename in files:
            if not filename.startswith('~'):
                os.rename(os.path.join(root,filename), os.path.join(root,find_replace(filename, dicto)))

change_name()


问:
@ApiResponse with empty response body (Spring Boot)
I'm looking for a way to tell swagger that a certain API response code doesn't have a response body. A get response, for example, that can either return a 200 code with the actual object as a response or a 404 if the object associated with the passed ID doesn't exist:

```<code>@ApiResponses(value = {
    @ApiResponse(responseCode = "200", description = "Object found"),
    @ApiResponse(responseCode = "404", description = "Invalid object ID", content = @Content)
})
</code>```

This is the closest thing I could figure out but it's not perfect, I still get an annoying "Media type" under the description of the 404 response.
Thanks!

答:
You can use the following on top of your method in v2

```<code>@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Success", response = YourObject.class),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message="Forbidden"),
        @ApiResponse(code = 404, message = "Not Found"),
        @ApiResponse(code = 500, message = "Failure")
})
</code>```

For V3, you could try something like this in case your method is returning some object

```<code>@Operation(summary = "Add a new object", description = "", tags = { "yourObject" })
@ApiResponses(value = {
        @ApiResponse(responseCode = "201", description = "Object created",content = @Content(schema = @Schema(implementation = YourObject.class))),
        @ApiResponse(responseCode = "400", description = "Invalid input"),
        @ApiResponse(responseCode = "409", description = "Object already exists") })
        @PostMapping(value = "/your-url", consumes = {"application/json","application/xml" })
        public ResponseEntity<YourObject> addObject(
            ...
            return ...
        }
</code>```

In case your method is returning void try this one

```<code>@Operation(summary = "Update an existing object", description = "", tags = { "yourObject" })
@ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "successful operation"),
        @ApiResponse(responseCode = "400", description = "Invalid ID supplied"),
        @ApiResponse(responseCode = "404", description = "Object not found"),
        @ApiResponse(responseCode = "405", description = "Validation exception") })
        @PutMapping(value = "/your-url/{id}", consumes = { "application/json", "application/xml" })
        public ResponseEntity<Void> addObject(
            ...
            return ...
        }
</code>```

Body:
I'm looking for a way to tell swagger that a certain API response code doesn't have a response body. A get response, for example, that can either return a 200 code with the actual object as a response or a 404 if the object associated with the passed ID doesn't exist:

@ApiResponses(value = {
    @ApiResponse(responseCode = "200", description = "Object found"),
    @ApiResponse(responseCode = "404", description = "Invalid object ID", content = @Content)
})

This is the closest thing I could figure out but it's not perfect, I still get an annoying "Media type" under the description of the 404 response.
Thanks!

Body:
You can use the following on top of your method in v2

@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Success", response = YourObject.class),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message="Forbidden"),
        @ApiResponse(code = 404, message = "Not Found"),
        @ApiResponse(code = 500, message = "Failure")
})

For V3, you could try something like this in case your method is returning some object

@Operation(summary = "Add a new object", description = "", tags = { "yourObject" })
@ApiResponses(value = {
        @ApiResponse(responseCode = "201", description = "Object created",content = @Content(schema = @Schema(implementation = YourObject.class))),
        @ApiResponse(responseCode = "400", description = "Invalid input"),
        @ApiResponse(responseCode = "409", description = "Object already exists") })
        @PostMapping(value = "/your-url", consumes = {"application/json","application/xml" })
        public ResponseEntity<YourObject> addObject(
            ...
            return ...
        }

In case your method is returning void try this one

@Operation(summary = "Update an existing object", description = "", tags = { "yourObject" })
@ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "successful operation"),
        @ApiResponse(responseCode = "400", description = "Invalid ID supplied"),
        @ApiResponse(responseCode = "404", description = "Object not found"),
        @ApiResponse(responseCode = "405", description = "Validation exception") })
        @PutMapping(value = "/your-url/{id}", consumes = { "application/json", "application/xml" })
        public ResponseEntity<Void> addObject(
            ...
            return ...
        }


问:
How to convert unix timestamp to datetime in milliseconds python 3
I have a large dataset with unix (epoch) time that I need to convert to datetime in milliseconds. My code should do the job since I specified to return milliseconds, but somehow it only returns up to seconds. What needs to be changed?</p>

```<code>import pandas as pd

# reading in the excel file timestamps.xlsx
# this file contains a column 'epoch' with the unix epoch timestamps
df = pd.read_excel('epoch_time.xlsx')

# translate epochs into human readable and write into newly created column
# timestamps are in ms, hence the unit
df['time'] = pd.to_datetime(df['epoch'], unit='ms')

# remove epoch row
df = df.drop('epoch', axis=1)

# write to excel file 'new_timestamps.xlsx'
# index=False prevents pandas to add the indices as a new column
df.to_excel('new_timestamps.xlsx', index=False)
</code>```

Body:
I have a large dataset with unix (epoch) time that I need to convert to datetime in milliseconds. My code should do the job since I specified to return milliseconds, but somehow it only returns up to seconds. What needs to be changed?

import pandas as pd

# reading in the excel file timestamps.xlsx
# this file contains a column 'epoch' with the unix epoch timestamps
df = pd.read_excel('epoch_time.xlsx')

# translate epochs into human readable and write into newly created column
# timestamps are in ms, hence the unit
df['time'] = pd.to_datetime(df['epoch'], unit='ms')

# remove epoch row
df = df.drop('epoch', axis=1)

# write to excel file 'new_timestamps.xlsx'
# index=False prevents pandas to add the indices as a new column
df.to_excel('new_timestamps.xlsx', index=False)

Body:
I guess this is what you are looking for:

pd.to_datetime(1582200012345, unit='ms').to_datetime64()

Output:

numpy.datetime64('2020-02-20T12:00:12.345000000')

Or for a column use:

df['time'] = pd.to_datetime(df['time'], unit='ms').apply(lambda x: x.to_datetime64())

Example:

df=pd.DataFrame([1582200012345,1582200012346])
df['time'] = pd.to_datetime(df[0], unit='ms').apply(lambda x: x.to_datetime64())
df
               0                    time
0  1582200012345 2020-02-20 12:00:12.345
1  1582200012345 2020-02-20 12:00:12.346


问:
Compare nested rows in a tibble and retrieve unique rows only
I have a tibble where each row contains some data. I would like to compare all the rows and retrieve only the unique ones.

reprex:

library(dplyr)

df <- tibble(
  data = list(mtcars, mtcars, iris, iris)
)

df
#> # A tibble: 4 x 1
#>   data
#>   <list>
#> 1 <df[,11] [32 × 11]>
#> 2 <df[,11] [32 × 11]>
#> 3 <df[,5] [150 × 5]>
#> 4 <df[,5] [150 × 5]>
```

<p><sup>Created on 2020-02-20 by the reprex package (v0.3.0)</sup></p>

<p><strong>expected output:</strong></p>

<pre class="lang-r prettyprint-override"><code>#> # A tibble: 2 x 1
#>   data
#>   <list>
#> 1 <df[,11] [32 × 11]>
#> 2 <df[,5] [150 × 5]>
</code>```

Any ideas? I have tried using dplyr::distinct() but it actually does not work in my real example. So, I don't think that is the correct way of doing it.

答:
Maybe you can try unique, i.e.,

```<code>unique(df)
</code>```

such that

```<code>> unique(df)
# A tibble: 2 x 1
  data
  <list>
1 <df[,11] [32 x 11]>
2 <df[,5] [150 x 5]>
</code>```

Body:
I have a tibble where each row contains some data. I would like to compare all the rows and retrieve only the unique ones.

reprex:

library(dplyr)

df <- tibble(
  data = list(mtcars, mtcars, iris, iris)
)

df
#> # A tibble: 4 x 1
#>   data
#>   <list>
#> 1 <df[,11] [32 × 11]>
#> 2 <df[,11] [32 × 11]>
#> 3 <df[,5] [150 × 5]>
#> 4 <df[,5] [150 × 5]>

Created on 2020-02-20 by the reprex package (v0.3.0)

expected output:

#> # A tibble: 2 x 1
#>   data
#>   <list>
#> 1 <df[,11] [32 × 11]>
#> 2 <df[,5] [150 × 5]>

Any ideas? I have tried using dplyr::distinct() but it actually does not work in my real example. So, I don't think that is the correct way of doing it.

Body:
Maybe you can try unique, i.e.,

unique(df)

such that

> unique(df)
# A tibble: 2 x 1
  data
  <list>
1 <df[,11] [32 x 11]>
2 <df[,5] [150 x 5]>


问:
How Does GetStringType Cause a Deadlock in Dll Main?
I'm looking at an application which hangs on Server 2016 but runs find on Server 2008 R2. I have traced it to a hang caused by deadlock when a particular DLL loads. Analysing the DLL (I don't have the source code) I can see that it violates the guideline here

Call GetStringTypeA, GetStringTypeEx, or GetStringTypeW (either
directly or indirectly). This can cause a deadlock or a crash

Specifically it calls GetStringTypeW from DllMain.

I'm trying to understand how this function can cause deadlocks in DllMain.

答:
Calling a function from DllMain that will (directly or indirectly) attempt to load another module is going to deadlock.

Module loading is serialized. The system uses a lock to ensure that at any given time no more than a single DLL entry point is entered. If you are calling LoadLibrary (directly or indirectly) from your DLL entry point, you are holding the loader lock. LoadLibrary will attempt to acquire the loader lock itself prior to calling into the module's entry point. So while your code is waiting for LoadLibrary to return, LoadLibrary is waiting for the lock you are holding. That's a deadlock.

This is likely the reason why calling GetStringType from DllMain deadlocks. Without access to source code I cannot verify this, though. You may be able to find evidence by enabling loader snaps.


问:
How should i catch and handle 406 error in VUEJS
I have a route where i send to the api the day and h to verify in database if there is an opening in a schedule, if is not the api is sending 406. And i'm getting in console 406 error.
How should i handle that error to have a clean console? </p>

答:
```<code>check_time(day,hour){
    var fields = {};
    fields.day = parseInt(day);
    fields.hour = parseInt(hour);

    try {
        this.$http.post('courses/check', fields)
    } catch {
        this.$store.dispatch('alert', {'message': 'Already exist a course in this interval.'});
    }

}
</code>```


问:
Lidar Data for the UK and Asia
I create golf courses in the game The Golf Club 2019, using TGC Lidar Course Designer

I use USGS Lidar Data Site for the lidar data in the USA.  I am looking for a site similar for the UK and Asia regions.  Does anyone know of any sites that I can download both the LAZ files and xml files associated with the map data?  Any help would be appreciated.

答:
The LAStools blog have several publications about open LiDAR data.

Here follows some of them:

Brazil/ Pernambuco

Canada/ New Brunswick

Germany/ North Rhine-Westphalia

Title: Lidar Data for the UK and Asia


问:
html5 form validation modernizr safari
this is the working example:
http://jsfiddle.net/trustweb/sTSMW/

i notice an errore using safari 5.05

if i set a form as  in an html5 page and i repleace the functionality with jquery if modernizr fail the test:

```<code>Modernizr.inputtypes.email && Modernizr.input.required && Modernizr.input.placeholder
</code>```

with other browsers (firefox, chrome and opera) the browser validate the form

in ie jquery replace the validation function

in safari it dosen't work, modernizr seems to return true while testing html5 compatibilies:

```<code>yepnope(
{
    test : Modernizr.inputtypes.email && Modernizr.input.required && Modernizr.input.placeholder,
    nope : 'http://www.trustweb.it/webforms_home.js'
});
</code>```

答:
actually i did't find how to do just with modernizr, so i implemented this check:</p>

```<code>var browser=navigator.userAgent.toLowerCase();
if (browser.indexOf("safari") != -1 && browser.indexOf("chrome") == -1) browser='safari';

yepnope(
{
    test : Modernizr.inputtypes.email && Modernizr.input.required && Modernizr.input.placeholder && browser!='safari',
    nope : 'javascript/webforms_home.js'
});
</code>```

Title: html5 form validation modernizr safari

Body:
this is the working example:
http://jsfiddle.net/trustweb/sTSMW/

i notice an errore using safari 5.05

if i set a form as  in an html5 page and i repleace the functionality with jquery if modernizr fail the test:

Modernizr.inputtypes.email && Modernizr.input.required && Modernizr.input.placeholder

with other browsers (firefox, chrome and opera) the browser validate the form

in ie jquery replace the validation function

in safari it dosen't work, modernizr seems to return true while testing html5 compatibilies:

yepnope(
{
    test : Modernizr.inputtypes.email && Modernizr.input.required && Modernizr.input.placeholder,
    nope : 'http://www.trustweb.it/webforms_home.js'
});

Body:
actually i did't find how to do just with modernizr, so i implemented this check:

var browser=navigator.userAgent.toLowerCase();
if (browser.indexOf("safari") != -1 && browser.indexOf("chrome") == -1) browser='safari';

yepnope(
{
    test : Modernizr.inputtypes.email && Modernizr.input.required && Modernizr.input.placeholder && browser!='safari',
    nope : 'javascript/webforms_home.js'
});


问:
Register a generic Validator using FluentValidation and Autofac
I have a generic class that handles different entities the same manner. I'm trying to implement a Validator in this generic class, the Validator type should change depending on the generic type. For example if the type is Person, the PersonValidator should get initialized. How is this possible using FluentValidation and Autofac? I've tried it using a generic BaseValidator but I cannot seem to register it correctly so the PersonValidator doesn't get called.

Generic class

```<code>var validator = new BaseValidator<TEntity>(); // TEntity = Person
await validator.ValidateAndThrowAsync(person);
</code>```

BaseValidator

```<code>public class BaseValidator<TEntity> : AbstractValidator<TEntity>
{
}
</code>```

PersonValidator

```<code>public class PersonValidator : BaseValidator<Person>
{
    public PersonValidator()
    {
        RuleFor(x => x.Name).NotEmpty();
    }
}
</code>```

Autofac registrations that I've tried

```<code> builder.RegisterGeneric(typeof(BaseValidator<>)).As(typeof(IValidator<>)).InstancePerDependency();
 builder.RegisterType<BaseValidator<Person>().As(typeof(IValidator<Person>)).InstancePerDependency();
 builder.RegisterType<PersonValidator>().As(typeof(IValidator<Person>)).InstancePerDependency();
 builder.RegisterType<PersonValidator>().As(typeof(BaseValidator<Person>)).InstancePerDependency();
</code>```

答: You can't use var validator = new BaseValidator<TEntity>(); You have to inject an IValidator<Person> in your ctor (or IValidator<T>).

Body:
I have a generic class that handles different entities the same manner. I'm trying to implement a Validator in this generic class, the Validator type should change depending on the generic type. For example if the type is Person, the PersonValidator should get initialized. How is this possible using FluentValidation and Autofac? I've tried it using a generic BaseValidator but I cannot seem to register it correctly so the PersonValidator doesn't get called.

Generic class

var validator = new BaseValidator<TEntity>(); // TEntity = Person
await validator.ValidateAndThrowAsync(person);

BaseValidator

public class BaseValidator<TEntity> : AbstractValidator<TEntity>
{
}

PersonValidator

public class PersonValidator : BaseValidator<Person>
{
    public PersonValidator()
    {
        RuleFor(x => x.Name).NotEmpty();
    }
}

Autofac registrations that I've tried

 builder.RegisterGeneric(typeof(BaseValidator<>)).As(typeof(IValidator<>)).InstancePerDependency();
 builder.RegisterType<BaseValidator<Person>().As(typeof(IValidator<Person>)).InstancePerDependency();
 builder.RegisterType<PersonValidator>().As(typeof(IValidator<Person>)).InstancePerDependency();
 builder.RegisterType<PersonValidator>().As(typeof(BaseValidator<Person>)).InstancePerDependency();


问:
Navigator PushReplacementName gives back button in flutter
This is weird but below code is not working for me. I get a back arrow on the home screen when using below code.

First line below is for dismissing the dialog box. second one is to go to home screen.

 Navigator.of(context, rootNavigator: true).pop();
 Navigator.of(context).pushReplacementNamed(HomeScreen.id);
```

This is first time I am facing this kind of situation with pushReplacementNamed. what's going on here ?

答:
It is probably because you have another screen in the stack. When you call pushReplacementNamed, it doesn't replace whole stack with the one you give. Can you try the following code;

// true don't work based on above query condition

 Navigator.of(context).pushNamedAndRemoveUntil(HomeScreen.id, (Route<dynamic> route) => true);

// false works
Navigator.of(context).pushNamedAndRemoveUntil(HomeScreen.id, (Route<dynamic> route) => false);

Body:
This is weird but below code is not working for me. I get a back arrow on the home screen when using below code.

First line below is for dismissing the dialog box. second one is to go to home screen.

 Navigator.of(context, rootNavigator: true).pop();
 Navigator.of(context).pushReplacementNamed(HomeScreen.id);

This is first time I am facing this kind of situation with pushReplacementNamed. what's going on here ?


问:
Card is flipped when a child button (with different functionality) is pressed. How to stop the propagation to the parent?
I have a card which is getting flipped when somebody presses on it (and that is totally fine) so the user can read more information from the back of the card. The card itself contains 2 buttons: 1st for redirecting the user to another page and the 2nd - triggering a modal popup.

The problem I am facing is when I press any of the buttons, both actions are performed. For example pressing the button triggering the modal pop up - the card is getting flipped and the modal appears (you can see the flipped card in the background).

How can I 'isolate' the clicks on the buttons not to trigger the card flip?

```<code><div class="col-md-4 d-flex align-items-stretch">
   <div class="student-card">
      <div class="card" id="busainfo_@i" onclick= "this.classList.toggle('flipped');">
         <div class="card-body d-flex flex-column">
            <h3 class="card-title">Jesper</h3>
            <p class="card-text">Short Description</p>
            <button type="button" class="btn btn-primary redirect_1" click="window.location.href ='https://google.com';"> Read More </button>
            <button type="button" class="btn btn-primary opensend_1" id="opensend_1" data-toggle="modal" data-target="#sendview_1">Send msg</button>
         </div>
         <div class="side back d-flex flex-column">
            <h3>Jesper</h3>
            <p>About Jesper</p>
         </div>
      </div>
   </div>
</div>
</code>```

I tried the stopPropagation(), but I could not make it work with my example.

答:
You can do it with JQuery.

You can bind the click event to the card element, and when the user clicks the card, check if the target clicked is a button. If it isn't a button, flip the card. Otherwise, do nothing, and the default button behavior will trigger.

This way the card will be flipped only when the user clicks the card, but not the element with the .btn class.

```<code>$("#busainfo_@i").on("click", function(e){
   if(!($(e.target).hasClass("btn"))){
       $(this).toggleClass("flipped");
   }
});
</code>```

Body:
I have a card which is getting flipped when somebody presses on it (and that is totally fine) so the user can read more information from the back of the card. The card itself contains 2 buttons: 1st for redirecting the user to another page and the 2nd - triggering a modal popup.

The problem I am facing is when I press any of the buttons, both actions are performed. For example pressing the button triggering the modal pop up - the card is getting flipped and the modal appears (you can see the flipped card in the background).

How can I 'isolate' the clicks on the buttons not to trigger the card flip?

Jesper

Short Description

            <button type="button" class="btn btn-primary redirect_1" click="window.location.href ='https://google.com';"> Read More </button>
            <button type="button" class="btn btn-primary opensend_1" id="opensend_1" data-toggle="modal" data-target="#sendview_1">Send msg</button>

Jesper

About Jesper

I tried the stopPropagation(), but I could not make it work with my example.

Body:
You can do it with JQuery.

You can bind the click event to the card element, and when the user clicks the card, check if the target clicked is a button. If it isn't a button, flip the card. Otherwise, do nothing, and the default button behavior will trigger.

This way the card will be flipped only when the user clicks the card, but not the element with the .btn class.

$("#busainfo_@i").on("click", function(e){
   if(!($(e.target).hasClass("btn"))){
       $(this).toggleClass("flipped");
   }
});


问:
Software for browsing classes in a C/C++ project
I have seen that some developers have a graphical representation of all their classes in an image file which comes with their project. How can I myself create these graphics?

Basically they show what classes exist in a file and how these files relate to each other.

Thanks

答: One common tool that allows people to do that fairly easily is Dot, which comes as part of Graphviz. Dot is sort of a markup language describing graphs. You can generate Dot files manually if you like, but there are a lot of code analysis tools that will do the job for you. Doxygen is one.</p>