问:
Can't run react-native run-android on Mac
I have a complete react native environment on my iMac, the project run completely when i run react-native run-ios, but when i'll do this with android it doesn't work, metro bundler window opens but doesn't work and don't appear any message.

What i have to do?

My terminal after i run "react-native run-android"

```<code>Daives-iMac:generico_toaqui_app fourtime$ react-native run-android
warn The following packages use deprecated "rnpm" config that will stop working from next release:
  - react-native-code-push: https://microsoft.github.io/code-push
  - react-native-maps: https://github.com/react-native-community/react-native-maps#readme
Please notify their maintainers about it. You can find more details at https://github.com/react-native-community/cli/blob/master/docs/configuration.md#migration-guide.
error React Native CLI uses autolinking for native dependencies, but the following modules are linked manually:
  - @react-native-community/netinfo (to unlink run: "react-native unlink @react-native-community/netinfo")
  - bugsnag-react-native (to unlink run: "react-native unlink bugsnag-react-native")
  - react-native-camera (to unlink run: "react-native unlink react-native-camera")
  - react-native-code-push (to unlink run: "react-native unlink react-native-code-push")
  - react-native-contacts (to unlink run: "react-native unlink react-native-contacts")
  - react-native-device-info (to unlink run: "react-native unlink react-native-device-info")
  - react-native-firebase (to unlink run: "react-native unlink react-native-firebase")
  - react-native-fs (to unlink run: "react-native unlink react-native-fs")
  - react-native-image-picker (to unlink run: "react-native unlink react-native-image-picker")
  - react-native-image-resizer (to unlink run: "react-native unlink react-native-image-resizer")
  - react-native-maps (to unlink run: "react-native unlink react-native-maps")
  - react-native-otp-verify (to unlink run: "react-native unlink react-native-otp-verify")
  - react-native-power-saving-mode (to unlink run: "react-native unlink react-native-power-saving-mode")
  - react-native-vector-icons (to unlink run: "react-native unlink react-native-vector-icons")
  - rethink-gpstracking (to unlink run: "react-native unlink rethink-gpstracking")
  - rethink-material-design (to unlink run: "react-native unlink rethink-material-design")
This is likely happening when upgrading React Native from below 0.60 to 0.60 or above. Going forward, you can unlink this dependency via "react-native unlink <dependency>" and it will be included in your app automatically. If a library isn't compatible with autolinking, disregard this message and notify the library maintainers.
Read more about autolinking: https://github.com/react-native-community/cli/blob/master/docs/autolinking.md
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 1891 file(s) to forward-jetify. Using 4 workers...
info Starting JS server...
info Installing the app...
Starting a Gradle Daemon, 1 incompatible and 2 stopped Daemons could not be reused, use --status for details

> Configure project :app
Could not find google-services.json while looking in [src/nullnull/debug, src/debug/nullnull, src/nullnull, src/debug, src/nullnullDebug]
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
Could not find google-services.json while looking in [src/nullnull/release, src/release/nullnull, src/nullnull, src/release, src/nullnullRelease]
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
Could not find google-services.json while looking in [src/nullnull/releaseStaging, src/releaseStaging/nullnull, src/nullnull, src/releaseStaging, src/nullnullReleaseStaging]
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)

> Configure project :react-native-firebase
react-native-firebase: using React Native prebuilt binary from /Users/fourtime/Documents/React Native/generico_toaqui_app/node_modules/react-native/android

> Configure project :react-native-image-resizer
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed soon. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

> Configure project :react-native-power-saving-mode
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed soon. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

> Configure project :rethink-gpstracking
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed soon. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

> Configure project :rethink-material-design
WARNING: The following project options are deprecated and have been removed:
android.useDeprecatedNdk
NdkCompile is no longer supported

WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed soon. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

> Configure project :rethink-utils
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed soon. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html
WARNING: The specified Android SDK Build Tools version (26.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '26.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (26.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '26.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (27.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '27.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (28.0.2) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '28.0.2'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (23.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '23.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (23.0.1) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '23.0.1'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (23.0.1) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '23.0.1'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (23.0.1) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '23.0.1'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.

> Task :app:processDebugGoogleServices
Parsing json file: /Users/fourtime/Documents/React Native/generico_toaqui_app/android/app/google-services.json

> Task :app:processDebugManifest
/Users/fourtime/Documents/React Native/generico_toaqui_app/android/app/src/debug/AndroidManifest.xml:24:9-31:50 Warning:
        activity#com.google.firebase.auth.internal.FederatedSignInActivity@android:launchMode was tagged at AndroidManifest.xml:24 to replace other declarations but no other declaration present

> Task :app:stripDebugDebugSymbols UP-TO-DATE
Compatible side by side NDK version was not found.

> Task :app:installDebug
04:58:49 V/ddms: execute: running am get-config
04:58:50 V/ddms: execute 'am get-config' on 'S541008694' : EOF hit. Read: -1
04:58:50 V/ddms: execute: returning
Installing APK 'app-debug.apk' on 'Twist 2 Go - 8.1.0' for app:debug
04:58:50 D/app-debug.apk: Uploading app-debug.apk onto device 'S541008694'
04:58:50 D/Device: Uploading file onto device 'S541008694'
04:58:50 D/ddms: Reading file permision of /Users/fourtime/Documents/React Native/generico_toaqui_app/android/app/build/outputs/apk/debug/app-debug.apk as: rw-r--r--
04:58:52 V/ddms: execute: running pm install -r -t "/data/local/tmp/app-debug.apk"
04:59:07 V/ddms: execute 'pm install -r -t "/data/local/tmp/app-debug.apk"' on 'S541008694' : EOF hit. Read: -1
04:59:07 V/ddms: execute: returning
04:59:07 V/ddms: execute: running rm "/data/local/tmp/app-debug.apk"
04:59:08 V/ddms: execute 'rm "/data/local/tmp/app-debug.apk"' on 'S541008694' : EOF hit. Read: -1
04:59:08 V/ddms: execute: returning
Installed on 1 device.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 2m 2s
485 actionable tasks: 9 executed, 476 up-to-date
/bin/sh: adb: command not found
info Connecting to the development server...
warn Failed to connect to development server using "adb reverse": spawnSync adb ENOENT
info Starting the app...
</code>```

My terminal's print screen after i run android and under it my metro bundler

答:
Looks likes you don't have the "NDK side by side" enabled per this error:

Compatible side by side NDK version was not found.

Open your Android Studio and install the "NDK (Side by side)" tool: Android Studio -> Tools -> SDK Manager -> SDK Tools

Then: react-native run-android

I hope this help.

Body:
I have a complete react native environment on my iMac, the project run completely when i run react-native run-ios, but when i'll do this with android it doesn't work, metro bundler window opens but doesn't work and don't appear any message.

What i have to do?

My terminal after i run "react-native run-android"

Daives-iMac:generico_toaqui_app fourtime$ react-native run-android
warn The following packages use deprecated "rnpm" config that will stop working from next release:
  - react-native-code-push: https://microsoft.github.io/code-push
  - react-native-maps: https://github.com/react-native-community/react-native-maps#readme
Please notify their maintainers about it. You can find more details at https://github.com/react-native-community/cli/blob/master/docs/configuration.md#migration-guide.
error React Native CLI uses autolinking for native dependencies, but the following modules are linked manually:
  - @react-native-community/netinfo (to unlink run: "react-native unlink @react-native-community/netinfo")
  - bugsnag-react-native (to unlink run: "react-native unlink bugsnag-react-native")
  - react-native-camera (to unlink run: "react-native unlink react-native-camera")
  - react-native-code-push (to unlink run: "react-native unlink react-native-code-push")
  - react-native-contacts (to unlink run: "react-native unlink react-native-contacts")
  - react-native-device-info (to unlink run: "react-native unlink react-native-device-info")
  - react-native-firebase (to unlink run: "react-native unlink react-native-firebase")
  - react-native-fs (to unlink run: "react-native unlink react-native-fs")
  - react-native-image-picker (to unlink run: "react-native unlink react-native-image-picker")
  - react-native-image-resizer (to unlink run: "react-native unlink react-native-image-resizer")
  - react-native-maps (to unlink run: "react-native unlink react-native-maps")
  - react-native-otp-verify (to unlink run: "react-native unlink react-native-otp-verify")
  - react-native-power-saving-mode (to unlink run: "react-native unlink react-native-power-saving-mode")
  - react-native-vector-icons (to unlink run: "react-native unlink react-native-vector-icons")
  - rethink-gpstracking (to unlink run: "react-native unlink rethink-gpstracking")
  - rethink-material-design (to unlink run: "react-native unlink rethink-material-design")
This is likely happening when upgrading React Native from below 0.60 to 0.60 or above. Going forward, you can unlink this dependency via "react-native unlink <dependency>" and it will be included in your app automatically. If a library isn't compatible with autolinking, disregard this message and notify the library maintainers.
Read more about autolinking: https://github.com/react-native-community/cli/blob/master/docs/autolinking.md
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 1891 file(s) to forward-jetify. Using 4 workers...
info Starting JS server...
info Installing the app...
Starting a Gradle Daemon, 1 incompatible and 2 stopped Daemons could not be reused, use --status for details

> Configure project :app
Could not find google-services.json while looking in [src/nullnull/debug, src/debug/nullnull, src/nullnull, src/debug, src/nullnullDebug]
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
Could not find google-services.json while looking in [src/nullnull/release, src/release/nullnull, src/nullnull, src/release, src/nullnullRelease]
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
Could not find google-services.json while looking in [src/nullnull/releaseStaging, src/releaseStaging/nullnull, src/nullnull, src/releaseStaging, src/nullnullReleaseStaging]
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)

> Configure project :react-native-firebase
react-native-firebase: using React Native prebuilt binary from /Users/fourtime/Documents/React Native/generico_toaqui_app/node_modules/react-native/android

> Configure project :react-native-image-resizer
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed soon. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

> Configure project :react-native-power-saving-mode
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed soon. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

> Configure project :rethink-gpstracking
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed soon. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

> Configure project :rethink-material-design
WARNING: The following project options are deprecated and have been removed:
android.useDeprecatedNdk
NdkCompile is no longer supported

WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed soon. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html

> Configure project :rethink-utils
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed soon. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html
WARNING: The specified Android SDK Build Tools version (26.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '26.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (26.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '26.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (27.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '27.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (28.0.2) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '28.0.2'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (23.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '23.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (23.0.1) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '23.0.1'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (23.0.1) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '23.0.1'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
WARNING: The specified Android SDK Build Tools version (23.0.1) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.5.3.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '23.0.1'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.

> Task :app:processDebugGoogleServices
Parsing json file: /Users/fourtime/Documents/React Native/generico_toaqui_app/android/app/google-services.json

> Task :app:processDebugManifest
/Users/fourtime/Documents/React Native/generico_toaqui_app/android/app/src/debug/AndroidManifest.xml:24:9-31:50 Warning:
        activity#com.google.firebase.auth.internal.FederatedSignInActivity@android:launchMode was tagged at AndroidManifest.xml:24 to replace other declarations but no other declaration present

> Task :app:stripDebugDebugSymbols UP-TO-DATE
Compatible side by side NDK version was not found.

> Task :app:installDebug
04:58:49 V/ddms: execute: running am get-config
04:58:50 V/ddms: execute 'am get-config' on 'S541008694' : EOF hit. Read: -1
04:58:50 V/ddms: execute: returning
Installing APK 'app-debug.apk' on 'Twist 2 Go - 8.1.0' for app:debug
04:58:50 D/app-debug.apk: Uploading app-debug.apk onto device 'S541008694'
04:58:50 D/Device: Uploading file onto device 'S541008694'
04:58:50 D/ddms: Reading file permision of /Users/fourtime/Documents/React Native/generico_toaqui_app/android/app/build/outputs/apk/debug/app-debug.apk as: rw-r--r--
04:58:52 V/ddms: execute: running pm install -r -t "/data/local/tmp/app-debug.apk"
04:59:07 V/ddms: execute 'pm install -r -t "/data/local/tmp/app-debug.apk"' on 'S541008694' : EOF hit. Read: -1
04:59:07 V/ddms: execute: returning
04:59:07 V/ddms: execute: running rm "/data/local/tmp/app-debug.apk"
04:59:08 V/ddms: execute 'rm "/data/local/tmp/app-debug.apk"' on 'S541008694' : EOF hit. Read: -1
04:59:08 V/ddms: execute: returning
Installed on 1 device.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 2m 2s
485 actionable tasks: 9 executed, 476 up-to-date
/bin/sh: adb: command not found
info Connecting to the development server...
warn Failed to connect to development server using "adb reverse": spawnSync adb ENOENT
info Starting the app...

My terminal's print screen after i run android and under it my metro bundler


来源: stackexchange

问:
Eslint rule for linebreaks in function bodies
I am looking for a rule which will mark the following as error:

const setStuff = () => { setThing(2); setOtherThing(3); };
```

<p>I want to enfore a linebreak when there is multiple statements in the body, so this should be correct:</p>

<pre class="lang-js prettyprint-override"><code>const setStuff = () => {
    setThing(2);
    setOtherThing(3);
};
</code>```

Which rules is applicable for this? I can't seem to find one. I do want to keep allowing one liners for returns (e.g. const get = () => 3)

答:
The docs: brace-style

You can use it in your .eslintrc like this:

```<code>'rules': {
    'brace-style': [
        'error',
        '1tbs'
    ]
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am looking for a rule which will mark the following as error:

const setStuff = () => { setThing(2); setOtherThing(3); };

I want to enfore a linebreak when there is multiple statements in the body, so this should be correct:

const setStuff = () => {
    setThing(2);
    setOtherThing(3);
};

Which rules is applicable for this? I can't seem to find one. I do want to keep allowing one liners for returns (e.g. const get = () => 3)

Body:
The docs: brace-style

You can use it in your .eslintrc like this:

'rules': {
    'brace-style': [
        'error',
        '1tbs'
    ]
}


问:
zsh: Evaluate array as command
It is very useful to be able to use array constructs to compose large, multi-line commands.  For example:

```<code>declare -a command=(
   somecommand
       -flagA # comment
       -flagB # comment

   # No need for line continuation characters!
   foo/bar/baz.ext

   # Pipe into grep
   || grep fizz buzz # <=== This does not work!
)
</code>```

And it can then be executed as ${command[@]}.  However, you cannot embed control-flow characters like && or || and have them executed correctly.

Is there any way to do this from a ZSH array?

答:
What you have in your example isn't a pipe; it's a command list. However, you also don't need implicit line continuations for either || or |.

```<code>someCommandArgs=(
    -flagA  # comment
    -flagB  # comment

    foo/bar/baz.ext
)

someCommand "${someCommandArgs[@]}" |
  grep fizz buzz
</code>```

A command cannot end with |, so the parser knows the command must continue onto the other line.

The above can be packaged into a single function:

```<code>myCommand () {
  local -a args=(
      -flagA  # comment
      -flagB  # comment

      foo/bar/baz.ext
  )
  someCommand "${args[@]}" |
    grep fizz buzz
}
</code>```

Title: zsh: Evaluate array as command

Body:
It is very useful to be able to use array constructs to compose large, multi-line commands.  For example:

declare -a command=(
   somecommand
       -flagA # comment
       -flagB # comment

   # No need for line continuation characters!
   foo/bar/baz.ext

   # Pipe into grep
   || grep fizz buzz # <=== This does not work!
)

And it can then be executed as ${command[@]}.  However, you cannot embed control-flow characters like && or || and have them executed correctly.

Is there any way to do this from a ZSH array?

Body:
What you have in your example isn't a pipe; it's a command list. However, you also don't need implicit line continuations for either || or |.

someCommandArgs=(
    -flagA  # comment
    -flagB  # comment

    foo/bar/baz.ext
)

someCommand "${someCommandArgs[@]}" |
  grep fizz buzz

A command cannot end with |, so the parser knows the command must continue onto the other line.

The above can be packaged into a single function:

myCommand () {
  local -a args=(
      -flagA  # comment
      -flagB  # comment

      foo/bar/baz.ext
  )
  someCommand "${args[@]}" |
    grep fizz buzz
}


问:
how to covert callbacks to promise?
i have next code

```<code>paypal.payment.create(create_payment_json, function (error, payment) {
        if (error) {
            throw error;
        } else {
            for(let i = 0;i < payment.links.length;i++){
              if(payment.links[i].rel === 'approval_url'){
                res.send({link:payment.links[i].href});
              }
            }
        }
});
</code>```

i neen to convert that to a promise:

```<code>const { links } = await paypal.payment.create(create_payment_json);
</code>```

答:
```<code>const PaypalPromise = module.exports;

const Paypal = require('paypal-rest-sdk').configure({
  mode: 'sandbox',
  client_id: 'your id',
  client_secret: 'your secret',
});

PaypalPromise .create = (pay) => new Promise((resolve, reject) => {
  Paypal.payment.create(pay, (error, payment) => {
    if (error) return reject(error);

    return resolve(payment);
  });
});
</code>```

Title: how to covert callbacks to promise?

Body:
i have next code

paypal.payment.create(create_payment_json, function (error, payment) {
        if (error) {
            throw error;
        } else {
            for(let i = 0;i < payment.links.length;i++){
              if(payment.links[i].rel === 'approval_url'){
                res.send({link:payment.links[i].href});
              }
            }
        }
});

i neen to convert that to a promise:

const { links } = await paypal.payment.create(create_payment_json);


问:
What causes ClickOnce URLDownloadToCacheFile failed during installation?
I'm getting the following error when installing my ClickOnce application via firefox. It doesn't happen with IE on the same computer. I swear I've installed it via firefox before. This is a Windows 7 machine.

```<code>The following properties have been set:
Property: [AdminUser] = true {boolean}
Property: [ProcessorArchitecture] = Intel {string}
Property: [VersionNT] = 6.1.0 {version}
Running checks for package '.NET Framework 2.0 (x86)', phase BuildList
Running external check with command 'C:\Users\luke\AppData\Local\Temp\VSDEF1A.tmp\DotNetFX\dotnetchk.exe' and parameters ''
Process exited with code 1
Setting value '1 {int}' for property 'DotNetInstalled'
Reading value 'Version' of registry key 'HKLM\Software\Microsoft\Internet Explorer'
Read string value '8.0.7600.16385'
Setting value '8.0.7600.16385 {string}' for property 'IEVersion'
The following properties have been set for package '.NET Framework 2.0 (x86)':
Property: [DotNetInstalled] = 1 {int}
Property: [IEVersion] = 8.0.7600.16385 {string}
Running checks for command 'DotNetFX\instmsia.exe'
Result of running operator 'ValueExists' on property 'VersionNT': true
Result of checks for command 'DotNetFX\instmsia.exe' is 'Bypass'
Running checks for command 'DotNetFX\WindowsInstaller-KB893803-v2-x86.exe'
Result of running operator 'ValueExists' on property 'Version9x': false
Result of running operator 'VersionLessThan' on property 'VersionNT' and value '5.0.3': false
Result of running operator 'VersionGreaterThanOrEqualTo' on property 'VersionMsi' and value '3.0': true
Result of checks for command 'DotNetFX\WindowsInstaller-KB893803-v2-x86.exe' is 'Bypass'
Running checks for command 'DotNetFX\dotnetfx.exe'
Result of running operator 'ValueNotEqualTo' on property 'DotNetInstalled' and value '0': true
Result of checks for command 'DotNetFX\dotnetfx.exe' is 'Bypass'
'.NET Framework 2.0 (x86)' RunCheck result: No Install Needed
Launching Application.
URLDownloadToCacheFile failed with HRESULT '-2146697211'
Error: An error occurred trying to download 'http://croppy.lukehunter.net/download/croppy.application'.
</code>```

The following is the howto from Microsoft, but this doesn't apply to firefox. There is no redirection happening either.

If a user has set Internet Explorer
  Advanced Security option "Warn if
  changing between secure and not secure
  mode" on the deployment target
  computer, and if the setup URL of the
  ClickOnce application being installed
  is redirected from a non-secure to a
  secure site (or vice-versa), the
  installation will fail because the
  Internet Explorer warning interrupts
  it.

答:
Internet Explorer calls either LaunchApplication or ShOpenVerbApplication procedure from dfshim.dll behind the scenes, whereas Firefox plug-in (as well as a standard bootstrapper created by Visual Studio 2008-2010, which could also produce this rare error) uses a different, out of date technique to launch ClickOnce applications. (Note, that LaunchApplication requires at least .NET Framework 2 SP 2.)

To avoid such error one could redirect Internet Explorer to a deployment manifest (.application) and all other browsers to a custom installer (.exe) that would install .NET Framework if necessary and then call ShOpenVerbApplication.

ContentLicense: CC BY-SA 2.5

Body:
I'm getting the following error when installing my ClickOnce application via firefox. It doesn't happen with IE on the same computer. I swear I've installed it via firefox before. This is a Windows 7 machine.

The following properties have been set:
Property: [AdminUser] = true {boolean}
Property: [ProcessorArchitecture] = Intel {string}
Property: [VersionNT] = 6.1.0 {version}
Running checks for package '.NET Framework 2.0 (x86)', phase BuildList
Running external check with command 'C:\Users\luke\AppData\Local\Temp\VSDEF1A.tmp\DotNetFX\dotnetchk.exe' and parameters ''
Process exited with code 1
Setting value '1 {int}' for property 'DotNetInstalled'
Reading value 'Version' of registry key 'HKLM\Software\Microsoft\Internet Explorer'
Read string value '8.0.7600.16385'
Setting value '8.0.7600.16385 {string}' for property 'IEVersion'
The following properties have been set for package '.NET Framework 2.0 (x86)':
Property: [DotNetInstalled] = 1 {int}
Property: [IEVersion] = 8.0.7600.16385 {string}
Running checks for command 'DotNetFX\instmsia.exe'
Result of running operator 'ValueExists' on property 'VersionNT': true
Result of checks for command 'DotNetFX\instmsia.exe' is 'Bypass'
Running checks for command 'DotNetFX\WindowsInstaller-KB893803-v2-x86.exe'
Result of running operator 'ValueExists' on property 'Version9x': false
Result of running operator 'VersionLessThan' on property 'VersionNT' and value '5.0.3': false
Result of running operator 'VersionGreaterThanOrEqualTo' on property 'VersionMsi' and value '3.0': true
Result of checks for command 'DotNetFX\WindowsInstaller-KB893803-v2-x86.exe' is 'Bypass'
Running checks for command 'DotNetFX\dotnetfx.exe'
Result of running operator 'ValueNotEqualTo' on property 'DotNetInstalled' and value '0': true
Result of checks for command 'DotNetFX\dotnetfx.exe' is 'Bypass'
'.NET Framework 2.0 (x86)' RunCheck result: No Install Needed
Launching Application.
URLDownloadToCacheFile failed with HRESULT '-2146697211'
Error: An error occurred trying to download 'http://croppy.lukehunter.net/download/croppy.application'.

The following is the howto from Microsoft, but this doesn't apply to firefox. There is no redirection happening either.

If a user has set Internet Explorer
  Advanced Security option "Warn if
  changing between secure and not secure
  mode" on the deployment target
  computer, and if the setup URL of the
  ClickOnce application being installed
  is redirected from a non-secure to a
  secure site (or vice-versa), the
  installation will fail because the
  Internet Explorer warning interrupts
  it.

ContentLicense: CC BY-SA 3.0


答:
Your schema is expecting an int, an int in Java has a maximum size of [-2 147 483 648 to           +2 147 483 647]. </p>

<p>So I would change the schema from int to long. </p>

Title: java.lang.IllegalArgumentException: Illegal sequence boundaries Spark

Body:
I am using Azure Databricks and Scala. I wanna show() a Dataframe but I obtained an error that I can not understand and I would like to solve it. The lines of code that I have are:

println("----------------------------------------------------------------Printing schema")
df.printSchema()
println("----------------------------------------------------------------Printing dataframe")
df.show()
println("----------------------------------------------------------------Error before")

The Standard output is the following one, the message "----------------------------------------------------------------Error before" it does not appears.

>     ----------------------------------------------------------------Printing schema
>     root
>      |-- processed: integer (nullable = false)
>      |-- processDatetime: string (nullable = false)
>      |-- executionDatetime: string (nullable = false)
>      |-- executionSource: string (nullable = false)
>      |-- executionAppName: string (nullable = false)
>
>     ----------------------------------------------------------------Printing dataframe
>     2020-02-18T14:19:00.069+0000: [GC (Allocation Failure) [PSYoungGen: 1497248K->191833K(1789440K)] 2023293K->717886K(6063104K),
> 0.0823288 secs] [Times: user=0.18 sys=0.02, real=0.09 secs]
>     2020-02-18T14:19:40.823+0000: [GC (Allocation Failure) [PSYoungGen: 1637209K->195574K(1640960K)] 2163262K->721635K(5914624K),
> 0.0483384 secs] [Times: user=0.17 sys=0.00, real=0.05 secs]
>     2020-02-18T14:19:44.843+0000: [GC (Allocation Failure) [PSYoungGen: 1640950K->139092K(1809920K)] 2167011K->665161K(6083584K),
> 0.0301711 secs] [Times: user=0.11 sys=0.00, real=0.03 secs]
>     2020-02-18T14:19:50.910+0000: Track exception: Job aborted due to stage failure: Task 59 in stage 62.0 failed 4 times, most recent
> failure: Lost task 59.3 in stage 62.0 (TID 2672, 10.139.64.6, executor
> 1): java.lang.IllegalArgumentException: Illegal sequence boundaries:
> 1581897600000000 to 1581811200000000 by 86400000000
>       at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage23.processNext(Unknown
> Source)
>       at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
>       at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$15$$anon$2.hasNext(WholeStageCodegenExec.scala:659)
>       at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)
>       at org.apache.spark.shuffle.sort.BypassMergeSortShuffleWriter.write(BypassMergeSortShuffleWriter.java:125)
>       at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:99)
>       at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:55)
>       at org.apache.spark.scheduler.Task.doRunTask(Task.scala:139)
>       at org.apache.spark.scheduler.Task.run(Task.scala:112)
>       at org.apache.spark.executor.Executor$TaskRunner$$anonfun$13.apply(Executor.scala:497)
>       at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1526)
>       at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:503)
>       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
>       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
>       at java.lang.Thread.run(Thread.java:748)
>
>     Driver stacktrace:.
>     2020-02-18T14:19:50.925+0000: Track message: Process finished with exit code 1. Metric: Writer. Value: 1.0.

Body:
Your schema is expecting an int, an int in Java has a maximum size of [-2 147 483 648 to           +2 147 483 647].

So I would change the schema from int to long.


问:
Javascript Binary Search algorithm unable to find number in the list
The following code seems to be unable to find the number in the list. Why might this be?

Trying this with the number to search for as '9' and the array of numbers consisting of numbers between 1-10 inclusively.

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
count = 0;

function binarySearch(array, number) {
    mid = Math.floor(array.length / 2);
    if (number === array[mid]) {
        return count;
    }

    else if (number < array[mid] && array.length > 1) {
        count++;
        arrayFirst = array.splice(0, array[mid]);
        console.log("Tried: ", array[mid])
        console.log(arrayFirst);
        return binarySearch(arrayFirst, number);
    }

    else if (number > array[mid] && array.length > 1) {
        count++;
        arraySecond = array.splice(array[mid], array.length);
        console.log("Tried: ", array[mid])
        console.log(arraySecond);
        return binarySearch(arraySecond, number);
    }

    else {
        return 'number doesnt exist';
    }

}
console.log(binarySearch(array, 4));```
</div>
</div>

The code is now struggling with finding the number 10
New Edit:</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>       array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13,14,15,16,17,18,19,20];
    count = 0;

    function binarySearch(array, number) {
        mid = Math.floor(array.length/ 2);
        if (number === array[mid]) {
            return count;
        }

        else if (number < array[mid] && array.length > 1) {
            count++;
            arrayFirst = array.splice(0, mid);
            console.log("Tried: ", array[mid])
            console.log(arrayFirst);
            return binarySearch(arrayFirst, number);
        }

        else if (number > array[mid] && array.length > 1) {
            count++;
            arraySecond = array.splice(array[mid], mid);
            console.log("Tried: ", array[mid])
            console.log(arraySecond);
            return binarySearch(arraySecond, number);
        }

        else {
            return 'number doesnt exist';
        }

    }

    console.log(binarySearch(array, 10));</code>```

答:
Some changes:

Take counting inside of the function by returning either one or zero or one plus the result of the call with a sub array.

Check length in advance (spelling matters ... arr) and return zero for unrachable values.

Use Array#slice instead of Array#splice (prevent mutation) and take the index, not the value of the item.

Finally return one plus the count of left or right side.

function binarySearch(array, number) {
    console.log(...array);
    var mid = Math.floor(array.length / 2);

    if (number === array[mid]) return 1;
    if (array.length <= 1) return 0;

    return number < array[mid]
        ? 1 + binarySearch(array.slice(0, mid), number)
        : 1 + binarySearch(array.slice(mid), number);
}

console.log('count:', binarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4));```

Body:
The following code seems to be unable to find the number in the list. Why might this be?

Trying this with the number to search for as '9' and the array of numbers consisting of numbers between 1-10 inclusively.

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
count = 0;

function binarySearch(array, number) {
    mid = Math.floor(array.length / 2);
    if (number === array[mid]) {
        return count;
    }

    else if (number < array[mid] && array.length > 1) {
        count++;
        arrayFirst = array.splice(0, array[mid]);
        console.log("Tried: ", array[mid])
        console.log(arrayFirst);
        return binarySearch(arrayFirst, number);
    }

    else if (number > array[mid] && array.length > 1) {
        count++;
        arraySecond = array.splice(array[mid], array.length);
        console.log("Tried: ", array[mid])
        console.log(arraySecond);
        return binarySearch(arraySecond, number);
    }

    else {
        return 'number doesnt exist';
    }

}
console.log(binarySearch(array, 4));

The code is now struggling with finding the number 10
New Edit:

       array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13,14,15,16,17,18,19,20];
    count = 0;

    function binarySearch(array, number) {
        mid = Math.floor(array.length/ 2);
        if (number === array[mid]) {
            return count;
        }

        else if (number < array[mid] && array.length > 1) {
            count++;
            arrayFirst = array.splice(0, mid);
            console.log("Tried: ", array[mid])
            console.log(arrayFirst);
            return binarySearch(arrayFirst, number);
        }

        else if (number > array[mid] && array.length > 1) {
            count++;
            arraySecond = array.splice(array[mid], mid);
            console.log("Tried: ", array[mid])
            console.log(arraySecond);
            return binarySearch(arraySecond, number);
        }

        else {
            return 'number doesnt exist';
        }

    }

    console.log(binarySearch(array, 10));


问:
GtKGLArea unable to create OpenGL 2.1 context
i'm currently working on a simple editor for my game engine project, while the project seems to run just fine on my main workstation ( GTX 650Ti with OpenGL 3.3+ support ) , but it'seems to be broken when im test it on my testing desktop ( GMA4500 with OpenGL 2.1 max support ).

The GtkGLArea's gtk_gl_area_make_current() unable to create OpenGL 2.1 context even if i specified the GL version with gtk_gl_area_set_required_version() to 2.1.

Tried to troubleshoot it with testing the gtk glarea demo ( https://git.gnome.org/browse/gtk+/tree/demos/gtk-demo/glarea.c ) and getting the same result.

Already search it on the web but none lead to any solution. Though someone have mention the same exatct issue on glarea example from ebassi (https://github.com/ebassi/glarea-example/issues/2)

Is there any solution to this?

Operating System: Fedora 23
GTK version 3.18

EDIT :
The Operating system (Fedora 23) are using OpenGL 2.1 ( checked with glxinfo ), and considering by demos given on GTK+ source i'm assuming GTK using GL 3.0+ as default. <s>is it any way to overide this?</s> (according to ebassi on his answer below, starting from GTK+ 3.20 GdkGLContext will falling back to legacy profiles if core profiles are not available. will test it as soon i upgrade to GTK+ 3.20)

EDIT 2:
I'm able to make workaround by using context created by SDL instead of GdkGLContext, but i'm still intrested to make GdkGLContext to work with OpenGL 2.1.

答:
You can use EGL to use legacy (pre-3.0) OpenGL versions with GtkDrawingArea

http://bobthegnome.blogspot.com/2014/09/using-egl-with-gtk.html


问:
How to structure python programs? Tried making it more structured, now runs 13 times slower
Im very new to programming, I wrote a simple program for a school project and wanted to make the code "prettier" by not just having the program be one giant function but instead be made up of multiple smaller functions with a singe purpose. I seemed to have messed up royally since the program now runs 13 times slower. How should I structured the program to make it run faster and just in general make programs easier to write, read and edit?

Here are the two programs:

First program (for reference values runs in ≈0:20):

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

def graf(a,b,H,p):
    GM =  39.5216489684
    x_0 = a + np.sqrt(a**2 - b**2)
    v_0 = np.sqrt(GM*(2/x_0 - 1/a))
    konstant_period = np.sqrt(a**3)*H
    h = 1/H

    '''starting position given by an elliptic orbit '''
    stor_x_lista = [x_0]
    stor_y_lista = [0]

    hastighet_x = [0]
    hastighet_y = [v_0]

    liten_x_lista = []
    liten_y_lista = []

    ''' a loop that approximates the points of the orbit'''

    t = 0
    tid_lista = []
    n = 0
    while n < konstant_period:
        hastighet_x.append(hastighet_x[n] - h*GM* stor_x_lista[n]/(np.sqrt(stor_x_lista[n]**2 + stor_y_lista[n]**2))**3)
        stor_x_lista.append(stor_x_lista[n] + h*hastighet_x[n])

        hastighet_y.append(hastighet_y[n] - h*GM*stor_y_lista[n]/(np.sqrt(stor_x_lista[n]**2 + stor_y_lista[n]**2))**3)
        stor_y_lista.append(stor_y_lista[n] + h*hastighet_y[n])

    '''smaller list of points to run faster'''
    if n % p == 0:
            liten_x_lista.append(stor_x_lista[n])
            liten_y_lista.append(stor_y_lista[n])
            tid_lista.append(t)

    n += 1
    t += h
    ''' function that finds the angle'''
    vinkel = []
    siffra = 0
    while siffra < len(liten_x_lista):
        if liten_y_lista[siffra ] >= 0:
            vinkel.append( np.arccos( liten_x_lista[siffra]/np.sqrt( liten_x_lista[siffra]**2 + liten_y_lista[siffra]**2)))
            siffra += 1

        elif liten_y_lista[siffra] < 0 :
            vinkel.append( np.pi + np.arccos( -liten_x_lista[siffra]/np.sqrt( liten_x_lista[siffra]**2 + liten_y_lista[siffra]**2) ))
            siffra += 1

    '''get rid of line to find periodic function'''
    mod_lista = []

    modn = 0
    while modn < len(vinkel):
        mod_lista.append(vinkel[modn] - (2*np.pi*tid_lista[modn])/np.sqrt(a**3))
        modn += 1

    '''make all inputs have period 1'''
    squeeze_tid = []
    squeezen = 0
    while squeezen < len(tid_lista):
        squeeze_tid.append(tid_lista[squeezen]/np.sqrt(a**3))
        squeezen += 1

    del mod_lista[-1:]
    del tid_lista[-1:]
    del squeeze_tid[-1:]

    plt.plot(squeeze_tid,mod_lista)
    plt.title('p(t) där a = ' + str(a) + ' och b = ' + str(b))
    plt.show
</code>```

Second more split up program (for reference values runs in ≈4:20):

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

'''function that generates the points of the orbit'''
def punkt(a,b,H,p):
    GM =  39.5216489684
    x_0 = a + np.sqrt(a**2 - b**2)
    v_0 = np.sqrt(GM*(2/x_0 - 1/a))
    konstant_period = np.sqrt(a**3)*H
    h = 1/H

    '''starting position given by an elliptic orbit '''
    stor_x_lista = [x_0]
    stor_y_lista = [0]

    hastighet_x = [0]
    hastighet_y = [v_0]

    liten_x_lista = []
    liten_y_lista = []

    ''' a loop that approximates the points of the orbit'''
    t = 0
    tid_lista = []
    n = 0
    while n < konstant_period:
        hastighet_x.append(hastighet_x[n] - h*GM* stor_x_lista[n]/(np.sqrt(stor_x_lista[n]**2 + stor_y_lista[n]**2))**3)
        stor_x_lista.append(stor_x_lista[n] + h*hastighet_x[n])

        hastighet_y.append(hastighet_y[n] - h*GM*stor_y_lista[n]/(np.sqrt(stor_x_lista[n]**2 + stor_y_lista[n]**2))**3)
        stor_y_lista.append(stor_y_lista[n] + h*hastighet_y[n])

        '''smaller list of points to run faster'''
        if n % p == 0:
            liten_x_lista.append(stor_x_lista[n])
            liten_y_lista.append(stor_y_lista[n])
            tid_lista.append(t)

        n += 1
        t += h

    return (liten_x_lista,liten_y_lista,tid_lista)

''' function that finds the angle'''

def vinkel(a,b,H,p):
    '''import lists'''
    liten_x_lista = punkt(a,b,H,p)[0]
    liten_y_lista = punkt(a,b,H,p)[1]
    tid_lista = punkt(a,b,H,p)[2]

    '''find the angle'''
    vinkel_lista = []
    siffra = 0
    while siffra < len(liten_x_lista):
        if liten_y_lista[siffra ] >= 0:
            vinkel_lista.append( np.arccos( liten_x_lista[siffra]/np.sqrt( liten_x_lista[siffra]**2 + liten_y_lista[siffra]**2)))
            siffra += 1

        elif liten_y_lista[siffra] < 0 :
            vinkel_lista.append( np.pi + np.arccos( -liten_x_lista[siffra]/np.sqrt( liten_x_lista[siffra]**2 + liten_y_lista[siffra]**2) ))
            siffra += 1
    return (vinkel_lista, tid_lista)

def periodisk(a,b,H,p):
    '''import lists'''
    tid_lista = vinkel(a,b,H,p)[1]
    vinkel_lista = vinkel(a,b,H,p)[0]

    '''get rid of linear line to find p(t)'''
    mod_lista = []

    modn = 0
    while modn < len(vinkel_lista):
        mod_lista.append((vinkel_lista[modn] - (2*np.pi*tid_lista[modn])/np.sqrt(a**3)))
        modn += 1

    '''make all inputs have period 1'''
    squeeze_tid = []
    squeezen = 0
    while squeezen < len(tid_lista):
        squeeze_tid.append(tid_lista[squeezen]/np.sqrt(a**3))
        squeezen += 1

    del mod_lista[-1:]
    del tid_lista[-1:]
    del squeeze_tid[-1:]

    return (squeeze_tid,mod_lista)

'''fixa 3d-punkt av p(a,b) a är konstant b varierar??? '''

def hitta_amp(a):
    x_b = []
    y_b = []
    n_b = 0.1
    while n_b <= a:
        x_b.append(n_b)
        y_b.append(punkt(a,n_b,10**5,10**3))

    return 0

def graf(a,b,H,p):
    plt.plot(periodisk(a,b,H,p)[0],periodisk(a,b,H,p)[1])
    plt.show
</code>```

I would assume the thing that is going wrong is that the program is running the same, slow code multiple times instead of just running it once and then accessing the data. Is the problem that everything is done locally and nothing is stored globally or is it something else?
Just as a heads up, the only thing I know about programming is basic syntax, I have no clue how to actually write and run programs. I ran all the code in spyder if that affects anything.

答:
```<code>plt.plot(periodisk(a,b,H,p)[0],periodisk(a,b,H,p)[1])
</code>```

This code runs periodisk twice with the same arguments, thus at this point we know we run things at least 2 times slower.

You should do some_var = periodisk(a,b,H,p) and then some_var[0], some_var[1]. Or just use unpacking:

```<code>plt.plot(*periodisk(a,b,H,p))
</code>```

```<code>tid_lista = vinkel(a,b,H,p)[1]
vinkel_lista = vinkel(a,b,H,p)[0]
</code>```

Again doing the same thing twice (total: 4*time of (current) vinkel function). Again, smart assignment to fix this:

```<code>vinkel_lista, tid_lista = vinkel(a,b,H,p)
</code>```

```<code>liten_x_lista = punkt(a,b,H,p)[0]
liten_y_lista = punkt(a,b,H,p)[1]
tid_lista = punkt(a,b,H,p)[2]
</code>```

And now you repeat yourself thrice. (total: 12 * time of current punkt function)

```<code>liten_x_lista, liten_y_lista, tid_lista = punkt(a,b,H,p)
</code>```

punkt function is like in original, so we arrived as total being 12 times slower - which quite matches your time estimations. :)

Body:
Im very new to programming, I wrote a simple program for a school project and wanted to make the code "prettier" by not just having the program be one giant function but instead be made up of multiple smaller functions with a singe purpose. I seemed to have messed up royally since the program now runs 13 times slower. How should I structured the program to make it run faster and just in general make programs easier to write, read and edit?

Here are the two programs:

First program (for reference values runs in ≈0:20):

import numpy as np
import matplotlib.pyplot as plt

def graf(a,b,H,p):
    GM =  39.5216489684
    x_0 = a + np.sqrt(a**2 - b**2)
    v_0 = np.sqrt(GM*(2/x_0 - 1/a))
    konstant_period = np.sqrt(a**3)*H
    h = 1/H

    '''starting position given by an elliptic orbit '''
    stor_x_lista = [x_0]
    stor_y_lista = [0]

    hastighet_x = [0]
    hastighet_y = [v_0]

    liten_x_lista = []
    liten_y_lista = []

    ''' a loop that approximates the points of the orbit'''

    t = 0
    tid_lista = []
    n = 0
    while n < konstant_period:
        hastighet_x.append(hastighet_x[n] - h*GM* stor_x_lista[n]/(np.sqrt(stor_x_lista[n]**2 + stor_y_lista[n]**2))**3)
        stor_x_lista.append(stor_x_lista[n] + h*hastighet_x[n])

        hastighet_y.append(hastighet_y[n] - h*GM*stor_y_lista[n]/(np.sqrt(stor_x_lista[n]**2 + stor_y_lista[n]**2))**3)
        stor_y_lista.append(stor_y_lista[n] + h*hastighet_y[n])

    '''smaller list of points to run faster'''
    if n % p == 0:
            liten_x_lista.append(stor_x_lista[n])
            liten_y_lista.append(stor_y_lista[n])
            tid_lista.append(t)

    n += 1
    t += h
    ''' function that finds the angle'''
    vinkel = []
    siffra = 0
    while siffra < len(liten_x_lista):
        if liten_y_lista[siffra ] >= 0:
            vinkel.append( np.arccos( liten_x_lista[siffra]/np.sqrt( liten_x_lista[siffra]**2 + liten_y_lista[siffra]**2)))
            siffra += 1

        elif liten_y_lista[siffra] < 0 :
            vinkel.append( np.pi + np.arccos( -liten_x_lista[siffra]/np.sqrt( liten_x_lista[siffra]**2 + liten_y_lista[siffra]**2) ))
            siffra += 1

    '''get rid of line to find periodic function'''
    mod_lista = []

    modn = 0
    while modn < len(vinkel):
        mod_lista.append(vinkel[modn] - (2*np.pi*tid_lista[modn])/np.sqrt(a**3))
        modn += 1

    '''make all inputs have period 1'''
    squeeze_tid = []
    squeezen = 0
    while squeezen < len(tid_lista):
        squeeze_tid.append(tid_lista[squeezen]/np.sqrt(a**3))
        squeezen += 1

    del mod_lista[-1:]
    del tid_lista[-1:]
    del squeeze_tid[-1:]

    plt.plot(squeeze_tid,mod_lista)
    plt.title('p(t) där a = ' + str(a) + ' och b = ' + str(b))
    plt.show

Second more split up program (for reference values runs in ≈4:20):

import numpy as np
import matplotlib.pyplot as plt

'''function that generates the points of the orbit'''
def punkt(a,b,H,p):
    GM =  39.5216489684
    x_0 = a + np.sqrt(a**2 - b**2)
    v_0 = np.sqrt(GM*(2/x_0 - 1/a))
    konstant_period = np.sqrt(a**3)*H
    h = 1/H

    '''starting position given by an elliptic orbit '''
    stor_x_lista = [x_0]
    stor_y_lista = [0]

    hastighet_x = [0]
    hastighet_y = [v_0]

    liten_x_lista = []
    liten_y_lista = []

    ''' a loop that approximates the points of the orbit'''
    t = 0
    tid_lista = []
    n = 0
    while n < konstant_period:
        hastighet_x.append(hastighet_x[n] - h*GM* stor_x_lista[n]/(np.sqrt(stor_x_lista[n]**2 + stor_y_lista[n]**2))**3)
        stor_x_lista.append(stor_x_lista[n] + h*hastighet_x[n])

        hastighet_y.append(hastighet_y[n] - h*GM*stor_y_lista[n]/(np.sqrt(stor_x_lista[n]**2 + stor_y_lista[n]**2))**3)
        stor_y_lista.append(stor_y_lista[n] + h*hastighet_y[n])

        '''smaller list of points to run faster'''
        if n % p == 0:
            liten_x_lista.append(stor_x_lista[n])
            liten_y_lista.append(stor_y_lista[n])
            tid_lista.append(t)

        n += 1
        t += h

    return (liten_x_lista,liten_y_lista,tid_lista)

''' function that finds the angle'''

def vinkel(a,b,H,p):
    '''import lists'''
    liten_x_lista = punkt(a,b,H,p)[0]
    liten_y_lista = punkt(a,b,H,p)[1]
    tid_lista = punkt(a,b,H,p)[2]

    '''find the angle'''
    vinkel_lista = []
    siffra = 0
    while siffra < len(liten_x_lista):
        if liten_y_lista[siffra ] >= 0:
            vinkel_lista.append( np.arccos( liten_x_lista[siffra]/np.sqrt( liten_x_lista[siffra]**2 + liten_y_lista[siffra]**2)))
            siffra += 1

        elif liten_y_lista[siffra] < 0 :
            vinkel_lista.append( np.pi + np.arccos( -liten_x_lista[siffra]/np.sqrt( liten_x_lista[siffra]**2 + liten_y_lista[siffra]**2) ))
            siffra += 1
    return (vinkel_lista, tid_lista)

def periodisk(a,b,H,p):
    '''import lists'''
    tid_lista = vinkel(a,b,H,p)[1]
    vinkel_lista = vinkel(a,b,H,p)[0]

    '''get rid of linear line to find p(t)'''
    mod_lista = []

    modn = 0
    while modn < len(vinkel_lista):
        mod_lista.append((vinkel_lista[modn] - (2*np.pi*tid_lista[modn])/np.sqrt(a**3)))
        modn += 1

    '''make all inputs have period 1'''
    squeeze_tid = []
    squeezen = 0
    while squeezen < len(tid_lista):
        squeeze_tid.append(tid_lista[squeezen]/np.sqrt(a**3))
        squeezen += 1

    del mod_lista[-1:]
    del tid_lista[-1:]
    del squeeze_tid[-1:]

    return (squeeze_tid,mod_lista)

'''fixa 3d-punkt av p(a,b) a är konstant b varierar??? '''

def hitta_amp(a):
    x_b = []
    y_b = []
    n_b = 0.1
    while n_b <= a:
        x_b.append(n_b)
        y_b.append(punkt(a,n_b,10**5,10**3))

    return 0

def graf(a,b,H,p):
    plt.plot(periodisk(a,b,H,p)[0],periodisk(a,b,H,p)[1])
    plt.show

I would assume the thing that is going wrong is that the program is running the same, slow code multiple times instead of just running it once and then accessing the data. Is the problem that everything is done locally and nothing is stored globally or is it something else?
Just as a heads up, the only thing I know about programming is basic syntax, I have no clue how to actually write and run programs. I ran all the code in spyder if that affects anything.

Body:
plt.plot(periodisk(a,b,H,p)[0],periodisk(a,b,H,p)[1])

This code runs periodisk twice with the same arguments, thus at this point we know we run things at least 2 times slower.

You should do some_var = periodisk(a,b,H,p) and then some_var[0], some_var[1]. Or just use unpacking:

plt.plot(*periodisk(a,b,H,p))

tid_lista = vinkel(a,b,H,p)[1]
vinkel_lista = vinkel(a,b,H,p)[0]

Again doing the same thing twice (total: 4*time of (current) vinkel function). Again, smart assignment to fix this:

vinkel_lista, tid_lista = vinkel(a,b,H,p)

liten_x_lista = punkt(a,b,H,p)[0]
liten_y_lista = punkt(a,b,H,p)[1]
tid_lista = punkt(a,b,H,p)[2]

And now you repeat yourself thrice. (total: 12 * time of current punkt function)

liten_x_lista, liten_y_lista, tid_lista = punkt(a,b,H,p)

punkt function is like in original, so we arrived as total being 12 times slower - which quite matches your time estimations. :)


问:
Python pandas create datafrane from csv embeded within a web txt file
I am trying to import CSV formatted data to Pandas dataframe. The CSV data is located within a .txt file the is located at a web URL. The issue is that I only want to import a part (or parts) of the .txt file that is formatted as CSV (see image below). Essentially I need to skip the first 9 rows and then import rows 10-16 as CSV.

My code

```<code>import csv
import pandas as pd
import io

url = "http://www.bom.gov.au/climate/averages/climatology/windroses/wr15/data/086282-3pmMonth.txt"
df = pd.read_csv(io.StringIO(url), skiprows = 9, sep =',', skipinitialspace = True)
df
</code>```

I get a lengthy error msg that ultimately says  "EmptyDataError: No columns to parse from file"

I have looked at similar examples Read .txt file with Python Pandas - strings and floats but this is different.

答:
The code above attempts to read a CSV file from the URL itself rather than the text file fetched from that URL.  To see what I mean take out the skiprows parameter and then show the data frame.  You'll see this:

```<code>Empty DataFrame
Columns: [http://www.bom.gov.au/climate/averages/climatology/windroses/wr15/data/086282-3pmMonth.txt]
Index: []
</code>```

Note that the columns are the URL itself.

Import requests (you may have to install it first) and then try this:

```<code>content = requests.get(url).content
df = pd.read_csv(io.StringIO(content.decode('utf-8')),skiprows=9)
</code>```

Body:
I am trying to import CSV formatted data to Pandas dataframe. The CSV data is located within a .txt file the is located at a web URL. The issue is that I only want to import a part (or parts) of the .txt file that is formatted as CSV (see image below). Essentially I need to skip the first 9 rows and then import rows 10-16 as CSV.

My code

import csv
import pandas as pd
import io

url = "http://www.bom.gov.au/climate/averages/climatology/windroses/wr15/data/086282-3pmMonth.txt"
df = pd.read_csv(io.StringIO(url), skiprows = 9, sep =',', skipinitialspace = True)
df

I get a lengthy error msg that ultimately says  "EmptyDataError: No columns to parse from file"

I have looked at similar examples Read .txt file with Python Pandas - strings and floats but this is different.

Body:
The code above attempts to read a CSV file from the URL itself rather than the text file fetched from that URL.  To see what I mean take out the skiprows parameter and then show the data frame.  You'll see this:

Empty DataFrame
Columns: [http://www.bom.gov.au/climate/averages/climatology/windroses/wr15/data/086282-3pmMonth.txt]
Index: []

Note that the columns are the URL itself.

Import requests (you may have to install it first) and then try this:

content = requests.get(url).content
df = pd.read_csv(io.StringIO(content.decode('utf-8')),skiprows=9)


答:
You are using array.splice(0, array[mid])

array[mid] is the value in the array and you need the quantity of elements to subtract array.splice(0, mid)  splice docs

also index start from 0 so your array[mid] is taking the 6th element and not the middle.

Title: Javascript Binary Search algorithm unable to find number in the list


问:
SQL row creation and modification time set by database or ORM?
If I want to track the created_at and modified_at timestamp of a mysql row, there are two ways.

Let mysql update the fields:

```<code>@Column(insertable = false, updatable = false,
       columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private LocalDateTime create_at;
</code>```

Or use the orm (hibernate) I'm using with spring-jpa:

```<code>@CreationTimestamp //or even the jpa @CreatedAt
@Temporal(TemporalType.TIMESTAMP)
private Date modification;
</code>```

Question: what is the advantage of one over the other.
Advantage of orm approach is independence of the database type (could be important eg for unit tests). But also the orm has to "intercept" the persist process for it.

With the CURRENT_TIMESTAMP the row is independent of the executing code.

Is there any clear line when to chose which approach?

答:
The main disadvantage of the database approach is that you end with a column definition that is database dependent.

But, there is a subtle diference using the ORM approach, is that you can know the assigned value in the same method/transaction. While with the data base approach you will not know the vaule generated until you do another query.

Body:
If I want to track the created_at and modified_at timestamp of a mysql row, there are two ways.

Let mysql update the fields:

@Column(insertable = false, updatable = false,
       columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private LocalDateTime create_at;

Or use the orm (hibernate) I'm using with spring-jpa:

@CreationTimestamp //or even the jpa @CreatedAt
@Temporal(TemporalType.TIMESTAMP)
private Date modification;

Question: what is the advantage of one over the other.
Advantage of orm approach is independence of the database type (could be important eg for unit tests). But also the orm has to "intercept" the persist process for it.

With the CURRENT_TIMESTAMP the row is independent of the executing code.

Is there any clear line when to chose which approach?


问:
mysql query prints data of different rows in one row
I am using MySQL version 8.0 and popSQL as the editor.

Table:

```<code>create table account (no int, salary int);

insert into account values
(901,25000),
(902,30000),
(903,21000),
(904,40000),
(905,27000);
</code>```

Now, I want no and salary of person with highest salary.
Highest salary is 40000 and corresponding no is 904.
But, this query is giving me different output.

```<code>-- no and salary of max salary
select no, max(salary)
from account ;
</code>```

The output is:
no  max(salary)
901 40000

It is printing the first no and the max salary.
i.e. data of different rows are shown in a same row.
How to fix this???

Same type of problem for my next query.

```<code>-- no and salary of second highest salary.
select no, max(salary)
from account
where salary not in
(select max(salary) from account);
</code>```

The output is:
no  max(salary)
901 30000

Whereas expected is 902,30000.

I searched through the stack overflow for issue where data of different rows are shown in one but didn't get any help.

Thanking you in advance.

答:
I want no and salary of person with highest salary

You don't need aggregation for this. You can just order by and limit:

```<code>select no, salary
from account
order by salary desc
limit 1
</code>```

Body:
I am using MySQL version 8.0 and popSQL as the editor.

Table:

create table account (no int, salary int);

insert into account values
(901,25000),
(902,30000),
(903,21000),
(904,40000),
(905,27000);

Now, I want no and salary of person with highest salary.
Highest salary is 40000 and corresponding no is 904.
But, this query is giving me different output.

-- no and salary of max salary
select no, max(salary)
from account ;

The output is:
no  max(salary)
901 40000

It is printing the first no and the max salary.
i.e. data of different rows are shown in a same row.
How to fix this???

Same type of problem for my next query.

-- no and salary of second highest salary.
select no, max(salary)
from account
where salary not in
(select max(salary) from account);

The output is:
no  max(salary)
901 30000

Whereas expected is 902,30000.

I searched through the stack overflow for issue where data of different rows are shown in one but didn't get any help.

Thanking you in advance.

Body:
I want no and salary of person with highest salary

You don't need aggregation for this. You can just order by and limit:

select no, salary
from account
order by salary desc
limit 1


问:
Run R Shiny app on SharePoint
I am wondering if and how I can run a shiny app on the SharePoint of my company.
I tried to work with a flexdashboard following this post.
I managed to make this work with a simple app but not with my own app.

My app does not have static data, but retrieves data via API's, which I guessed was the reason a flexdashboard won't work (correct me if I'm wrong).

I have no experience in publishing/deploying shiny apps other than on shinyapps.io. In this case this will not be an option since the data is sensitive.

What are the options for me to make the app run on SharePoint?

Many thanks in advance.

答:
For my own use, I've set up multiple pages that simply redirect through a SharePoint page (aspx) using javascript. It's not hosted directly on SP this way, but the effect is nearly the same to end users.

NB: This also does not truly prevent unauthorized access to the server, should an unauthorized user learn the IP address of the server. The SP front-end access restrictions only work for this redirection interface.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ Page Language="C#" %>
<%@ Register tagprefix="SharePoint" namespace="Microsoft.SharePoint.WebControls" assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
  <head runat="server">
    <title>Shiny Redirecting... Please wait.</title>
    <meta http-equiv="X-UA-Compatible" content="IE=10" />
    <SharePoint:CssRegistration Name="default" runat="server"/>
  </head>
  <body bgcolor="#B3B3B3">
    <script>
      window.location = "<IP:PORT>";
    </script>
  </body>
</html>
</code>```

Title: Run R Shiny app on SharePoint

Body:
For my own use, I've set up multiple pages that simply redirect through a SharePoint page (aspx) using javascript. It's not hosted directly on SP this way, but the effect is nearly the same to end users.

NB: This also does not truly prevent unauthorized access to the server, should an unauthorized user learn the IP address of the server. The SP front-end access restrictions only work for this redirection interface.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ Page Language="C#" %>
<%@ Register tagprefix="SharePoint" namespace="Microsoft.SharePoint.WebControls" assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
  <head runat="server">
    <title>Shiny Redirecting... Please wait.</title>
    <meta http-equiv="X-UA-Compatible" content="IE=10" />
    <SharePoint:CssRegistration Name="default" runat="server"/>
  </head>
  <body bgcolor="#B3B3B3">
    <script>
      window.location = "<IP:PORT>";
    </script>
  </body>
</html>


问:
How to generate a @CreatedDate LocalDateTime as Timestamp?
I'm using spring-jpa to persist a LocalDateTime created_at with @CreatedDate.

```<code>@CreatedDate
private LocalDateTime created_at;
</code>```

Problem: this auto-generates a column with datetime(6) mysql column type.

Question: how can I change this to TIMESTAMP type? I tried @Temporal(TIMESTAMP) but which is not allowed on LocalDateTime.

Is it possible at all?

答:
I could get it working with any of the following solutions:

```<code>    //spring way, with @EnableJpaAuditing on configuration
    @EntityListeners(AuditingEntityListener.class)
    class MyEntity {
        @CreatedDate
        @Column(columnDefinition = "TIMESTAMP", nullable = false)
        private LocalDateTime created_at;
    }

    //hibernate way
    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    private Date created_at;

    //mysql way
    @Column(insertable = false, updatable = false,
            columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
    private LocalDateTime created_at;
</code>```

For the mysql the important part is: insertable=false for mysql using the defined DEFAULT CURRENT_TIMESTAMP, and updatable=false for ON UPDATE CURRENT_TIMESTAMP.

Otherwise, the hibernate orm would send created_at=null as null value to the database, preventing the column definition to take over! Or worse, if you set nullable=false, the insert would fail although you defined the default timestamp handling for the column.

Body:
I'm using spring-jpa to persist a LocalDateTime created_at with @CreatedDate.

@CreatedDate
private LocalDateTime created_at;

Problem: this auto-generates a column with datetime(6) mysql column type.

Question: how can I change this to TIMESTAMP type? I tried @Temporal(TIMESTAMP) but which is not allowed on LocalDateTime.

Is it possible at all?

Body:
I could get it working with any of the following solutions:

    //spring way, with @EnableJpaAuditing on configuration
    @EntityListeners(AuditingEntityListener.class)
    class MyEntity {
        @CreatedDate
        @Column(columnDefinition = "TIMESTAMP", nullable = false)
        private LocalDateTime created_at;
    }

    //hibernate way
    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    private Date created_at;

    //mysql way
    @Column(insertable = false, updatable = false,
            columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
    private LocalDateTime created_at;

For the mysql the important part is: insertable=false for mysql using the defined DEFAULT CURRENT_TIMESTAMP, and updatable=false for ON UPDATE CURRENT_TIMESTAMP.

Otherwise, the hibernate orm would send created_at=null as null value to the database, preventing the column definition to take over! Or worse, if you set nullable=false, the insert would fail although you defined the default timestamp handling for the column.


问:
Is it forbidden to use static methods in factory pattern?
I got told that using static methods when implementing the factory-method-pattern is wrong and should be avoided. Because I wasn't really familiar with the pattern I accepted that answer.

After reading articles and getting deeper into it, I couldn't find any source which supports this statement.

Can someone help me out with this situation. Should I avoid the static-keyword in factory-methods and if so, when are they useful?

答:
Sometimes the implementation class doesn't matter, because the interface specifies all of the relevant behavior. In these cases, callers don't care how it's implemented, and a static factory method is OK.  Collections.emptyList() or singletonSet(item), for example, are fine.

Sometimes, though, it is not necessarily true that the same implementation will suffice for  all callers.  This is the usual case, even if special implementations are only needed for tests or staging environments.  In these cases the proper functioning of the callers depends on the implementation choice, and a static factory method is a violation of the dependency inversion principle.

If the same implementation isn't necessarily acceptable for all uses, then you should inject a non-static factory so that the callers aren't coupled to the particular implementation choice.


问:
How to end a program using blank line in python?
```<code>fee = []

age = int(input("Enter age: "))

while age != '':

    age = int(input("Enter age: "))

    if age <= 5:
        fee.append(0)
    elif age >= 6 and age <= 64:
        fee.append(50.00)
    else:
        fee.append(25.00)

total = sum(fee)
print("Total payment: ", total)
</code>```

I want to make a program that would sum up the given entrance fees. I don't even know if I'm doing it correctly

答:
```<code>fee = 0

age = int(input("Enter age: "))

while age != '':
    try:
        age = int(input("Enter age: "))  // to avoid exception of string
    except:
        break
    if age <= 5:
        fee += 0  // no need to append if outcome is a number
    elif age >= 6 and age <= 64:
        fee += 50
    else:
        fee += 25

total = fee
print("Total payment: ", total)
</code>```

Body:
fee = []

age = int(input("Enter age: "))

while age != '':

    age = int(input("Enter age: "))

    if age <= 5:
        fee.append(0)
    elif age >= 6 and age <= 64:
        fee.append(50.00)
    else:
        fee.append(25.00)

total = sum(fee)
print("Total payment: ", total)

I want to make a program that would sum up the given entrance fees. I don't even know if I'm doing it correctly


问:
Bokeh labelling a slope with legend
I am doing a simple 1D linear regression model and am plotting my line of best fit as a slope using Bokeh. The problem is that I want to display two lines of best fit, one from SKLearn and the other from my own gradient descent code. I want to display these lines with a legend but can't seem to figure out how to label a Slope in Bokeh.

I want to keep using the Slope annotation feature as it extends beyond the extent of the data.

Any help would be greatly appreciated.

```<code># Here x is my x-data and y is my y-data

theta_GD = np.array([[-3.63029144],[ 1.16636235]]) # my fitting gradient descent parameters
theta_SK = np.array([[1.19303364],[-3.8957808783]]) # fitting parameters from SKLearn

fig = figure()

gradient_GD = theta_GD[1]
y_intercept_GD = theta_GD[0]

gradient_SK = theta_SK[1]
y_intercept_SK = theta_SK[0]

slope1 = Slope(gradient=gradient_GD, y_intercept=y_intercept_GD, line_color='red', line_width=2)
slope2 = Slope(gradient=gradient_SK, y_intercept=y_intercept_SK, line_color='blue', line_width=2)

fig.scatter(x,y)
fig.add_layout(slope1)
fig.add_layout(slope2)
show(fig)
</code>```

答:
I'd recommend that you draw your fitted lines as Line glyphs instead of  Slope annotations. For example:

```<code>m, b= 3,1
m1, b1 = 3.2, .8
x = np.linspace(-10,10,100)
data = m*x + b + np.random.normal(0,3,size=len(x))
y = m*x + b
y1 = m1*x+b1
fig = figure()
fig.line(x,y,legend_label='My Regression',color='green',line_width=2)
fig.line(x,y1,legend_label="Other Algorithm",color='red',line_width=2)
fig.scatter(x,data)
show(fig)
</code>```

which yields:

Title: Bokeh labelling a slope with legend

Body:
I am doing a simple 1D linear regression model and am plotting my line of best fit as a slope using Bokeh. The problem is that I want to display two lines of best fit, one from SKLearn and the other from my own gradient descent code. I want to display these lines with a legend but can't seem to figure out how to label a Slope in Bokeh.

I want to keep using the Slope annotation feature as it extends beyond the extent of the data.

Any help would be greatly appreciated.

# Here x is my x-data and y is my y-data

theta_GD = np.array([[-3.63029144],[ 1.16636235]]) # my fitting gradient descent parameters
theta_SK = np.array([[1.19303364],[-3.8957808783]]) # fitting parameters from SKLearn

fig = figure()

gradient_GD = theta_GD[1]
y_intercept_GD = theta_GD[0]

gradient_SK = theta_SK[1]
y_intercept_SK = theta_SK[0]

slope1 = Slope(gradient=gradient_GD, y_intercept=y_intercept_GD, line_color='red', line_width=2)
slope2 = Slope(gradient=gradient_SK, y_intercept=y_intercept_SK, line_color='blue', line_width=2)

fig.scatter(x,y)
fig.add_layout(slope1)
fig.add_layout(slope2)
show(fig)

Body:
I'd recommend that you draw your fitted lines as Line glyphs instead of  Slope annotations. For example:

m, b= 3,1
m1, b1 = 3.2, .8
x = np.linspace(-10,10,100)
data = m*x + b + np.random.normal(0,3,size=len(x))
y = m*x + b
y1 = m1*x+b1
fig = figure()
fig.line(x,y,legend_label='My Regression',color='green',line_width=2)
fig.line(x,y1,legend_label="Other Algorithm",color='red',line_width=2)
fig.scatter(x,data)
show(fig)

which yields:


答:
You can't compare a string to an integer, that's your main problem. If you retrieve it from the user as a string and check it is indeed an integer or not will work. That code should do the trick:</p>

```<code>def RepresentsInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

fee = []

r='start'

while r != '':

    r = input("Enter age: ")
    if RepresentsInt(r):
        age = int(r)
        if age <= 5:
            fee.append(0)
        elif age >= 6 and age <= 64:
            fee.append(50.00)
        else:
            fee.append(25.00)

total = sum(fee)
print("Total payment: ", total)
</code>```

Title: How to end a program using blank line in python?

Body:
You can't compare a string to an integer, that's your main problem. If you retrieve it from the user as a string and check it is indeed an integer or not will work. That code should do the trick:

def RepresentsInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

fee = []

r='start'

while r != '':

    r = input("Enter age: ")
    if RepresentsInt(r):
        age = int(r)
        if age <= 5:
            fee.append(0)
        elif age >= 6 and age <= 64:
            fee.append(50.00)
        else:
            fee.append(25.00)

total = sum(fee)
print("Total payment: ", total)


问:
How to add edges with a list as label in Networkx Python
I have this example:

```<code>G.add_nodes_from(List1)
G.add_nodes_from(List2)
edgeList = list(zip(List1, List2))
for item in List3:
    G.add_edges_from(edgeList, label = item)
</code>```

What I want as outcome is each edge between the two lists to have as a label the corresponding  element of the list3. Something like this:

(List1[0], List2[0], {'label': List3[0]})

答:
Note: I have change the variable name from List1 to source_nodes, List2 to dest_nodes and List3 to data_nodes in the following code.

You can try to use zip over all three lists and add the edges using nx.add_edge. Something like this:

```<code>import networkx as nx

source_nodes = ['A', 'B', 'C', 'D']
dest_nodes = ['P', 'Q', 'R', 'S']
data_nodes = ['W', 'X', 'Y', 'Z']

G = nx.DiGraph()

# Each element of this zip will be
# (source[i], dest[i], data[i])
for u,v,d in zip(source_nodes, dest_nodes, data_nodes):
    G.add_edge(u, v, label=d)

print(G.edges(data=True))
# OutEdgeDataView([('A', 'P', {'label': 'W'}),
#                  ('B', 'Q', {'label': 'X'}),
#                  ('C', 'R', {'label': 'Y'}),
#                  ('D', 'S', {'label': 'Z'})])
</code>```

You can also view the code in this Google Colab Notebook for more info.

Body:
I have this example:

G.add_nodes_from(List1)
G.add_nodes_from(List2)
edgeList = list(zip(List1, List2))
for item in List3:
    G.add_edges_from(edgeList, label = item)

What I want as outcome is each edge between the two lists to have as a label the corresponding  element of the list3. Something like this:

(List1[0], List2[0], {'label': List3[0]})

Body:
Note: I have change the variable name from List1 to source_nodes, List2 to dest_nodes and List3 to data_nodes in the following code.

You can try to use zip over all three lists and add the edges using nx.add_edge. Something like this:

import networkx as nx

source_nodes = ['A', 'B', 'C', 'D']
dest_nodes = ['P', 'Q', 'R', 'S']
data_nodes = ['W', 'X', 'Y', 'Z']

G = nx.DiGraph()

# Each element of this zip will be
# (source[i], dest[i], data[i])
for u,v,d in zip(source_nodes, dest_nodes, data_nodes):
    G.add_edge(u, v, label=d)

print(G.edges(data=True))
# OutEdgeDataView([('A', 'P', {'label': 'W'}),
#                  ('B', 'Q', {'label': 'X'}),
#                  ('C', 'R', {'label': 'Y'}),
#                  ('D', 'S', {'label': 'Z'})])

You can also view the code in this Google Colab Notebook for more info.


问:
How do I get the file system id for aws-cdk EFS?
```<code>const fileSystem = new efs.CfnFileSystem(this, 'EFS', {}); //This creates the file system
new cdk.CfnOutput(this, 'FileSystemID', { value: fileSystem.???? });
</code>```

I need the filesystemid to pass as an environment variable to other resources

答:
```<code>const fileSystem = new efs.CfnFileSystem(this, 'EFS', {

    });

    const mount = new efs.CfnMountTarget(this, 'MountTarget', {

      fileSystemId: fileSystem.ref,
      securityGroups: [vpc.vpcDefaultSecurityGroup],
      subnetId: vpc.publicSubnets[0].subnetId,

    });

    new cdk.CfnOutput(this, 'FileSystemId', { value: mount.fileSystemId });
</code>```

Body:
const fileSystem = new efs.CfnFileSystem(this, 'EFS', {}); //This creates the file system
new cdk.CfnOutput(this, 'FileSystemID', { value: fileSystem.???? });

I need the filesystemid to pass as an environment variable to other resources


问:
Get request to a .html file is not handled by express
```<code>const express = require('express');
const app = express();
const port = 3000;
const bodyPar=require('body-parser');
const session = require('express-session');
const path=require('path');
var user=["Jared","Bill","Jason","Jeremy"];

app.use(express.static('proiect'));
app.use(bodyPar.urlencoded({extended : true}));
app.use(bodyPar.json());
app.use(session({secret:'secret',saveUninitialized:true,resave:true}));
var sess;
var s;

app.post('/login',function(req,res){
    var i=0;
    sess=req.session;

    var username=req.body.username;
    var pass=req.body.password;
    var but=req.body.value;
    s=0;
    sess.email=username;

    for(i=0;i<3;i++)
    {
        if(username==user[i])
        {
            s=s+1;
            i=5;
        }
    }
    if(pass="123")
        s=s+1;
    if(s==2)
        res.redirect('homepage.html');
    else
        res.redirect('login-error.html');

    res.end();
});

app.get('/homepage.html',function(req,res){

        console.log('aaa');

});
app.get('bios.html',function(req,res){

        console.log('aaa');

});
app.post('/guest',function(req,res){
    sess=req.session;
    sess.username="Guest";
    s=2;
    res.redirect('homepage.html');
});
app.get('/logout',function(req,res){
    req.session.destroy(function(){
       res.redirect('login.html');
       s=0;
    });

});
app.listen(port, () => console.log(`listening on port ${port}!`));
</code>```

The server doesnt handle the app.get('homepage.html') or 'bios.html' it just displays the html file in the browser.(should hang and display smth on console).

Am i supposed to serve/render those files instead of directly accessing them in the browser?
Both of those files are in the /proiect/ folder i've included on the server.

答:
Express finds the static HTML file and then returns that to the user. Therefore it skips the route handler you wrote.

If you are trying to perform some server-side logic and returning an HTML page, rather return the page inside your route handler to avoid such side effects. In this case, create your HTML file in a templates folder or something. Then you can put all your static resources in your static folder. So your structure would look something like this:

```<code>+ project_folder
   + static
      + css
         - style.css
      + js
         - app.js
   + templates
      - bios.html
      - homepage.html
      - login.html
      - login-error.html
   - app.js
</code>```

Then your app.js would look something like this:

const express = require('express');
const app = express();
const port = 3000;
const bodyPar=require('body-parser');
const session = require('express-session');
const path=require('path');
var user=["Jared","Bill","Jason","Jeremy"];

app.use(express.static('static'));
app.use(bodyPar.urlencoded({extended : true}));
app.use(bodyPar.json());
app.use(session({secret:'secret',saveUninitialized:true,resave:true}));
var sess;
var s;

app.get('/login', function(req, res) {
    res.sendFile(path.join(__dirname, '/templates/login.html'));
});

app.post('/login',function(req,res){
    var i=0;
    sess=req.session;

    var username=req.body.username;
    var pass=req.body.password;
    var but=req.body.value;
    s=0;
    sess.email=username;

    for(i=0;i<3;i++)
    {
        if(username==user[i])
        {
            s=s+1;
            i=5;
        }
    }
    if(pass="123")
        s=s+1;
    if(s==2)
        res.redirect('homepage');
    else
        res.redirect('login-error');

    res.end();
});

app.get('/homepage',function(req,res){
    res.sendFile(path.join(__dirname, '/templates/homepage.html'));
});

app.get('bios',function(req,res){
    res.sendFile(path.join(__dirname, '/templates/bios.html'));
});

app.get('login-error', function(req, res) {
    res.sendFile(path.join(__dirname, '/templates/login-error.html'));
});

app.post('/guest',function(req,res){
    sess=req.session;
    sess.username="Guest";
    s=2;
    res.redirect('homepage');
});

app.get('/logout',function(req,res){
    req.session.destroy(function(){
       res.redirect('login');
       s=0;
    });

});
app.listen(port, () => console.log(`listening on port ${port}!`));
```

Body:
const express = require('express');
const app = express();
const port = 3000;
const bodyPar=require('body-parser');
const session = require('express-session');
const path=require('path');
var user=["Jared","Bill","Jason","Jeremy"];

app.use(express.static('proiect'));
app.use(bodyPar.urlencoded({extended : true}));
app.use(bodyPar.json());
app.use(session({secret:'secret',saveUninitialized:true,resave:true}));
var sess;
var s;

app.post('/login',function(req,res){
    var i=0;
    sess=req.session;

    var username=req.body.username;
    var pass=req.body.password;
    var but=req.body.value;
    s=0;
    sess.email=username;

    for(i=0;i<3;i++)
    {
        if(username==user[i])
        {
            s=s+1;
            i=5;
        }
    }
    if(pass="123")
        s=s+1;
    if(s==2)
        res.redirect('homepage.html');
    else
        res.redirect('login-error.html');

    res.end();
});

app.get('/homepage.html',function(req,res){

        console.log('aaa');

});
app.get('bios.html',function(req,res){

        console.log('aaa');

});
app.post('/guest',function(req,res){
    sess=req.session;
    sess.username="Guest";
    s=2;
    res.redirect('homepage.html');
});
app.get('/logout',function(req,res){
    req.session.destroy(function(){
       res.redirect('login.html');
       s=0;
    });

});
app.listen(port, () => console.log(`listening on port ${port}!`));

The server doesnt handle the app.get('homepage.html') or 'bios.html' it just displays the html file in the browser.(should hang and display smth on console).

Am i supposed to serve/render those files instead of directly accessing them in the browser?
Both of those files are in the /proiect/ folder i've included on the server.

Body:
Express finds the static HTML file and then returns that to the user. Therefore it skips the route handler you wrote.

If you are trying to perform some server-side logic and returning an HTML page, rather return the page inside your route handler to avoid such side effects. In this case, create your HTML file in a templates folder or something. Then you can put all your static resources in your static folder. So your structure would look something like this:

+ project_folder
   + static
      + css
         - style.css
      + js
         - app.js
   + templates
      - bios.html
      - homepage.html
      - login.html
      - login-error.html
   - app.js

Then your app.js would look something like this:

const express = require('express');
const app = express();
const port = 3000;
const bodyPar=require('body-parser');
const session = require('express-session');
const path=require('path');
var user=["Jared","Bill","Jason","Jeremy"];

app.use(express.static('static'));
app.use(bodyPar.urlencoded({extended : true}));
app.use(bodyPar.json());
app.use(session({secret:'secret',saveUninitialized:true,resave:true}));
var sess;
var s;

app.get('/login', function(req, res) {
    res.sendFile(path.join(__dirname, '/templates/login.html'));
});

app.post('/login',function(req,res){
    var i=0;
    sess=req.session;

    var username=req.body.username;
    var pass=req.body.password;
    var but=req.body.value;
    s=0;
    sess.email=username;

    for(i=0;i<3;i++)
    {
        if(username==user[i])
        {
            s=s+1;
            i=5;
        }
    }
    if(pass="123")
        s=s+1;
    if(s==2)
        res.redirect('homepage');
    else
        res.redirect('login-error');

    res.end();
});

app.get('/homepage',function(req,res){
    res.sendFile(path.join(__dirname, '/templates/homepage.html'));
});

app.get('bios',function(req,res){
    res.sendFile(path.join(__dirname, '/templates/bios.html'));
});

app.get('login-error', function(req, res) {
    res.sendFile(path.join(__dirname, '/templates/login-error.html'));
});

app.post('/guest',function(req,res){
    sess=req.session;
    sess.username="Guest";
    s=2;
    res.redirect('homepage');
});

app.get('/logout',function(req,res){
    req.session.destroy(function(){
       res.redirect('login');
       s=0;
    });

});
app.listen(port, () => console.log(`listening on port ${port}!`));


问:
How can I implement a 'random mine placer' in PHP
For a project im making a minesweeper game. So im looking to implement a random mine placer in my PHP code. I made a dynamic table using the following code:

```<code><?php

$rows = 6; //  amount of rows
$cols = 6;  //  amount of columns

echo "<table border='1'>";

for($tr=1;$tr<=$rows;$tr++){

    echo "<tr>";
    for($td=1;$td<=$cols;$td++){
        echo "<td></td>";
    }
    echo "</tr>";
}

echo "</table>";

?>
</code>```

Now the thing is that I need to be able to let the mines spawn in a random cell every time I would restart the game. Anyone that could help me out?

答:
To spawn one new bomb, generate a random row and column and check for it:</p>

```<code>$rows = 6;  //  amount of rows
$cols = 6;  //  amount of columns
$rand_row = rand(1, 6);  // random row
$rand_col = rand(1, 6);  // random column

echo "<table border='1'>";

for($tr=1;$tr<=$rows;$tr++){
    echo "<tr>";

    for($td=1;$td<=$cols;$td++){
        echo "<td>";

        if($tr == $rand_row && $td == $rand_col) { // check for row and column
            echo "***BOMB***";
        }
        echo "</td>";
    }
    echo "</tr>";
}
echo "</table>";
</code>```

Body:
For a project im making a minesweeper game. So im looking to implement a random mine placer in my PHP code. I made a dynamic table using the following code:

<?php

$rows = 6; //  amount of rows
$cols = 6;  //  amount of columns

echo "
";

for($tr=1;$tr<=$rows;$tr++){

    echo "
";
    for($td=1;$td<=$cols;$td++){
        echo "	";
    }
    echo "
";
}

echo "
";

?>

Now the thing is that I need to be able to let the mines spawn in a random cell every time I would restart the game. Anyone that could help me out?

Body:
To spawn one new bomb, generate a random row and column and check for it:

$rows = 6;  //  amount of rows
$cols = 6;  //  amount of columns
$rand_row = rand(1, 6);  // random row
$rand_col = rand(1, 6);  // random column

echo "<table border='1'>";

for($tr=1;$tr<=$rows;$tr++){
    echo "<tr>";

    for($td=1;$td<=$cols;$td++){
        echo "<td>";

        if($tr == $rand_row && $td == $rand_col) { // check for row and column
            echo "***BOMB***";
        }
        echo "</td>";
    }
    echo "</tr>";
}
echo "</table>";


问:
UILabel not resizing after scaling font using minimumScaleFactor
I have a UILabel inside a UITableViewCell that I want to dynamically adjust its font and size based on content to always maintain the largest font that it can support without truncating. I am most of the way there using adjustsFontSizeToFitWidth, but the label has extra vertical space that it does not need.

In this screenshot running on the iPhone SE simulator, the label correctly scaled the font down from 55 to fit, but there is this extra space at the top of the label. I want that space to go away!

Here is my label code:

```<code>private lazy var label: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 55, weight: .ultraLight)
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.25
        label.backgroundColor = .purple
        return label
    }()
</code>```

Here is my layout code:

```<code>self.addSubview(self.labelsContainerView)
self.labelsContainerView.snp.makeConstraints { (make) in
    make.leading.equalTo(leftView.snp.trailing).offset(20)
    make.trailing.equalTo(rightView.snp.leading).offset(-20)
    make.top.bottom.equalToSuperview()
}

self.labelsContainerView.addSubview(self.middleLabel)
self.middleLabel.snp.makeConstraints { (make) in
    make.leading.trailing.centerY.equalToSuperview()
}

self.labelsContainerView.addSubview(self.topLabel)
self.topLabel.snp.makeConstraints { (make) in
    make.leading.equalToSuperview()
    make.bottom.equalTo(self.middleLabel.snp.top)
    make.top.equalToSuperview().offset(8)
}

self.labelsContainerView.addSubview(self.bottomLabel)
self.bottomLabel.snp.makeConstraints { (make) in
    make.leading.equalToSuperview()
    make.top.equalTo(self.middleLabel.snp.bottom)
    make.bottom.equalToSuperview().offset(-8)
}
</code>```

In short, I have a UIView pinned to the top and bottom of my UITableViewCell. Inside that view, I have 3 labels: top, middle, and bottom. The labels are pinned top-to-bottom.

I want middleLabel to always be the largest size it can be to satisfy layout and use the largest font that will fit inside that size without truncating. It seems almost like the intrinsic content size isn't being updated when the label's font changes. I have tried all kinds of calls to setNeedsLayout() and layoutIfNeeded() but they never helped.

答:
It will take some extra work to get the label's Height to change, but if you only need the text vertically centered, add this to your label configuration:

```<code>label.baselineAdjustment = .alignCenters
</code>```

Here's the difference... top uses default .alignBaselines bottom uses .alignCenters:

Body:
I have a UILabel inside a UITableViewCell that I want to dynamically adjust its font and size based on content to always maintain the largest font that it can support without truncating. I am most of the way there using adjustsFontSizeToFitWidth, but the label has extra vertical space that it does not need.

In this screenshot running on the iPhone SE simulator, the label correctly scaled the font down from 55 to fit, but there is this extra space at the top of the label. I want that space to go away!

Here is my label code:

private lazy var label: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 55, weight: .ultraLight)
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.25
        label.backgroundColor = .purple
        return label
    }()

Here is my layout code:

self.addSubview(self.labelsContainerView)
self.labelsContainerView.snp.makeConstraints { (make) in
    make.leading.equalTo(leftView.snp.trailing).offset(20)
    make.trailing.equalTo(rightView.snp.leading).offset(-20)
    make.top.bottom.equalToSuperview()
}

self.labelsContainerView.addSubview(self.middleLabel)
self.middleLabel.snp.makeConstraints { (make) in
    make.leading.trailing.centerY.equalToSuperview()
}

self.labelsContainerView.addSubview(self.topLabel)
self.topLabel.snp.makeConstraints { (make) in
    make.leading.equalToSuperview()
    make.bottom.equalTo(self.middleLabel.snp.top)
    make.top.equalToSuperview().offset(8)
}

self.labelsContainerView.addSubview(self.bottomLabel)
self.bottomLabel.snp.makeConstraints { (make) in
    make.leading.equalToSuperview()
    make.top.equalTo(self.middleLabel.snp.bottom)
    make.bottom.equalToSuperview().offset(-8)
}

In short, I have a UIView pinned to the top and bottom of my UITableViewCell. Inside that view, I have 3 labels: top, middle, and bottom. The labels are pinned top-to-bottom.

I want middleLabel to always be the largest size it can be to satisfy layout and use the largest font that will fit inside that size without truncating. It seems almost like the intrinsic content size isn't being updated when the label's font changes. I have tried all kinds of calls to setNeedsLayout() and layoutIfNeeded() but they never helped.

Body:
It will take some extra work to get the label's Height to change, but if you only need the text vertically centered, add this to your label configuration:

label.baselineAdjustment = .alignCenters

Here's the difference... top uses default .alignBaselines bottom uses .alignCenters: