问:
Getting A new session could not be created
Can anyone help me out I am new to Android testing with Appium , I am trying to open app in AVD the app getting installed but then m getting Error "A new Session could not be created.(Original error: Command failed: )","killed":false,"code":1,"signal":null,"origValue":"Command failed: "},"sessionId":null}

Thanks for the help in advance

tried with just giving capabilities.setCapability("appActivity", ".MainActivity");

```<code>'''

File classpathRoot = new File(System.getProperty("user.dir"));
        File appDir = new File(classpathRoot, "/Apps/src/");
        File app = new File(appDir, "ChatApp-release.apk");

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
        capabilities.setCapability("deviceName", "emulator-5554");
        capabilities.setCapability("platformVersion", "7.1.1");
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("app", app.getAbsolutePath());
        capabilities.setCapability("appPackage", "com.aaa.charla");
        capabilities.setCapability("appActivity", "com.aaa.xxx.MainActivity");

        driver = new AndroidDriver(new URL("https://127.0.0.1:4723/wd/hub"), capabilities);
        driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
        Thread.sleep(10000);
        driver.quit();
</code>```

Following are the Debug log:

info: Console LogLevel: debug
  info: --> POST /wd/hub/session {"desiredCapabilities":{"app":"D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk","appPackage":"com.odysseyinc.charla","appActivity":"com.odyssey.chatapp.MainActivity","newCommandTimeout":"10000","platformName":"Android","version":"7.1.1","deviceName":"emulator-5554"}}
  info: Client User-Agent string: Apache-HttpClient/4.5.2 (Java/1.8.0_162)
  info: [debug] The following desired capabilities were provided, but not recognized by appium. They will be passed on to any other services running on this server. : version
  info: [debug] Using local app from desired caps: D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk
  info: [debug] Creating new appium session 0d25aeac-d055-449f-af84-b6d314d9b4a5
  info: Starting android appium
  info: [debug] Getting Java version
  info: Java version is: 1.8.0_162
  info: [debug] Checking whether adb is present
  info: [debug] Using adb from C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe
  info: [debug] Set chromedriver binary as: C:\Program Files (x86)\Appium\node_modules\appium\build\chromedriver\windows\chromedriver.exe
  info: [debug] Using fast reset? true
  info: [debug] Preparing device for session
  info: [debug] Checking whether app is actually present
  info: Retrieving device
  info: [debug] Trying to find a connected android device
  info: [debug] Getting connected devices...
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe devices
  info: [debug] 1 device(s) connected
  info: Found device emulator-5554
  info: [debug] Setting device id to emulator-5554
  info: [debug] Waiting for device to be ready and to respond to shell commands (timeout = 5)
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 wait-for-device
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "echo 'ready'"
  info: [debug] Starting logcat capture
  info: [debug] Getting device API level
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop ro.build.version.sdk"
  info: [debug] Device is at API Level 25
  info: Device API level is: 25
  info: [debug] Extracting strings for language: default
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop persist.sys.language"
  info: [debug] Current device persist.sys.language:
  info: [debug] java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\appium_apk_tools.jar" "stringsFromApk" "D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk" "C:\Users\UNMESH~1.GHA\AppData\Local\Temp\com.odysseyinc.charla"
  info: [debug] Reading strings from converted strings.json
  info: [debug] Setting language to default
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 push "C:\Users\UNMESH~1.GHA\AppData\Local\Temp\com.odysseyinc.charla\strings.json" /data/local/tmp
  info: [debug] Checking whether aapt is present
  info: [debug] Using aapt from C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\aapt.exe
  info: [debug] Retrieving process from manifest.
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\aapt.exe dump xmltree D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk AndroidManifest.xml
  info: [debug] Set app process to: com.odysseyinc.charla
  info: [debug] Not uninstalling app since server not started with --full-reset
  info: [debug] Checking app cert for D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk.
  info: [debug] executing cmd: java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\verify.jar" D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk
  info: [debug] App already signed.
  info: [debug] Zip-aligning D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk
  info: [debug] Checking whether zipalign is present
  info: [debug] Using zipalign from C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\zipalign.exe
  info: [debug] Zip-aligning apk.
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\zipalign.exe -f 4 D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk C:\Users\UNMESH~1.GHA\AppData\Local\Temp\119427-15556-1rmbgw9\appium.tmp
  info: [debug] MD5 for app is f3d7efc8b197792c3d0529a48dc92ff2
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "ls /data/local/tmp/f3d7efc8b197792c3d0529a48dc92ff2.apk"
  info: [debug] Getting install status for com.odysseyinc.charla
  info: [debug] Getting device API level
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop ro.build.version.sdk"
  info: [debug] Device is at API Level 25
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "pm list packages -3 com.odysseyinc.charla"
  info: [debug] App is installed
  info: App is already installed, resetting app
  info: [debug] Running fast reset (stop and clear)
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "am force-stop com.odysseyinc.charla"
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "pm clear com.odysseyinc.charla"
  info: [debug] Forwarding system:4724 to device:4724
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 forward tcp:4724 tcp:4724
  info: [debug] Pushing appium bootstrap to device...
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 push "C:\Program Files (x86)\Appium\node_modules\appium\build\android_bootstrap\AppiumBootstrap.jar" /data/local/tmp/
  info: [debug] Pushing settings apk to device...
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 install "C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk"
  info: [debug] Stopping logcat capture
  info: [debug] Logcat terminated with code null, signal SIGTERM
  info: [debug] Sent shutdown command, waiting for UiAutomator to stop...
  warn: UiAutomator did not shut down fast enough, calling it gone
  error: Failed to start an Appium session, err was: Error: Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]

info: [debug] Cleaning up android objects
  info: [debug] Cleaning up appium session
  info: [debug] Error: Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]

```<code>at ChildProcess.exithandler (child_process.js:637:15)
at ChildProcess.EventEmitter.emit (events.js:98:17)
at maybeClose (child_process.js:743:16)
at Process.ChildProcess._handle.onexit (child_process.js:810:5)
</code>```

info: [debug] Responding to client with error: {"status":33,"value":{"message":"A new session could not be created. (Original error: Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]\r\n)","killed":false,"code":1,"signal":null,"origValue":"Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]\r\n"},"sessionId":null}
  info: <-- POST /wd/hub/session 500 32039.992 ms - 664

`

答:
You need to share the full appium logs in order to know the reason for that.
[After checking the logs]
That's a known issue for that specific Android image as it installs 2 versions of appium settings app and unlock app. What you can do is either change the android image you are testing against or uninstall those 2 apps before starting your script.

You can uninstall them manually by starting the emulator GUI and do that with the mouse or through the below commands:

```<code>adb -s device_serial uninstall io.appium.settings
adb -s device_serial uninstall io.appium.unlock
</code>```

Also, you can add those commands in your code if you really have to execute the tests on android 7 devices as below:

```<code>String androidVersion=executeCommand("adb shell getprop ro.build.version.release");
if(androidVersion.contains("7"))
{
    //uninstall appium settings app
    cmd="adb uninstall  io.appium.settings";
    executeCommand(cmd);

    //uninstall appium unlock app
    cmd="adb uninstall  io.appium.unlock";
    executeCommand(cmd);
}
</code>```

Body:
Can anyone help me out I am new to Android testing with Appium , I am trying to open app in AVD the app getting installed but then m getting Error "A new Session could not be created.(Original error: Command failed: )","killed":false,"code":1,"signal":null,"origValue":"Command failed: "},"sessionId":null}

Thanks for the help in advance

tried with just giving capabilities.setCapability("appActivity", ".MainActivity");

'''

File classpathRoot = new File(System.getProperty("user.dir"));
        File appDir = new File(classpathRoot, "/Apps/src/");
        File app = new File(appDir, "ChatApp-release.apk");

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
        capabilities.setCapability("deviceName", "emulator-5554");
        capabilities.setCapability("platformVersion", "7.1.1");
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("app", app.getAbsolutePath());
        capabilities.setCapability("appPackage", "com.aaa.charla");
        capabilities.setCapability("appActivity", "com.aaa.xxx.MainActivity");

        driver = new AndroidDriver(new URL("https://127.0.0.1:4723/wd/hub"), capabilities);
        driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
        Thread.sleep(10000);
        driver.quit();

Following are the Debug log:

info: Console LogLevel: debug
  info: --> POST /wd/hub/session {"desiredCapabilities":{"app":"D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk","appPackage":"com.odysseyinc.charla","appActivity":"com.odyssey.chatapp.MainActivity","newCommandTimeout":"10000","platformName":"Android","version":"7.1.1","deviceName":"emulator-5554"}}
  info: Client User-Agent string: Apache-HttpClient/4.5.2 (Java/1.8.0_162)
  info: [debug] The following desired capabilities were provided, but not recognized by appium. They will be passed on to any other services running on this server. : version
  info: [debug] Using local app from desired caps: D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk
  info: [debug] Creating new appium session 0d25aeac-d055-449f-af84-b6d314d9b4a5
  info: Starting android appium
  info: [debug] Getting Java version
  info: Java version is: 1.8.0_162
  info: [debug] Checking whether adb is present
  info: [debug] Using adb from C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe
  info: [debug] Set chromedriver binary as: C:\Program Files (x86)\Appium\node_modules\appium\build\chromedriver\windows\chromedriver.exe
  info: [debug] Using fast reset? true
  info: [debug] Preparing device for session
  info: [debug] Checking whether app is actually present
  info: Retrieving device
  info: [debug] Trying to find a connected android device
  info: [debug] Getting connected devices...
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe devices
  info: [debug] 1 device(s) connected
  info: Found device emulator-5554
  info: [debug] Setting device id to emulator-5554
  info: [debug] Waiting for device to be ready and to respond to shell commands (timeout = 5)
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 wait-for-device
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "echo 'ready'"
  info: [debug] Starting logcat capture
  info: [debug] Getting device API level
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop ro.build.version.sdk"
  info: [debug] Device is at API Level 25
  info: Device API level is: 25
  info: [debug] Extracting strings for language: default
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop persist.sys.language"
  info: [debug] Current device persist.sys.language:
  info: [debug] java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\appium_apk_tools.jar" "stringsFromApk" "D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk" "C:\Users\UNMESH~1.GHA\AppData\Local\Temp\com.odysseyinc.charla"
  info: [debug] Reading strings from converted strings.json
  info: [debug] Setting language to default
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 push "C:\Users\UNMESH~1.GHA\AppData\Local\Temp\com.odysseyinc.charla\strings.json" /data/local/tmp
  info: [debug] Checking whether aapt is present
  info: [debug] Using aapt from C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\aapt.exe
  info: [debug] Retrieving process from manifest.
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\aapt.exe dump xmltree D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk AndroidManifest.xml
  info: [debug] Set app process to: com.odysseyinc.charla
  info: [debug] Not uninstalling app since server not started with --full-reset
  info: [debug] Checking app cert for D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk.
  info: [debug] executing cmd: java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\verify.jar" D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk
  info: [debug] App already signed.
  info: [debug] Zip-aligning D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk
  info: [debug] Checking whether zipalign is present
  info: [debug] Using zipalign from C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\zipalign.exe
  info: [debug] Zip-aligning apk.
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\zipalign.exe -f 4 D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk C:\Users\UNMESH~1.GHA\AppData\Local\Temp\119427-15556-1rmbgw9\appium.tmp
  info: [debug] MD5 for app is f3d7efc8b197792c3d0529a48dc92ff2
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "ls /data/local/tmp/f3d7efc8b197792c3d0529a48dc92ff2.apk"
  info: [debug] Getting install status for com.odysseyinc.charla
  info: [debug] Getting device API level
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop ro.build.version.sdk"
  info: [debug] Device is at API Level 25
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "pm list packages -3 com.odysseyinc.charla"
  info: [debug] App is installed
  info: App is already installed, resetting app
  info: [debug] Running fast reset (stop and clear)
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "am force-stop com.odysseyinc.charla"
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "pm clear com.odysseyinc.charla"
  info: [debug] Forwarding system:4724 to device:4724
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 forward tcp:4724 tcp:4724
  info: [debug] Pushing appium bootstrap to device...
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 push "C:\Program Files (x86)\Appium\node_modules\appium\build\android_bootstrap\AppiumBootstrap.jar" /data/local/tmp/
  info: [debug] Pushing settings apk to device...
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 install "C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk"
  info: [debug] Stopping logcat capture
  info: [debug] Logcat terminated with code null, signal SIGTERM
  info: [debug] Sent shutdown command, waiting for UiAutomator to stop...
  warn: UiAutomator did not shut down fast enough, calling it gone
  error: Failed to start an Appium session, err was: Error: Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]

info: [debug] Cleaning up android objects
  info: [debug] Cleaning up appium session
  info: [debug] Error: Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]

at ChildProcess.exithandler (child_process.js:637:15)
at ChildProcess.EventEmitter.emit (events.js:98:17)
at maybeClose (child_process.js:743:16)
at Process.ChildProcess._handle.onexit (child_process.js:810:5)

info: [debug] Responding to client with error: {"status":33,"value":{"message":"A new session could not be created. (Original error: Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]\r\n)","killed":false,"code":1,"signal":null,"origValue":"Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]\r\n"},"sessionId":null}
  info: <-- POST /wd/hub/session 500 32039.992 ms - 664

`

Body:
You need to share the full appium logs in order to know the reason for that.
[After checking the logs]
That's a known issue for that specific Android image as it installs 2 versions of appium settings app and unlock app. What you can do is either change the android image you are testing against or uninstall those 2 apps before starting your script.

You can uninstall them manually by starting the emulator GUI and do that with the mouse or through the below commands:

adb -s device_serial uninstall io.appium.settings
adb -s device_serial uninstall io.appium.unlock

Also, you can add those commands in your code if you really have to execute the tests on android 7 devices as below:

String androidVersion=executeCommand("adb shell getprop ro.build.version.release");
if(androidVersion.contains("7"))
{
    //uninstall appium settings app
    cmd="adb uninstall  io.appium.settings";
    executeCommand(cmd);

    //uninstall appium unlock app
    cmd="adb uninstall  io.appium.unlock";
    executeCommand(cmd);
}


来源: stackexchange

问:
Fit image inside as background button when button is clicked
When input type file is clicked, I want to show the selected image as background of the button.

But the following code doesn't fit(cover) the image inside the button after the image is selected.

Html

input#file {
  display: inline-block;
  box-shadow: 0 0 5px rgb(0, 0, 0, 0.3);
  width: 100%;
  padding: 400px 0 0 0;
  overflow: hidden;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  border-radius: 20px;
  background-size: 60px 60px;
  cursor: pointer;
  border: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type='file' id="file" (change)="onSelectFile($event)" class="form-control btn btn-primary" [ngStyle]="{'background': 'url(' + imageURL + ') center center no-repeat #e4e4e4'}"></code>```

Component

```<code>onSelectFile(event) {
  if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();

    reader.readAsDataURL(event.target.files[0]);

    reader.onload = (event) => {
      this.imageURL = event.target.result;
    }
  }
}
</code>```

答:
Try adding a background-size to the style of the button in question. It defaults to auto which shows actual size, not fit to container.

Add either background-size: cover (the image will fill the button but maybe not show the whole image. Or background-size: contain (the whole image will be forced to fit in the button, even if it looks squashed).

ContentLicense: CC BY-SA 4.0

Body:
When input type file is clicked, I want to show the selected image as background of the button.

But the following code doesn't fit(cover) the image inside the button after the image is selected.

Html

input#file {
  display: inline-block;
  box-shadow: 0 0 5px rgb(0, 0, 0, 0.3);
  width: 100%;
  padding: 400px 0 0 0;
  overflow: hidden;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  border-radius: 20px;
  background-size: 60px 60px;
  cursor: pointer;
  border: none;
}

<input type='file' id="file" (change)="onSelectFile($event)" class="form-control btn btn-primary" [ngStyle]="{'background': 'url(' + imageURL + ') center center no-repeat #e4e4e4'}">

Component

onSelectFile(event) {
  if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();

    reader.readAsDataURL(event.target.files[0]);

    reader.onload = (event) => {
      this.imageURL = event.target.result;
    }
  }
}


问:
How to play video in HTML page
I am trying to play a mp4 video on my HTML page, I have searched the web and found that in HTML5 I can do this with video tag like this below

```<code><video width="320" height="240" autoplay>
  <source src="movie.mp4" type="video/mp4">
</video>
</code>```

Issue I am facing

My main issue is my video is stored in my local computer in some location, So how can I call that from that path

In my system it is located in D drive so I want to call it from there

I am new to this so I don't know if I am doing it the right way; is my approach correct?

My requirement is to auto-play video on my web page

I am doing like this

```<code><video width="320" height="240" autoplay>
  <source src="D:\Video\samplevideo.mp4" type="video/mp4">
</video>
</code>```

D:\Video\samplevideo.mp4 is the path of my file and samplevideo.mp4 is the name of the video

On Chrome it show error Not allowed to load local resource: file:///D:/Video/samplevideo.mp4

And on Firefox All candidate resources failed to load. Media load paused.

Edit

My main focus is to play video on webpage.

I need to play a video on the web (HTML page) when page is loaded I have that video in my system at D:\Video\samplevideo.mp4 this path, how can I play that video when page is loaded.

答:
Try this Code</p>

```<code> <video muted autoplay loop class="video video js-video" id="hero-vid" poster="video/desktop-screen-banner.png">
    <source src="video/movie.webm" type="video/webm">
    <source src="video/movie.mp4" type="video/mp4">
    <source src="video/movie.ogg" type="video/ogg">
</video>
</code>```

Title: How to play video in HTML page

Body:
I am trying to play a mp4 video on my HTML page, I have searched the web and found that in HTML5 I can do this with video tag like this below

<video width="320" height="240" autoplay>
  <source src="movie.mp4" type="video/mp4">
</video>

Issue I am facing

My main issue is my video is stored in my local computer in some location, So how can I call that from that path

In my system it is located in D drive so I want to call it from there

I am new to this so I don't know if I am doing it the right way; is my approach correct?

My requirement is to auto-play video on my web page

I am doing like this

<video width="320" height="240" autoplay>
  <source src="D:\Video\samplevideo.mp4" type="video/mp4">
</video>

D:\Video\samplevideo.mp4 is the path of my file and samplevideo.mp4 is the name of the video

On Chrome it show error Not allowed to load local resource: file:///D:/Video/samplevideo.mp4

And on Firefox All candidate resources failed to load. Media load paused.

Edit

My main focus is to play video on webpage.

I need to play a video on the web (HTML page) when page is loaded I have that video in my system at D:\Video\samplevideo.mp4 this path, how can I play that video when page is loaded.

Body:
Try this Code

 <video muted autoplay loop class="video video js-video" id="hero-vid" poster="video/desktop-screen-banner.png">
    <source src="video/movie.webm" type="video/webm">
    <source src="video/movie.mp4" type="video/mp4">
    <source src="video/movie.ogg" type="video/ogg">
</video>


问:
How can I get the video's thumbnail using ytdl.getInfo?
I am using ytdl-core and discord.js to create a discord bot, and am adding a music command. Is there a way using ytdl.getInfo that I can get the thumbnail of the provided URL?

Edit:

```<code>let validate = await ytdl.validateURL(args[0])
    if(!validate) return message.channel.send("This URL doesn't seem to be valid. Please put a valid YouTube URL after the command.")
    let vidInfo = await ytdl.getInfo(args[0])
</code>```

答:
Yes you can

By just running ytdl.getInfo() you can find that one of the first property of the object is thumbnail_url. So it would be

```<code>const ytdl = require('ytdl-core');

ytdl.getInfo('https://www.youtube.com/watch?v=YQHsXMglC9A', function(err, info) {
  console.log(info.thumbnail_url) // "Adele - Hello" thumbail
});
</code>```

Howver the default thumbnail is really small. So I went on the video and found (by inspecting the element) that the picture used for the backrground is the same as the default one, but with 'hqdefault' instead of 'default' in the name.

Example:

Adele Hello thumbnail: https://i.ytimg.com/vi/YQHsXMglC9A/default.jpg

Adele Hello hq thumbnail: https://i.ytimg.com/vi/YQHsXMglC9A/hqdefault.jpg

I don't know if it apply to all video tho. I think you can do something like, try hq thumbnail, if not found use default thumbnail.

Edit: Adele Hello maxres thumbnail: https://i.ytimg.com/vi/YQHsXMglC9A/maxresdefault.jpg

Body:
I am using ytdl-core and discord.js to create a discord bot, and am adding a music command. Is there a way using ytdl.getInfo that I can get the thumbnail of the provided URL?

Edit:

let validate = await ytdl.validateURL(args[0])
    if(!validate) return message.channel.send("This URL doesn't seem to be valid. Please put a valid YouTube URL after the command.")
    let vidInfo = await ytdl.getInfo(args[0])

Body:
Yes you can

By just running ytdl.getInfo() you can find that one of the first property of the object is thumbnail_url. So it would be

const ytdl = require('ytdl-core');

ytdl.getInfo('https://www.youtube.com/watch?v=YQHsXMglC9A', function(err, info) {
  console.log(info.thumbnail_url) // "Adele - Hello" thumbail
});

Howver the default thumbnail is really small. So I went on the video and found (by inspecting the element) that the picture used for the backrground is the same as the default one, but with 'hqdefault' instead of 'default' in the name.

Example:

Adele Hello thumbnail: https://i.ytimg.com/vi/YQHsXMglC9A/default.jpg

Adele Hello hq thumbnail: https://i.ytimg.com/vi/YQHsXMglC9A/hqdefault.jpg

I don't know if it apply to all video tho. I think you can do something like, try hq thumbnail, if not found use default thumbnail.

Edit: Adele Hello maxres thumbnail: https://i.ytimg.com/vi/YQHsXMglC9A/maxresdefault.jpg


问:
Unable to create and attach a public ip ro a VM by terraform
I am getting the below error when I try to create a public ip

```<code>2019-05-27T03:07:44.5185437Z * azurerm_network_interface.tf-ni-erx-sqlcl1[1]: Resource 'azurerm_public_ip.tf-pip-erx-sqlcl1' not found for variable 'azurerm_public_ip.tf-pip-erx-sqlcl1.id'
2019-05-27T03:07:44.5186152Z * azurerm_network_interface.tf-ni-erx-sqlcl1[0]: Resource 'azurerm_public_ip.tf-pip-erx-sqlcl1' not found for variable 'azurerm_public_ip.tf-pip-erx-sqlcl1.id'
2019-05-27T03:07:44.5186473Z * azurerm_network_interface.tf-ni-erx-sqlcl2: 2 error(s) occurred:
2019-05-27T03:07:44.5186558Z
2019-05-27T03:07:44.5186910Z * azurerm_network_interface.tf-ni-erx-sqlcl2[0]: Resource 'azurerm_public_ip.tf-pip-erx-sqlcl2' not found for variable 'azurerm_public_ip.tf-pip-erx-sqlcl2.id'
2019-05-27T03:07:44.5187360Z * azurerm_network_interface.tf-ni-erx-sqlcl2[1]: Resource 'azurerm_public_ip.tf-pip-erx-sqlcl2' not found for variable 'azurerm_public_ip.tf-pip-erx-sqlcl2.id'
</code>```

My terraform code is as below:

```<code>resource "azurerm_public_ip" "tf-pip-erx-sqlcl1" {
  count                     = "${var.count_sqlcl1_vm}"
  name                      = "${var.sql_base_hostname}${format("%02d",count.index+1)}-pip01"
  location                  = "${data.azurerm_resource_group.tf-rg-erx-external.location}"
  resource_group_name       = "${data.azurerm_resource_group.tf-rg-erx-external.name}"
  allocation_method         = "Dynamic"
}
# Network inteface for sql
resource "azurerm_network_interface" "tf-ni-erx-sqlcl1" {
 count               = "${var.count_sqlcl1_vm}"
 name                = "${var.bussvc_base_hostname}${format("%02d",count.index+1)}-nic01"
 location            = "${data.azurerm_resource_group.tf-rg-erx-external.location}"
 resource_group_name = "${data.azurerm_resource_group.tf-rg-erx-external.name}"

ip_configuration {
    name                          = "${var.sql_base_hostname}${format("%02d",count.index+1)}-iip01"
    subnet_id                     = "${data.azurerm_subnet.tf-sn-erx-sql.id}"
    private_ip_address_allocation = "${var.env=="msdn"?"dynamic":"static"}"
    #private_ip_address            = "${var.env=="msdn"?"":"10.112.3.${count.index+10}"}"
    public_ip_address_id          = "${azurerm_public_ip.tf-pip-erx-sqlcl1.id}"
}
}
resource "azurerm_public_ip" "tf-pip-erx-sqlcl2" {
  count                     = "${var.count_sqlcl2_vm}"
  name                      = "${var.sql_base_hostname}${format("%02d",count.index+1)}-pip01"
  location                  = "${data.azurerm_resource_group.tf-rg-erx-external.location}"
  resource_group_name       = "${data.azurerm_resource_group.tf-rg-erx-external.name}"
  allocation_method         = "Dynamic"
}
resource "azurerm_network_interface" "tf-ni-erx-sqlcl2" {
 count               = "${var.count_sqlcl2_vm}"
 name                = "${var.sql_base_hostname}${format("%02d%s",count.index,var.count_sqlcl1_vm)}-nic01"
 location            = "${data.azurerm_resource_group.tf-rg-erx-external.location}"
 resource_group_name = "${data.azurerm_resource_group.tf-rg-erx-external.name}"

ip_configuration {
    name                          = "${var.sql_base_hostname}${format("%02d",count.index+1)}-iip01"
    subnet_id                     = "${data.azurerm_subnet.tf-sn-erx-sql.id}"
    private_ip_address_allocation = "${var.env=="msdn"?"dynamic":"static"}"
    #private_ip_address           = "10.112.3.${count.index+15}"
    public_ip_address_id          = "${azurerm_public_ip.tf-pip-erx-sqlcl2.id}"
}
}
</code>```

I'm unable to understand what is the issue, I specifically added "depends_on" to network interface , ip configuration block like below

```<code>depends_on                    = "[azure_public_ip.tf-pip-erx-sqlcl2]"
</code>```

The idea behind to do so is to ensure public ip is created before network interface resource is created but unfortunately that does not help either.

It reports error as below,

```<code>Error: azurerm_network_interface.tf-ni-erx-sqlcl2[1]: ip_configuration.0: invalid or unknown key: depends_on
</code>```

Any assistance would be highly appreciated.

答:
About the error, since your resource "azurerm_network_interface" has count, you could change the public_ip_address_id  like this with element function:

```<code>public_ip_address_id          = "${element(azurerm_public_ip.tf-pip-erx-sqlcl1.*.id,count.index)}"
</code>```

and

```<code>public_ip_address_id          = "${element(azurerm_public_ip.tf-pip-erx-sqlcl2.*.id,count.index)}"
</code>```

Body:
I am getting the below error when I try to create a public ip

2019-05-27T03:07:44.5185437Z * azurerm_network_interface.tf-ni-erx-sqlcl1[1]: Resource 'azurerm_public_ip.tf-pip-erx-sqlcl1' not found for variable 'azurerm_public_ip.tf-pip-erx-sqlcl1.id'
2019-05-27T03:07:44.5186152Z * azurerm_network_interface.tf-ni-erx-sqlcl1[0]: Resource 'azurerm_public_ip.tf-pip-erx-sqlcl1' not found for variable 'azurerm_public_ip.tf-pip-erx-sqlcl1.id'
2019-05-27T03:07:44.5186473Z * azurerm_network_interface.tf-ni-erx-sqlcl2: 2 error(s) occurred:
2019-05-27T03:07:44.5186558Z
2019-05-27T03:07:44.5186910Z * azurerm_network_interface.tf-ni-erx-sqlcl2[0]: Resource 'azurerm_public_ip.tf-pip-erx-sqlcl2' not found for variable 'azurerm_public_ip.tf-pip-erx-sqlcl2.id'
2019-05-27T03:07:44.5187360Z * azurerm_network_interface.tf-ni-erx-sqlcl2[1]: Resource 'azurerm_public_ip.tf-pip-erx-sqlcl2' not found for variable 'azurerm_public_ip.tf-pip-erx-sqlcl2.id'

My terraform code is as below:

resource "azurerm_public_ip" "tf-pip-erx-sqlcl1" {
  count                     = "${var.count_sqlcl1_vm}"
  name                      = "${var.sql_base_hostname}${format("%02d",count.index+1)}-pip01"
  location                  = "${data.azurerm_resource_group.tf-rg-erx-external.location}"
  resource_group_name       = "${data.azurerm_resource_group.tf-rg-erx-external.name}"
  allocation_method         = "Dynamic"
}
# Network inteface for sql
resource "azurerm_network_interface" "tf-ni-erx-sqlcl1" {
 count               = "${var.count_sqlcl1_vm}"
 name                = "${var.bussvc_base_hostname}${format("%02d",count.index+1)}-nic01"
 location            = "${data.azurerm_resource_group.tf-rg-erx-external.location}"
 resource_group_name = "${data.azurerm_resource_group.tf-rg-erx-external.name}"

ip_configuration {
    name                          = "${var.sql_base_hostname}${format("%02d",count.index+1)}-iip01"
    subnet_id                     = "${data.azurerm_subnet.tf-sn-erx-sql.id}"
    private_ip_address_allocation = "${var.env=="msdn"?"dynamic":"static"}"
    #private_ip_address            = "${var.env=="msdn"?"":"10.112.3.${count.index+10}"}"
    public_ip_address_id          = "${azurerm_public_ip.tf-pip-erx-sqlcl1.id}"
}
}
resource "azurerm_public_ip" "tf-pip-erx-sqlcl2" {
  count                     = "${var.count_sqlcl2_vm}"
  name                      = "${var.sql_base_hostname}${format("%02d",count.index+1)}-pip01"
  location                  = "${data.azurerm_resource_group.tf-rg-erx-external.location}"
  resource_group_name       = "${data.azurerm_resource_group.tf-rg-erx-external.name}"
  allocation_method         = "Dynamic"
}
resource "azurerm_network_interface" "tf-ni-erx-sqlcl2" {
 count               = "${var.count_sqlcl2_vm}"
 name                = "${var.sql_base_hostname}${format("%02d%s",count.index,var.count_sqlcl1_vm)}-nic01"
 location            = "${data.azurerm_resource_group.tf-rg-erx-external.location}"
 resource_group_name = "${data.azurerm_resource_group.tf-rg-erx-external.name}"

ip_configuration {
    name                          = "${var.sql_base_hostname}${format("%02d",count.index+1)}-iip01"
    subnet_id                     = "${data.azurerm_subnet.tf-sn-erx-sql.id}"
    private_ip_address_allocation = "${var.env=="msdn"?"dynamic":"static"}"
    #private_ip_address           = "10.112.3.${count.index+15}"
    public_ip_address_id          = "${azurerm_public_ip.tf-pip-erx-sqlcl2.id}"
}
}

I'm unable to understand what is the issue, I specifically added "depends_on" to network interface , ip configuration block like below

depends_on                    = "[azure_public_ip.tf-pip-erx-sqlcl2]"

The idea behind to do so is to ensure public ip is created before network interface resource is created but unfortunately that does not help either.

It reports error as below,

Error: azurerm_network_interface.tf-ni-erx-sqlcl2[1]: ip_configuration.0: invalid or unknown key: depends_on

Any assistance would be highly appreciated.

Body:
About the error, since your resource "azurerm_network_interface" has count, you could change the public_ip_address_id  like this with element function:

public_ip_address_id          = "${element(azurerm_public_ip.tf-pip-erx-sqlcl1.*.id,count.index)}"

and

public_ip_address_id          = "${element(azurerm_public_ip.tf-pip-erx-sqlcl2.*.id,count.index)}"


问:
how to detect if a file operation is currently done on a file on linux
How can i detect if a file is open and a file operation is being done on it by another process on linux by using c or c++? I know lsof lists all open files but i dont how it gets that information.

Thx

答:
I'm not sure lsof is actually working like this, but a way to implement it could be this:

get your process' open files by looknig to /proc/$PID/fd/ files.

look to any any other process' /proc/$PID/fd/ in order to see who is reading your same files.

ContentLicense: CC BY-SA 3.0


问:
How to run an Asyncio task without awaiting?
I need to call a task periodically but (a)waiting times are almost more than the period.

In the following code, How can I run do_something() task without need to await for the result?

```<code> import asyncio
 import time
 from random import randint

 period = 1  # Second

 def get_epoch_ms():
     return int(time.time() * 1000.0)

 async def do_something(name):
     print("Start  :", name, get_epoch_ms())
     try:
         # Do something which may takes more than 1 secs.
         slp = randint(1, 5)
         print("Sleep  :", name, get_epoch_ms(), slp)
         await asyncio.sleep(slp)
     except Exception as e:
         print("Error  :", e)

     print("Finish :", name, get_epoch_ms())

 async def main():
     i = 0
     while True:
         i += 1
         # Todo : this line should be change
         await do_something('T' + str(i))
         await asyncio.sleep(period)

 asyncio.get_event_loop().run_until_complete(main())
</code>```

答:
Your problem is using the run_until_complete(main()) which does not satisfy your concurrency purpose. So, assuming your coroutine tasks (do_something()) are bounded to 5, your code will be as follows:

```<code>import time
from random import randint

period = 1  # Second

def get_epoch_ms():
    return int(time.time() * 1000.0)

async def do_something(name):
    print("Start  :", name, get_epoch_ms())
    try:
        # Do something which may takes more than 1 secs.
        slp = randint(1, 5)
        print("Sleep  :", name, get_epoch_ms(), slp)
        await asyncio.sleep(slp)
    except Exception as e:
        print("Error  :", e)

    print("Finish :", name, get_epoch_ms())

loop = asyncio.get_event_loop()
futures = [loop.create_task(do_something('T' + str(i)))
           for i in range(5)]

loop.run_forever()

for f in futures:
    f.cancel()
</code>```

Here is the concurrency workflow in its output:

```<code>Start  : T0 1558937750705
Sleep  : T0 1558937750705 5
Start  : T1 1558937750705
Sleep  : T1 1558937750705 1
Start  : T2 1558937750705
Sleep  : T2 1558937750705 4
Start  : T3 1558937750705
Sleep  : T3 1558937750705 5
Start  : T4 1558937750705
Sleep  : T4 1558937750705 5
Finish : T1 1558937751707
Finish : T2 1558937754709
Finish : T0 1558937755707
Finish : T3 1558937755708
Finish : T4 1558937755708
</code>```

However, If your coroutine tasks are not bounded you could do it:

```<code>...
async def main(loop):
    i = 0
    while True:
        i += 1
        loop.create_task(do_something('T' + str(i)))
        await asyncio.sleep(period)

loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
</code>```

Body:
I need to call a task periodically but (a)waiting times are almost more than the period.

In the following code, How can I run do_something() task without need to await for the result?

 import asyncio
 import time
 from random import randint

 period = 1  # Second

 def get_epoch_ms():
     return int(time.time() * 1000.0)

 async def do_something(name):
     print("Start  :", name, get_epoch_ms())
     try:
         # Do something which may takes more than 1 secs.
         slp = randint(1, 5)
         print("Sleep  :", name, get_epoch_ms(), slp)
         await asyncio.sleep(slp)
     except Exception as e:
         print("Error  :", e)

     print("Finish :", name, get_epoch_ms())

 async def main():
     i = 0
     while True:
         i += 1
         # Todo : this line should be change
         await do_something('T' + str(i))
         await asyncio.sleep(period)

 asyncio.get_event_loop().run_until_complete(main())

Body:
Your problem is using the run_until_complete(main()) which does not satisfy your concurrency purpose. So, assuming your coroutine tasks (do_something()) are bounded to 5, your code will be as follows:

import time
from random import randint

period = 1  # Second

def get_epoch_ms():
    return int(time.time() * 1000.0)

async def do_something(name):
    print("Start  :", name, get_epoch_ms())
    try:
        # Do something which may takes more than 1 secs.
        slp = randint(1, 5)
        print("Sleep  :", name, get_epoch_ms(), slp)
        await asyncio.sleep(slp)
    except Exception as e:
        print("Error  :", e)

    print("Finish :", name, get_epoch_ms())

loop = asyncio.get_event_loop()
futures = [loop.create_task(do_something('T' + str(i)))
           for i in range(5)]

loop.run_forever()

for f in futures:
    f.cancel()

Here is the concurrency workflow in its output:

Start  : T0 1558937750705
Sleep  : T0 1558937750705 5
Start  : T1 1558937750705
Sleep  : T1 1558937750705 1
Start  : T2 1558937750705
Sleep  : T2 1558937750705 4
Start  : T3 1558937750705
Sleep  : T3 1558937750705 5
Start  : T4 1558937750705
Sleep  : T4 1558937750705 5
Finish : T1 1558937751707
Finish : T2 1558937754709
Finish : T0 1558937755707
Finish : T3 1558937755708
Finish : T4 1558937755708

However, If your coroutine tasks are not bounded you could do it:

...
async def main(loop):
    i = 0
    while True:
        i += 1
        loop.create_task(do_something('T' + str(i)))
        await asyncio.sleep(period)

loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))


问:
Making a folder directory from a text file using a python script
I have a text file with hundreds of lines, each line contains a number to represent the level the folder/file should be on and a folder/file name. Because the  hierarchy is too large I want to make a script to automate making this directory/sub directory.

Example text file

```<code> .0.  Folder Name a
  .1. Folder Name b
   .2. Folder Name c
   .2. Folder Name c2
  .1. Folder Name d
   .2. Folder Name e
   .2. Folder Name e2
    .3. Folder Name f
</code>```

I assume I need to read line by line and use os.mkdir, but I don't know how to step down a directory level.

```<code>#path of file
import os

with open('Tree.txt', 'r') as t:
 for line in t:
  readline(.{Level}. {FolderName})
    if Level == '0'
     os.mkdir(FolderName)
    else if Level == '1'
     # go down and os.mkdir(FolderName)
</code>```

答:
I did something like this. It is using os.mkdir and os.chdir, inspired from @JROS.

It basically checks by levels, if level is bigger it gets inside the folder. If it is less, then it simply moves back n times, n being the difference between two consecutive levels.

commands.txt is the file that contains the lines.

import os

with open('commands.txt') as f:
  line = f.readline().strip()
  prev_level = int(line.split(". ")[0].split(".")[1])
  folder_name = line.split("Folder Name ")[1]
  curr_level = prev_level
  while line:
    if curr_level > prev_level:
      os.chdir(prev_folder_name)
    elif curr_level < prev_level:
      diff = prev_level - curr_level
      for i in range(diff):
        os.chdir('..')

    os.mkdir(folder_name)

    line = f.readline().strip()
    if line:
      prev_level = curr_level
      curr_level = int(line.split(". ")[0].split(".")[1])
      prev_folder_name = folder_name
      folder_name = line.split("Folder Name ")[1]
```

Body:
I have a text file with hundreds of lines, each line contains a number to represent the level the folder/file should be on and a folder/file name. Because the  hierarchy is too large I want to make a script to automate making this directory/sub directory.

Example text file

 .0.  Folder Name a
  .1. Folder Name b
   .2. Folder Name c
   .2. Folder Name c2
  .1. Folder Name d
   .2. Folder Name e
   .2. Folder Name e2
    .3. Folder Name f

I assume I need to read line by line and use os.mkdir, but I don't know how to step down a directory level.

#path of file
import os

with open('Tree.txt', 'r') as t:
 for line in t:
  readline(.{Level}. {FolderName})
    if Level == '0'
     os.mkdir(FolderName)
    else if Level == '1'
     # go down and os.mkdir(FolderName)


问:
What are some good ways to delete files with blank(invisible) names?
I discovered some files with blank names in my code repository, but I don't know how to find them all and delete them.</p>

答: You can use -b option of ls to find non printable characters eg ls -b


问:
Simplify one row Grid Xamarin forms Xaml
Does anyone know a simpler way to define a one row Grid. I have the following:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Label Text="Tester:"/>
    <Entry Grid.Column="1" />
</Grid>
</code>```

Hard to explain but using xamStrap to layout some forms and due to the label and entry layout wrapping required we need to create Grid's currently for the label and entry pairing. Having a grid for every label and entry on the form is making some really ugly large xaml contentviews.

Is there any shorthand or better way to lay this out in xaml?

答:
You could use a horizontal StackLayout / FlexLayout instead of a Grid.
If you prefer grid, you could also convert this view to a custom control to make the code in the ContentPage shorter.

Body:
Does anyone know a simpler way to define a one row Grid. I have the following:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <Entry Grid.Column="1" />
</Grid>

Hard to explain but using xamStrap to layout some forms and due to the label and entry layout wrapping required we need to create Grid's currently for the label and entry pairing. Having a grid for every label and entry on the form is making some really ugly large xaml contentviews.

Is there any shorthand or better way to lay this out in xaml?


问:
Not able to fetch subscription details
I have a multi tenant azure application. When i am trying to fetch subscription details using azure management api, it is always giving null.

I have followed all the steps except step3 mentioned in this post

Fetching VM details from multiple tenants

答:
Its seems that you are trying to get azure subscription Information.

Try with REST API:

```<code>GET https://management.azure.com/subscriptions
</code>```

Note: Refer to this docs. Then click on Try it section.

See the screen shot:

Click on Try it. you will prompt to login login with your credential. After that you will be given option for which tenant you want to get subscription. In response you would get your information like below:

Title: Not able to fetch subscription details

Body:
Its seems that you are trying to get azure subscription Information.

Try with REST API:

GET https://management.azure.com/subscriptions

Note: Refer to this docs. Then click on Try it section.

See the screen shot:

Click on Try it. you will prompt to login login with your credential. After that you will be given option for which tenant you want to get subscription. In response you would get your information like below:


问:
Mongoexport exporting invalid json files
I collected some tweets from the twitter API and stored it to mongodb, I tried exporting the data to a JSON file and didn't have any issues there, until I tried to make a python script to read the JSON and convert it to a csv. I get this traceback error with my code:

```<code>json.decoder.JSONDecodeError: Extra data: line 367 column 1 (char 9745)
</code>```

So, after digging around the internet I was pointed to check the actual JSON data in an online validator, which I did. This gave me the error of:

```<code>Multiple JSON root elements
</code>```

from the site https://jsonformatter.curiousconcept.com/

Here are pictures of the 1st/2nd object beginning/end of the file:

or a link to the data here

Now, the problem is, I haven't found anything on the internet of how to handle that error. I'm not sure if it's an error with the data I've collected, exported, or if I just don't know how to work with it.

My end game with these tweets is to make a network graph. I was looking at either Networkx or Gephi, which is why I'd like to get a csv file.

答:
A bit late reply, and I am not sure it was available the time this question was posted. Anyway, now there is a simple way to import the mongoexport json data as follows:

```<code>df = pd.read_json(filename, lines=True)

</code>```

mongoexport provides each line as a json objects itself, instead of the whole file as json.

Body:
I collected some tweets from the twitter API and stored it to mongodb, I tried exporting the data to a JSON file and didn't have any issues there, until I tried to make a python script to read the JSON and convert it to a csv. I get this traceback error with my code:

json.decoder.JSONDecodeError: Extra data: line 367 column 1 (char 9745)

So, after digging around the internet I was pointed to check the actual JSON data in an online validator, which I did. This gave me the error of:

Multiple JSON root elements

from the site https://jsonformatter.curiousconcept.com/

Here are pictures of the 1st/2nd object beginning/end of the file:

or a link to the data here

Now, the problem is, I haven't found anything on the internet of how to handle that error. I'm not sure if it's an error with the data I've collected, exported, or if I just don't know how to work with it.

My end game with these tweets is to make a network graph. I was looking at either Networkx or Gephi, which is why I'd like to get a csv file.

Body:
A bit late reply, and I am not sure it was available the time this question was posted. Anyway, now there is a simple way to import the mongoexport json data as follows:

df = pd.read_json(filename, lines=True)

mongoexport provides each line as a json objects itself, instead of the whole file as json.


问:
Translating to english using word lists
Say I have a list of item-colour pairs:

Item1 red

Item2 red_in_finnish

Item3 red_in_polish

Item4 blue_in_russian

Item5 blue_in_estonian

Item6 blue_in_polish

I need to translate all the colours in foreign languages to English:

Item1 red

Item2 red

Item3 red

Item4 blue

Item5 blue

Item6 blue

In my actual code, I have many more than two colours, and about a dozen different arrays containing all the foreign words for each colour. This is the current way I am performing the replacement:

```<code>red_words = ['red_in_finnish', 'red_in_polish']
blue_words = ['blue_in_russian', 'blue_in_estonian', 'blue_in_polish']

for word in red_words:
   if word in item_name:
      item_name = item_name.replace(word, "red")
</code>```

The problem is that I do not know beforehand if each name contains any specific colour, so I need to check for all of them to make sure I replace everything.

Is there a smart way to do this? It would be perfect if it was possible to somehow map colours' foreign names to their English names.

答:
You can use Goslate (Free Google Translate API) </p>

```<code>import goslate
gs = goslate.Goslate()

for word in words:
    print(gs.translate(word, 'en'))
</code>```

Title: Translating to english using word lists

Body:
Say I have a list of item-colour pairs:

Item1 red

Item2 red_in_finnish

Item3 red_in_polish

Item4 blue_in_russian

Item5 blue_in_estonian

Item6 blue_in_polish

I need to translate all the colours in foreign languages to English:

Item1 red

Item2 red

Item3 red

Item4 blue

Item5 blue

Item6 blue

In my actual code, I have many more than two colours, and about a dozen different arrays containing all the foreign words for each colour. This is the current way I am performing the replacement:

red_words = ['red_in_finnish', 'red_in_polish']
blue_words = ['blue_in_russian', 'blue_in_estonian', 'blue_in_polish']

for word in red_words:
   if word in item_name:
      item_name = item_name.replace(word, "red")

The problem is that I do not know beforehand if each name contains any specific colour, so I need to check for all of them to make sure I replace everything.

Is there a smart way to do this? It would be perfect if it was possible to somehow map colours' foreign names to their English names.

Body:
You can use Goslate (Free Google Translate API)

import goslate
gs = goslate.Goslate()

for word in words:
    print(gs.translate(word, 'en'))


问:
How do I correctly use .click on this select type from html coding in Javascript?
```<code><select name="s" id="s">
    <option value="64752">Small</option>
    <option value="64753">Medium</option>
</select>
</code>```

Here is the HTML code for the select type from the website

```<code>.realClick('select#s', {x: 1, y: 1})
.insert('input#s', size)
</code>```

Here is part of my coding I have tried, I get the error "cannot find element: "select#s"

I am not really sure what else to try I am fairly new to automating. I use PhantomJS with real-click PhantomJS. Any ideas would be great. Thank you

答:
I don't think you can use click on selects. I remember when I was using PhantomJS a lot I had to set the selected index of the option I was trying to choose:

```<code>page.evaluate(function() {

  // Set the selected index
  var select = document.getElementById('s');
  select.selectedIndex = 1;

  // Trigger a change event
  var onChange = document.createEvent('HTMLEvents');
  onChange.initEvent('change', false, true);
  select.dispatchEvent(onChange);

});
</code>```

This should select the option Medium.

More info regarding the onChange parameters.

Body:
<select name="s" id="s">
    <option value="64752">Small</option>
    <option value="64753">Medium</option>
</select>

Here is the HTML code for the select type from the website

.realClick('select#s', {x: 1, y: 1})
.insert('input#s', size)

Here is part of my coding I have tried, I get the error "cannot find element: "select#s"

I am not really sure what else to try I am fairly new to automating. I use PhantomJS with real-click PhantomJS. Any ideas would be great. Thank you

Body:
I don't think you can use click on selects. I remember when I was using PhantomJS a lot I had to set the selected index of the option I was trying to choose:

page.evaluate(function() {

  // Set the selected index
  var select = document.getElementById('s');
  select.selectedIndex = 1;

  // Trigger a change event
  var onChange = document.createEvent('HTMLEvents');
  onChange.initEvent('change', false, true);
  select.dispatchEvent(onChange);

});

This should select the option Medium.

More info regarding the onChange parameters.


问:
Way to call hooks from button events in react
This is my first time to develop a react application. I intend to make an Api call when user clicked a button. Is it possible to directly call a hook from an event? If yes, how can I call it if the hook was from a different component?

This is the button (different component)

```<code> const paginationButtons = (
    <React.Fragment>
      <Button onClick={() => viewDetails()}>View Details</Button>
    </React.Fragment>
  );

function viewDetails() {
   //Is it Possible to call fetch data.js and pass the url from here?
  }
</code>```

This is the hook for fetch data.js

```<code>import axios from 'axios';
import PropTypes from 'prop-types';
import { useState, useEffect} from 'react';

const propTypes = {
  initialUrl: PropTypes.string.isRequired,
  initialParams: PropTypes.object
}

export const useFetchData = props => {
  PropTypes.checkPropTypes(propTypes, props, 'property', 'useFetchData');

  const { initialUrl, initialParams } = props;

  const [request, setRequest] = useState({
    url: initialUrl,
    params: initialParams
  });
  const [loading, setIsLoading] = useState(false);
  const [error, setError] = useState();
  const [data, setData] = useState([]);

  useEffect(() => {
    const {url, params} = request;

    const fetchData = async () => {
      setIsLoading(true);
      try {
        const result = await axios(url, {params: {...params}});
        setIsLoading(false);
        setData(result.data);
      } catch(err) {
        setIsLoading(false);
        setError(err);
      }
    }

    fetchData();
  }, [request]);

  const doFetch = (params) => {
    setRequest({url: request.url, params: params});
  };
  return {loading, error, data, doFetch};
}

</code>```

Thank you very much for your help.

答:
you may need context</p>

```<code>const Context = React.createContext(null);

function FetchProvider(props){
   const state = useFetchData(props);
   return (
     <Context.Provider value={state}>{props.children}</Context.Provider>
   )
}

function Button(){
   const { doFetch } = React.useContext(Context);
   const handleClick = React.useCallback(()=> doFetch({id: ""}), [])
   return <button onClick={handleClick}>Fetch</button>
}

function ViewDetails(){
   const {data, error, loading} = React.useContext(Context);
   if (loading) { return <div>Loading</div> }
   if (error) { return <div>{error.message}</div> }
   return <div>{JSON.stringify(data)}</div>
}

function Page(){
   return (
     <FetchProvider initialUrl="/url" initialParams={{id: ""}}>
       <ViewDetails/>
       <Button/>
     </FetchProvider >
   );
}
</code>```

Body:
This is my first time to develop a react application. I intend to make an Api call when user clicked a button. Is it possible to directly call a hook from an event? If yes, how can I call it if the hook was from a different component?

This is the button (different component)

 const paginationButtons = (
    <React.Fragment>
      <Button onClick={() => viewDetails()}>View Details</Button>
    </React.Fragment>
  );

function viewDetails() {
   //Is it Possible to call fetch data.js and pass the url from here?
  }

This is the hook for fetch data.js

import axios from 'axios';
import PropTypes from 'prop-types';
import { useState, useEffect} from 'react';

const propTypes = {
  initialUrl: PropTypes.string.isRequired,
  initialParams: PropTypes.object
}

export const useFetchData = props => {
  PropTypes.checkPropTypes(propTypes, props, 'property', 'useFetchData');

  const { initialUrl, initialParams } = props;

  const [request, setRequest] = useState({
    url: initialUrl,
    params: initialParams
  });
  const [loading, setIsLoading] = useState(false);
  const [error, setError] = useState();
  const [data, setData] = useState([]);

  useEffect(() => {
    const {url, params} = request;

    const fetchData = async () => {
      setIsLoading(true);
      try {
        const result = await axios(url, {params: {...params}});
        setIsLoading(false);
        setData(result.data);
      } catch(err) {
        setIsLoading(false);
        setError(err);
      }
    }

    fetchData();
  }, [request]);

  const doFetch = (params) => {
    setRequest({url: request.url, params: params});
  };
  return {loading, error, data, doFetch};
}

Thank you very much for your help.

Body:
you may need context

const Context = React.createContext(null);

function FetchProvider(props){
   const state = useFetchData(props);
   return (
     <Context.Provider value={state}>{props.children}</Context.Provider>
   )
}

function Button(){
   const { doFetch } = React.useContext(Context);
   const handleClick = React.useCallback(()=> doFetch({id: ""}), [])
   return <button onClick={handleClick}>Fetch</button>
}

function ViewDetails(){
   const {data, error, loading} = React.useContext(Context);
   if (loading) { return <div>Loading</div> }
   if (error) { return <div>{error.message}</div> }
   return <div>{JSON.stringify(data)}</div>
}

function Page(){
   return (
     <FetchProvider initialUrl="/url" initialParams={{id: ""}}>
       <ViewDetails/>
       <Button/>
     </FetchProvider >
   );
}


问:
php variable scope
i'm confused about the php variable scope.
such as:

```<code>while(true){
    $var = "yes , it is a test!";
  }
  printf($var)
</code>```

the $var is defined in while statement scope , how could we get it outside it's scope ? and i can't find explanation on the document .

i wonder how php deal with it's scope .

答:
If you do while(true) you will not get out of the while, so it wouldn't matter. But if you would have a real expression, something like this (this is a useless example, i know)

```<code>$i=0
while($i<10){
   $var = "yes , it is a test!";
   $i++;
 }
 printf($var);
</code>```

Will just work.
There is no special "while" variable scope, the printf will print your string. check : http://php.net/manual/en/language.variables.scope.php

Title: php variable scope

Body:
i'm confused about the php variable scope.
such as:

while(true){
    $var = "yes , it is a test!";
  }
  printf($var)

the $var is defined in while statement scope , how could we get it outside it's scope ? and i can't find explanation on the document .

i wonder how php deal with it's scope .

Body:
If you do while(true) you will not get out of the while, so it wouldn't matter. But if you would have a real expression, something like this (this is a useless example, i know)

$i=0
while($i<10){
   $var = "yes , it is a test!";
   $i++;
 }
 printf($var);

Will just work.
There is no special "while" variable scope, the printf will print your string. check : http://php.net/manual/en/language.variables.scope.php


问:
what is the usage of bs4.element.Tag?
here is a html block

```<code>print(t)
</code>```

gives

```<code><dl class="docutils" id="index-0">
<dt><code class="docutils literal notranslate"><span class="pre">.</span></code></dt>
<dd>(Dot.)  In the default mode, this matches any character except a newline.  If
the <a class="reference internal" href="#re.DOTALL" title="re.DOTALL"><code class="xref py py-const docutils literal notranslate"><span class="pre">DOTALL</span></code></a> flag has been specified, this matches any character
including a newline.</dd>
</dl>
</code>```

while

```<code>print(t.select('dt .pre'))
</code>```

outputs

```<code>[<span class="pre">.</span>]
</code>```

what does the pattern string do in this line of code.

答:
You are using beautifulsoup's CSS selectors.

.select() takes a Tag as the first parameter, the second parameter serves different purpose, in your case since the second parameter starts with . it searches for a tag with the mentioned class name.

print(t.select('dt .pre')): It searches inside a dt tag that has a tag with class name pre.

You can find out more here

Title: what is the usage of bs4.element.Tag?

Body:
here is a html block

print(t)

gives

.

(Dot.)  In the default mode, this matches any character except a newline.  If
the DOTALL flag has been specified, this matches any character
including a newline.

while

print(t.select('dt .pre'))

outputs

[.]

what does the pattern string do in this line of code.


问:
Canvas resize photoshop script
Would it be possible to write a script to resize each image to the closest round number (for example if the original image is 791x1265px then it could be resized to 800x1300px)

Thanks!

答:
Pretty Easy and small script can do it :) Enjoy

Note : You have two choices for script; before running script either use static base value (default) or if you want to add prompt on each run then uncomment below line of var base and comment the var base line :) Hope that is what you were looking :)

```<code>    //get Original Ruler Units;
var origRuler = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;

    //get Active document scales
var origWidth = app.activeDocument.width;
var origHeight = app.activeDocument.height;

    //define base
var base = 100; //change your base like 10;100 etc; use below code to make a prompt on each run;
//var base = prompt("Enter Your Base number",""); //use this code if you want prompt for each run . uncomment by rermoving first two "//"

    //magical Mathematics XD
var roundWidth = Math.ceil(origWidth / base) * base;
var roundHeight = Math.ceil(origHeight / base) * base;

    //resize canvas
app.activeDocument.resizeCanvas (roundWidth, roundHeight);

    //Restores Original Ruler Units;
app.preferences.rulerUnits = origRuler;
</code>```

Edit: Updated script to avoid ruler units conflicts and changed Math.round to Math.ceil as per @Sergey Suggestion!

Title: Canvas resize photoshop script

Body:
Pretty Easy and small script can do it :) Enjoy

Note : You have two choices for script; before running script either use static base value (default) or if you want to add prompt on each run then uncomment below line of var base and comment the var base line :) Hope that is what you were looking :)

    //get Original Ruler Units;
var origRuler = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;

    //get Active document scales
var origWidth = app.activeDocument.width;
var origHeight = app.activeDocument.height;

    //define base
var base = 100; //change your base like 10;100 etc; use below code to make a prompt on each run;
//var base = prompt("Enter Your Base number",""); //use this code if you want prompt for each run . uncomment by rermoving first two "//"

    //magical Mathematics XD
var roundWidth = Math.ceil(origWidth / base) * base;
var roundHeight = Math.ceil(origHeight / base) * base;

    //resize canvas
app.activeDocument.resizeCanvas (roundWidth, roundHeight);

    //Restores Original Ruler Units;
app.preferences.rulerUnits = origRuler;

Edit: Updated script to avoid ruler units conflicts and changed Math.round to Math.ceil as per @Sergey Suggestion!


问:
How to edit "Reference Resolution" by script in Unity?
I want to change Reference Resolutuion with C# script in real time game, how can I make it?

Because I want to scale my controls with easiest way

答:
You cannot set reference resolution, but can caculate and set the Scale Factor with UISclleMode: Constant Pixel Size.

```<code>void SetReferenceResolution(Vector2 m_ReferenceResolution,float m_MatchWidthOrHeight = 1f)
{
    private const float kLogBase = 2;
    float logWidth = Mathf.Log(screenSize.x / m_ReferenceResolution.x, kLogBase);
    float logHeight = Mathf.Log(screenSize.y / m_ReferenceResolution.y, kLogBase);
    float logWeightedAverage = Mathf.Lerp(logWidth, logHeight, m_MatchWidthOrHeight);
    GetComponent<Canvas>().scaleFactor = Mathf.Pow(kLogBase, logWeightedAverage);
}
</code>```

Body:
You cannot set reference resolution, but can caculate and set the Scale Factor with UISclleMode: Constant Pixel Size.

void SetReferenceResolution(Vector2 m_ReferenceResolution,float m_MatchWidthOrHeight = 1f)
{
    private const float kLogBase = 2;
    float logWidth = Mathf.Log(screenSize.x / m_ReferenceResolution.x, kLogBase);
    float logHeight = Mathf.Log(screenSize.y / m_ReferenceResolution.y, kLogBase);
    float logWeightedAverage = Mathf.Lerp(logWidth, logHeight, m_MatchWidthOrHeight);
    GetComponent<Canvas>().scaleFactor = Mathf.Pow(kLogBase, logWeightedAverage);
}


问:
kotlin coroutine withTimeout does not cancel when using withContext to get non-blocking code
I am using withContext to transform a function into a suspending function which does not block the calling thread.
For this I used https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761 as reference.

Now I would like to invoke this function with a timeout. For this I use withTimeout to call the function as such:

```<code>@Test
internal fun timeout() {
    runBlocking {
        logger.info("launching")
        try {
            withTimeout(1000) {
                execute()
            }
        } catch (e: TimeoutCancellationException) {
            logger.info("timed out", e)
        }
    }
}

private suspend fun execute() {
    withContext(Dispatchers.IO) {
        logger.info("sleeping")
        Thread.sleep(2000)
    }
}
</code>```

So what I would expect is that after 1000 millis the async launched coroutine is cancelled and the TimeoutCancellationException is thrown.

But what happens is that the full 2000 millis pass and when the coroutine is completed the exception is thrown:

14:46:29.231 [main @coroutine#1] INFO  b.t.c.c.CoroutineControllerTest
  - launching

  14:46:29.250 [DefaultDispatcher-worker-1 @coroutine#1] INFO  b.t.c.c.CoroutineControllerTest - sleeping

  14:46:31.261 [main@coroutine#1] INFO  b.t.c.c.CoroutineControllerTest - timed out
  kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for
  1000 ms   at
  kotlinx.coroutines.TimeoutKt.TimeoutCancellationException(Timeout.kt:128)
    at kotlinx.coroutines.TimeoutCoroutine.run(Timeout.kt:94)   at
  kotlinx.coroutines.EventLoopImplBase$DelayedRunnableTask.run(EventLoop.kt:307)
    at
  kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.kt:116)
    at kotlinx.coroutines.DefaultExecutor.run(DefaultExecutor.kt:68)    at
  java.lang.Thread.run(Thread.java:748)

Am I using something wrong?

Or perhaps this is the intended behavior? In the documentation the counter also gets to 2 which means 1500 millis have passed before the coroutine is cancelled:
https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/cancellation-and-timeouts.md#timeout

答:
After rereading the documentation on cancellation it seems coroutines have to cooperate to be cancellable:

Coroutine cancellation is cooperative. A coroutine code has to
  cooperate to be cancellable.

https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html#cancellation-is-cooperative

I also found that threads by design do not get interrupted:

Cancelling a coroutine does not interrupt a thread. This is done so by
  design, because, unfortunately, many Java libraries incorrectly
  operate in interrupted threads.

https://discuss.kotlinlang.org/t/calling-blocking-code-in-coroutines/2368/6

This explains why the code waits for the sleep to finish.

This also means that it is not possible to use withTimeout on a coroutine that blocks the thread to add a timeout.

When using a non-blocking library which returns futures the withTimeout can be used as outlined here:

In order to properly integrate with cancellation,
  CompletableFuture.await() uses the same convention as all future
  combinators do — it cancels the underlying future if the await call
  itself is cancelled.

https://medium.com/@elizarov/futures-cancellation-and-coroutines-b5ce9c3ede3a

Side note on the example from the documentation:
By adding log statements to the delay/timeout example I found that only 1300 millis pass so delay works perfectly with withTimeout.

08:02:24.736 [main @coroutine#1] INFO  b.t.c.c.CoroutineControllerTest
  - I'm sleeping 0 ...

  08:02:25.242 [main @coroutine#1] INFO  b.t.c.c.CoroutineControllerTest - I'm sleeping 1 ...

  08:02:25.742 [main @coroutine#1] INFO  b.t.c.c.CoroutineControllerTest - I'm
  sleeping 2 ...

  08:02:26.041 [main @coroutine#1] INFO  b.t.c.c.CoroutineControllerTest - cancelled

Body:
I am using withContext to transform a function into a suspending function which does not block the calling thread.
For this I used https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761 as reference.

Now I would like to invoke this function with a timeout. For this I use withTimeout to call the function as such:

@Test
internal fun timeout() {
    runBlocking {
        logger.info("launching")
        try {
            withTimeout(1000) {
                execute()
            }
        } catch (e: TimeoutCancellationException) {
            logger.info("timed out", e)
        }
    }
}

private suspend fun execute() {
    withContext(Dispatchers.IO) {
        logger.info("sleeping")
        Thread.sleep(2000)
    }
}

So what I would expect is that after 1000 millis the async launched coroutine is cancelled and the TimeoutCancellationException is thrown.

But what happens is that the full 2000 millis pass and when the coroutine is completed the exception is thrown:

14:46:29.231 [main @coroutine#1] INFO  b.t.c.c.CoroutineControllerTest
  - launching

  14:46:29.250 [DefaultDispatcher-worker-1 @coroutine#1] INFO  b.t.c.c.CoroutineControllerTest - sleeping

  14:46:31.261 [main@coroutine#1] INFO  b.t.c.c.CoroutineControllerTest - timed out
  kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for
  1000 ms   at
  kotlinx.coroutines.TimeoutKt.TimeoutCancellationException(Timeout.kt:128)
    at kotlinx.coroutines.TimeoutCoroutine.run(Timeout.kt:94)   at
  kotlinx.coroutines.EventLoopImplBase$DelayedRunnableTask.run(EventLoop.kt:307)
    at
  kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.kt:116)
    at kotlinx.coroutines.DefaultExecutor.run(DefaultExecutor.kt:68)    at
  java.lang.Thread.run(Thread.java:748)

Am I using something wrong?

Or perhaps this is the intended behavior? In the documentation the counter also gets to 2 which means 1500 millis have passed before the coroutine is cancelled:
https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/cancellation-and-timeouts.md#timeout


问:
Python app to make a random prime number between 10^300 and 10^301
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

```<code>
import random , math
check_prime = 0</p>

<p>print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1<br>
    return True</p>

<p>while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break
```

答: Since you are handling extremely large numbers, you should really build on what clever people already did for you. Given that you need to know for sure your number is a prime (Miller Rabin is out), and you do want a random prime (not of a specific structure), I would suggest AKS. I am not sure how to optimize your numbers under test, but just choosing a random number might be okay given the speed of the primality test.

Body:
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

import random , math
check_prime = 0

print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1

    return True

while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break


答: It seems that you just want to: os.system(f'mkdir -p {FolderName}')

Title: Making a folder directory from a text file using a python script

Body:
I have a text file with hundreds of lines, each line contains a number to represent the level the folder/file should be on and a folder/file name. Because the  hierarchy is too large I want to make a script to automate making this directory/sub directory.

Example text file

 .0.  Folder Name a
  .1. Folder Name b
   .2. Folder Name c
   .2. Folder Name c2
  .1. Folder Name d
   .2. Folder Name e
   .2. Folder Name e2
    .3. Folder Name f

I assume I need to read line by line and use os.mkdir, but I don't know how to step down a directory level.

#path of file
import os

with open('Tree.txt', 'r') as t:
 for line in t:
  readline(.{Level}. {FolderName})
    if Level == '0'
     os.mkdir(FolderName)
    else if Level == '1'
     # go down and os.mkdir(FolderName)


问:
The GPIO folder is deleted when the same GPIO is exported again
I am basically exporting any gpios in my application. I started to implement this on the beaglebone black. After having no problem, I passed onto implementing the application on beaglebone blue. So, I realized that the application can run for the first time, then it fails for the second time. Afterwards, it again can run for the third time.

After a little bit of search, I realized the problem is occurring when exporting the any gpio on beaglebone blue, not only it does not let overwriting desired GPIO value, but it also deletes existing gpio. As an example, simple echo 23 > /sys/class/gpio/export command gives the output on beaglebone black and beaglebone blue as follows:

Beaglebone Black (3.8.13-bone86)

```<code>root@beaglebone# echo 23 > /sys/class/gpio/export
root@beaglebone# ls /sys/class/gpio/
export  gpio23  gpiochip0  gpiochip32  gpiochip64  gpiochip96  unexport
root@beaglebone# echo 23 > /sys/class/gpio/export
bash: echo: write error: Device or resource busy
root@beaglebone# ls /sys/class/gpio/
export  gpio23  gpiochip0  gpiochip32  gpiochip64  gpiochip96  unexport
</code>```

Beaglebone Blue (4.9.105-ti-rt-r113)

```<code>root@beaglebone# echo 23 > /sys/class/gpio/export
root@beaglebone# ls /sys/class/gpio/
export  gpio23  gpiochip0  gpiochip32  gpiochip64  gpiochip96  unexport
root@beaglebone# echo 23 > /sys/class/gpio/export
bash: echo: write error: Operation not permitted
root@beaglebone# ls /sys/class/gpio/
export  gpiochip0  gpiochip32  gpiochip64  gpiochip96  unexport
</code>```

So, how can I get rid of this problem on beaglebone blue ?

答:
I repeated this 'bug' in BeagleBone Black (4.14.71-ti-r80).

It was occurring in some C++ copied from the excellent Exploring BeagleBone book by Derek Molloy Issue 1, which was written when the 3.8 kernel was the latest.

I checked new version of the book (released this year), but no mention of this issue.

I 'fixed' it by putting a test for the gpio# directory existence, before writing the gpio number to the export sysfs file.

I.e. I checked for the existence of '/sys/class/gpio/gpio7'

Before writing 7 to '/sys/class/gpio/export'

I changed the existing exportGPIO function in Molloy's GPIO.cpp from:

```<code>int GPIO::exportGPIO(){
    return write(GPIO_PATH, "export", this->number);
}
</code>```

to:

```<code>int GPIO::exportGPIO(){
    // APM - 2019-05-27 - export twice kills it

    if (checkDirectoryExists(GPIO_PATH + this->name)) {
        cout << std::string("GPIO: export ") + GPIO_PATH + this->name + " already exists" << endl;
        return 0;
    }
    return write(GPIO_PATH, "export", this->number);
}
</code>```

The checkDirectoryExists function I wrote based on a stat() call.

A similar approach should be quite simple in a shell script.

Body:
I am basically exporting any gpios in my application. I started to implement this on the beaglebone black. After having no problem, I passed onto implementing the application on beaglebone blue. So, I realized that the application can run for the first time, then it fails for the second time. Afterwards, it again can run for the third time.

After a little bit of search, I realized the problem is occurring when exporting the any gpio on beaglebone blue, not only it does not let overwriting desired GPIO value, but it also deletes existing gpio. As an example, simple echo 23 > /sys/class/gpio/export command gives the output on beaglebone black and beaglebone blue as follows:

Beaglebone Black (3.8.13-bone86)

root@beaglebone# echo 23 > /sys/class/gpio/export
root@beaglebone# ls /sys/class/gpio/
export  gpio23  gpiochip0  gpiochip32  gpiochip64  gpiochip96  unexport
root@beaglebone# echo 23 > /sys/class/gpio/export
bash: echo: write error: Device or resource busy
root@beaglebone# ls /sys/class/gpio/
export  gpio23  gpiochip0  gpiochip32  gpiochip64  gpiochip96  unexport

Beaglebone Blue (4.9.105-ti-rt-r113)

root@beaglebone# echo 23 > /sys/class/gpio/export
root@beaglebone# ls /sys/class/gpio/
export  gpio23  gpiochip0  gpiochip32  gpiochip64  gpiochip96  unexport
root@beaglebone# echo 23 > /sys/class/gpio/export
bash: echo: write error: Operation not permitted
root@beaglebone# ls /sys/class/gpio/
export  gpiochip0  gpiochip32  gpiochip64  gpiochip96  unexport

So, how can I get rid of this problem on beaglebone blue ?

Body:
I repeated this 'bug' in BeagleBone Black (4.14.71-ti-r80).

It was occurring in some C++ copied from the excellent Exploring BeagleBone book by Derek Molloy Issue 1, which was written when the 3.8 kernel was the latest.

I checked new version of the book (released this year), but no mention of this issue.

I 'fixed' it by putting a test for the gpio# directory existence, before writing the gpio number to the export sysfs file.

I.e. I checked for the existence of '/sys/class/gpio/gpio7'

Before writing 7 to '/sys/class/gpio/export'

I changed the existing exportGPIO function in Molloy's GPIO.cpp from:

int GPIO::exportGPIO(){
    return write(GPIO_PATH, "export", this->number);
}

to:

int GPIO::exportGPIO(){
    // APM - 2019-05-27 - export twice kills it

    if (checkDirectoryExists(GPIO_PATH + this->name)) {
        cout << std::string("GPIO: export ") + GPIO_PATH + this->name + " already exists" << endl;
        return 0;
    }
    return write(GPIO_PATH, "export", this->number);
}

The checkDirectoryExists function I wrote based on a stat() call.

A similar approach should be quite simple in a shell script.


问:
Is there a different way to convert to hexadecimal?
I'm trying to write some information to a special device that requires me to encode the string and I quote " an even number of bytes to write (1-32, base 10) "

The example string provided "DE AD BE EF CA FE" (works).
I have converted my string to decimal and from decimal to hexadecimal.

```<code>string TextToConvert = "Test Andrei";
            TextToConvert=ConvertStringToHex(TextToConvert, Encoding.UTF8);

            List<char> Chars = TextToConvert.ToCharArray().ToList();
            string CharValue = "";
            string secondHexConvert = "";
            foreach(char c in Chars)
            {
                CharValue+=Convert.ToInt32(c);
                secondHexConvert+=Convert.ToString(c, 16)+" ";
            }
            string hexValue = String.Format("{0:X}", CharValue)+" ";
</code>```

I have found on internet a tool that converts to hexadecimal that works. The problem is that I can't figure what type of encoding is that. The site is this: https://codebeautify.org/decimal-hex-converter
from decimal "841011151163265110100114101105" to hex = "a9d741e82c990000000000000"

答:
To convert such a big integer to a hexadecimal string, use the aptly named BigInteger type:

```<code>var num = BigInteger.Parse("841011151163265110100114101105");
string hex = num.ToString("X");
Console.WriteLine(hex);
</code>```

will output:

```<code>0A9D741E82C98FC6A137B75371
</code>```

but here's a snag, the output you showed in your question is somewhat different, let me show it together with what the code above produces:

```<code>0A9D741E82C98FC6A137B75371
 a9d741e82c990000000000000
</code>```

As you can see, the numbers start the same but your example then ends up with lots of zeroes.

The only way I understand this could happen is that they're in fact not using a type that can hold that many significant digits, so you get a rounding error.

Many of the dynamic programming languages allows you to use floating point numbers and integers interchangeably, I guess this is what happened, a floating point type that can only hold 17-18 significant digits or some such was used, and you lost precision. .NET, however, doesn't have built-in support for converting floating point types to hexadecimal.

You can see that .NET produces the exact value by converting back:

```<code>Console.WriteLine(BigInteger.Parse(hex, System.Globalization.NumberStyles.HexNumber));
</code>```

outputs:

```<code>841011151163265110100114101105
</code>```

In other words, I'm not sure you can get the exact same results in .NET.

Corollary: Don't use that site for this kind of conversion!

Body:
I'm trying to write some information to a special device that requires me to encode the string and I quote " an even number of bytes to write (1-32, base 10) "

The example string provided "DE AD BE EF CA FE" (works).
I have converted my string to decimal and from decimal to hexadecimal.

string TextToConvert = "Test Andrei";
            TextToConvert=ConvertStringToHex(TextToConvert, Encoding.UTF8);

            List<char> Chars = TextToConvert.ToCharArray().ToList();
            string CharValue = "";
            string secondHexConvert = "";
            foreach(char c in Chars)
            {
                CharValue+=Convert.ToInt32(c);
                secondHexConvert+=Convert.ToString(c, 16)+" ";
            }
            string hexValue = String.Format("{0:X}", CharValue)+" ";

I have found on internet a tool that converts to hexadecimal that works. The problem is that I can't figure what type of encoding is that. The site is this: https://codebeautify.org/decimal-hex-converter
from decimal "841011151163265110100114101105" to hex = "a9d741e82c990000000000000"

Body:
To convert such a big integer to a hexadecimal string, use the aptly named BigInteger type:

var num = BigInteger.Parse("841011151163265110100114101105");
string hex = num.ToString("X");
Console.WriteLine(hex);

will output:

0A9D741E82C98FC6A137B75371

but here's a snag, the output you showed in your question is somewhat different, let me show it together with what the code above produces:

0A9D741E82C98FC6A137B75371
 a9d741e82c990000000000000

As you can see, the numbers start the same but your example then ends up with lots of zeroes.

The only way I understand this could happen is that they're in fact not using a type that can hold that many significant digits, so you get a rounding error.

Many of the dynamic programming languages allows you to use floating point numbers and integers interchangeably, I guess this is what happened, a floating point type that can only hold 17-18 significant digits or some such was used, and you lost precision. .NET, however, doesn't have built-in support for converting floating point types to hexadecimal.

You can see that .NET produces the exact value by converting back:

Console.WriteLine(BigInteger.Parse(hex, System.Globalization.NumberStyles.HexNumber));

outputs:

841011151163265110100114101105

In other words, I'm not sure you can get the exact same results in .NET.

Corollary: Don't use that site for this kind of conversion!


问:
Merge 'with' and 'whereHas' in Laravel 5
I have this code in Laravel 5, using Eloquent, which is working perfectly:

```<code>$filterTask = function($query) use ($id) {
    $query->where('taskid', $id);
};

User::whereHas('submissions', $filterTask)->with(['submissions' => $filterTask])->get();
</code>```

Basically the goal is to get only those users with their filtered submissions, which has any of them.
However, it seems wasting to run both whereHas and with methods with the same callback function. Is there a way to simplify it?

Thanks.

答:
I want to extend the answer from @lukasgeiter using static functions.

```<code>public static function withAndWhereHas($relation, $constraint){
    return (new static)->whereHas($relation, $constraint)
        ->with([$relation => $constraint]);
}
</code>```

Usage is the same

```<code>User::withAndWhereHas('submissions', function($query) use ($id){
    $query->where('taskid', $id);
})->get();
</code>```

Body:
I have this code in Laravel 5, using Eloquent, which is working perfectly:

$filterTask = function($query) use ($id) {
    $query->where('taskid', $id);
};

User::whereHas('submissions', $filterTask)->with(['submissions' => $filterTask])->get();

Basically the goal is to get only those users with their filtered submissions, which has any of them.
However, it seems wasting to run both whereHas and with methods with the same callback function. Is there a way to simplify it?

Thanks.

Body:
I want to extend the answer from @lukasgeiter using static functions.

public static function withAndWhereHas($relation, $constraint){
    return (new static)->whereHas($relation, $constraint)
        ->with([$relation => $constraint]);
}

Usage is the same

User::withAndWhereHas('submissions', function($query) use ($id){
    $query->where('taskid', $id);
})->get();


问:
How can I insert a scalar value and a binary value to a layer (last layer) in keras?
I am trying to modify the network which is implemented here. This network uses chest x ray images as input and classifies it into 14 categories (13 types of diseases and no finding). The network does not take the patient age and gender as an input. So I want to provide the network with that information too. In short At the last 3 layers of the network is like the following:

```<code>bn (BatchNormalization)         (None, 7, 7, 1024)   4096        conv5_block16_concat[0][0]
__________________________________________________________________________________________________
avg_pool (GlobalAveragePooling2 (None, 1024)         0           bn[0][0]
__________________________________________________________________________________________________
predictions (Dense)             (None, 14)           14350       avg_pool[0][0]
</code>```

So what I have done so far is the following:
I simply pop the last dense layer using model_vgg16.layers.pop().

Then as expexted the network turns into:

```<code>bn (BatchNormalization)         (None, 7, 7, 1024)   4096        conv5_block16_concat[0][0]
__________________________________________________________________________________________________
avg_pool (GlobalAveragePooling2 (None, 1024)         0           bn[0][0]
</code>```

I know that I can add a layer using:

```<code>new_layer = Dense(14, activation='softmax', name='my_dense')

inp = model.input
out = new_layer(model.layers[-1].output)

model2 = Model(inp, out)
</code>```

But I do not know how to add a layer that takes the inputs from previous layer together with 1 scalar value (age [0:100]), and one binary value gender [0:1].

So How can I add a last layer that takes inputs from previous layer together with 1 scalar value and 1 binary value?

Edit: The base model I am using is DenseNet121. The some final layers looks like this:

EDIT
The way I load the model is the following:

```<code>cp = ConfigParser()
cp.read(config_file)

# default config
output_dir = cp["DEFAULT"].get("output_dir")
base_model_name = cp["DEFAULT"].get("base_model_name")
class_names = cp["DEFAULT"].get("class_names").split(",")
image_source_dir = cp["DEFAULT"].get("image_source_dir")
image_dimension = cp["TRAIN"].getint("image_dimension")

output_weights_name = cp["TRAIN"].get("output_weights_name")
weights_path = os.path.join(output_dir, output_weights_name)
best_weights_path = os.path.join(output_dir, f"best_{output_weights_name}")
model_weights_path = best_weights_path

model_factory = ModelFactory()
model = model_factory.get_model(
    class_names,
    model_name=base_model_name,
    use_base_weights=False,
    weights_path=model_weights_path)

</code>```

Now the model is in variable model.
Then as suggested I do

```<code>x = model.output
flat1 = Flatten()(x)
</code>```

and get this error:

ValueError: Input 0 is incompatible with layer flatten_27: expected min_ndim=3, found ndim=2

When I repeat the same thing after removing the last layer using model.layers.pop()

I still get the same error? Even though I have spent couple of hours cannot overcome that problem. So how can this be done?

答:
Issue is solved by first removing the last layer (prediction layer) by

model_original.layers.pop()

Then defining another model which is the replica of the original model except the last layer

model2 = keras.Model(model_original.input, model_original.layers[-1].output)

after that the input, which includes the age is defined

age = layers.Input(shape=(1,))

Next, age input and the last layer of the previously defined network is concatenated using

x = model2.output
concatenated = layers.concatenate([x, age])

In th final step, a prediction layer is added after the concatenation to complete the network

output = Dense(14, activation='linear')(concatenated)
model3 = keras.Model(inputs=[model_original.input, age], outputs=output)

So the final layers of the design looks like that:

Body:
I am trying to modify the network which is implemented here. This network uses chest x ray images as input and classifies it into 14 categories (13 types of diseases and no finding). The network does not take the patient age and gender as an input. So I want to provide the network with that information too. In short At the last 3 layers of the network is like the following:

bn (BatchNormalization)         (None, 7, 7, 1024)   4096        conv5_block16_concat[0][0]
__________________________________________________________________________________________________
avg_pool (GlobalAveragePooling2 (None, 1024)         0           bn[0][0]
__________________________________________________________________________________________________
predictions (Dense)             (None, 14)           14350       avg_pool[0][0]

So what I have done so far is the following:
I simply pop the last dense layer using model_vgg16.layers.pop().

Then as expexted the network turns into:

bn (BatchNormalization)         (None, 7, 7, 1024)   4096        conv5_block16_concat[0][0]
__________________________________________________________________________________________________
avg_pool (GlobalAveragePooling2 (None, 1024)         0           bn[0][0]

I know that I can add a layer using:

new_layer = Dense(14, activation='softmax', name='my_dense')

inp = model.input
out = new_layer(model.layers[-1].output)

model2 = Model(inp, out)

But I do not know how to add a layer that takes the inputs from previous layer together with 1 scalar value (age [0:100]), and one binary value gender [0:1].

So How can I add a last layer that takes inputs from previous layer together with 1 scalar value and 1 binary value?

Edit: The base model I am using is DenseNet121. The some final layers looks like this:

EDIT
The way I load the model is the following:

cp = ConfigParser()
cp.read(config_file)

# default config
output_dir = cp["DEFAULT"].get("output_dir")
base_model_name = cp["DEFAULT"].get("base_model_name")
class_names = cp["DEFAULT"].get("class_names").split(",")
image_source_dir = cp["DEFAULT"].get("image_source_dir")
image_dimension = cp["TRAIN"].getint("image_dimension")

output_weights_name = cp["TRAIN"].get("output_weights_name")
weights_path = os.path.join(output_dir, output_weights_name)
best_weights_path = os.path.join(output_dir, f"best_{output_weights_name}")
model_weights_path = best_weights_path

model_factory = ModelFactory()
model = model_factory.get_model(
    class_names,
    model_name=base_model_name,
    use_base_weights=False,
    weights_path=model_weights_path)

Now the model is in variable model.
Then as suggested I do

x = model.output
flat1 = Flatten()(x)

and get this error:

ValueError: Input 0 is incompatible with layer flatten_27: expected min_ndim=3, found ndim=2

When I repeat the same thing after removing the last layer using model.layers.pop()

I still get the same error? Even though I have spent couple of hours cannot overcome that problem. So how can this be done?