问:
Print sequences with prime sum
Given an integer n, I want to find two permutations of the numbers 1 to n (inclusive) such that the sum of numbers from the two permutations at any given index is always prime.

For example:

```<code>   n = 5

      1 2 3 4 5
      1 5 4 3 2

   n = 8

      1 2 3 4 5 6 7 8
      2 1 4 3 8 7 6 5
</code>```

答:
Find the smallest number k>=1 such that n+k is prime.

Form pairs: (n,k), (n-1, k+1), ..., (k,n).

If k>1, repeat on the range [1,k].

E.g., n=5: 5+2=7, so we have:

```<code>5, 4, 3, 2
2, 3, 4, 5
</code>```

Then we repeat for 1.

E.g. n=8: 8+3 = 11, so we have:

```<code>8, 7, 6, 5, 4, 3
3, 4, 5, 6, 7, 8
</code>```

Leaving us with 2:

```<code>1, 2
2, 1
</code>```

By Bertrand's postulate aka Chebyshev's theorem, for any n>1 there is a prime p s.t. n < p < 2n, and for n=1 we have 1+1=2, so we will always be able to do this.

Title: Print sequences with prime sum

Body:
Given an integer n, I want to find two permutations of the numbers 1 to n (inclusive) such that the sum of numbers from the two permutations at any given index is always prime.

For example:

   n = 5

      1 2 3 4 5
      1 5 4 3 2

   n = 8

      1 2 3 4 5 6 7 8
      2 1 4 3 8 7 6 5

Body:
Find the smallest number k>=1 such that n+k is prime.

Form pairs: (n,k), (n-1, k+1), ..., (k,n).

If k>1, repeat on the range [1,k].

E.g., n=5: 5+2=7, so we have:

5, 4, 3, 2
2, 3, 4, 5

Then we repeat for 1.

E.g. n=8: 8+3 = 11, so we have:

8, 7, 6, 5, 4, 3
3, 4, 5, 6, 7, 8

Leaving us with 2:

1, 2
2, 1

By Bertrand's postulate aka Chebyshev's theorem, for any n>1 there is a prime p s.t. n < p < 2n, and for n=1 we have 1+1=2, so we will always be able to do this.


来源: stackexchange

问:
Get text from ".txt" file and save it in String variable dart
I have a ".txt" file called "bio.txt" inside the Document folder of my application.
I want to read its content and store it inside a String variable.
My problem is that the "reading action" is a "Future" function and I have some troubles to save its value in a "String".

I read the file with :

Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}

Future<File> _localFile(String name) async {
  final path = await _localPath;
  return File('$path/$name');
}

Future<String> _read(String filename) async {
  try {
    final file = await _localFile(filename);

    // Read the file.
    return await file.readAsString();
  } catch (e) {
    // If encountering an error, return 0.
    return "Can't read";
  }
}
```

<p>And I would like to save it with :</p>

<pre class="lang-dart prettyprint-override"><code>String _bio = _read("bio.txt").then((value) => String);
</code>```

Do you know why this solution isn't working?
Any suggestion?

答:
Because the then of Futures won't return a value, it should be like this,

var _bio;

_read("bio.txt").then((value) {
  _bio = value;
});
```

<p>or by making the context <code>_bio</code> is in to an asynchronous one,</p>

<pre class="lang-dart prettyprint-override"><code>var _bio = await _read("bio.txt");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a ".txt" file called "bio.txt" inside the Document folder of my application.
I want to read its content and store it inside a String variable.
My problem is that the "reading action" is a "Future" function and I have some troubles to save its value in a "String".

I read the file with :

Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}

Future<File> _localFile(String name) async {
  final path = await _localPath;
  return File('$path/$name');
}

Future<String> _read(String filename) async {
  try {
    final file = await _localFile(filename);

    // Read the file.
    return await file.readAsString();
  } catch (e) {
    // If encountering an error, return 0.
    return "Can't read";
  }
}

And I would like to save it with :

String _bio = _read("bio.txt").then((value) => String);

Do you know why this solution isn't working?
Any suggestion?

Body:
Because the then of Futures won't return a value, it should be like this,

var _bio;

_read("bio.txt").then((value) {
  _bio = value;
});

or by making the context _bio is in to an asynchronous one,

var _bio = await _read("bio.txt");


问:
Is variable inside of llvm BasicBlock visible for others?
Suppose we have a Function named hello.world, which contains two BasicBlock bb.1 and bb.2, for example:

```<code>i32 @hello.world(i32 %x)
bb.1:
  %a = i32 %x
bb.2:
  %b = i32 %a
  ret i32 %b
</code>```

Is variable %a in bb.1 visible for %b in bb.2 ?

答:
Your code is invalid, because bb.1 doesn't end with a terminator instruction. Have it end with br label %bb.2 and the answer would be yes.

Strictly speaking, variables defined in the given BB are visible from all BBs that are dominated by the given one.

Body:
Suppose we have a Function named hello.world, which contains two BasicBlock bb.1 and bb.2, for example:

i32 @hello.world(i32 %x)
bb.1:
  %a = i32 %x
bb.2:
  %b = i32 %a
  ret i32 %b

Is variable %a in bb.1 visible for %b in bb.2 ?


问:
Unrecognized options "sandbox, swagger" under "nelmio_api_doc". Available options are "areas", "documentation", "models"
I'm trying to implement a Rest API for an application I develop using Symfony 4.
After installing packages such as : nelmio/api-doc-bundle (my composer.json is pasted bellow), I am getting the following error :

InvalidConfigurationException Unrecognized options "sandbox, swagger" under "nelmio_api_doc". Available options are "areas",
  "documentation", "models"..

I'm trying to figure out what is happening for days now.
Please need help.

This is my composer.json :

```<code>{
  "type": "project",
  "license": "proprietary",
  "require": {
    "php": "^7.1.3",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "cocur/slugify": "^3.2",
    "dompdf/dompdf": "^0.8.3",
    "friendsofsymfony/oauth-server-bundle": "^1.6",
    "friendsofsymfony/rest-bundle": "^2.5",
    "friendsofsymfony/user-bundle": "~2.0",
    "inacho/php-credit-card-validator": "^1.0",
    "jms/serializer-bundle": "^3.3",
    "nelmio/api-doc-bundle": "^3.4",
    "sensio/framework-extra-bundle": "^5.3",
    "symfony/apache-pack": "^1.0",
    "symfony/asset": "4.2.*",
    "symfony/console": "4.2.*",
    "symfony/dotenv": "4.2.*",
    "symfony/expression-language": "4.2.*",
    "symfony/filesystem": "4.2.*",
    "symfony/finder": "4.2.*",
    "symfony/flex": "^1.1",
    "symfony/form": "4.2.*",
    "symfony/framework-bundle": "4.2.*",
    "symfony/monolog-bundle": "^3.1",
    "symfony/orm-pack": "*",
    "symfony/process": "4.2.*",
    "symfony/security-bundle": "4.2.*",
    "symfony/serializer-pack": "*",
    "symfony/swiftmailer-bundle": "^3.2",
    "symfony/translation": "4.2.*",
    "symfony/twig-bundle": "4.2.*",
    "symfony/validator": "4.2.*",
    "symfony/web-link": "4.2.*",
    "symfony/yaml": "4.2.*",
    "twig/extensions": "^1.5",
    "zircote/swagger-php": "*"
  },
  "require-dev": {
    "symfony/debug-pack": "*",
    "symfony/maker-bundle": "^1.0",
    "symfony/profiler-pack": "*",
    "symfony/test-pack": "*",
    "symfony/web-server-bundle": "4.2.*"
  },
  "config": {
    "preferred-install": {
      "*": "dist"
    },
    "sort-packages": true
  },
  "autoload": {
    "psr-4": {
      "App\\": "src/"
    }
  },
  "autoload-dev": {
    "psr-4": {
      "App\\Tests\\": "tests/"
    }
  },
  "replace": {
    "paragonie/random_compat": "2.*",
    "symfony/polyfill-ctype": "*",
    "symfony/polyfill-iconv": "*",
    "symfony/polyfill-php71": "*",
    "symfony/polyfill-php70": "*",
    "symfony/polyfill-php56": "*"
  },
  "scripts": {
    "auto-scripts": {
      "cache:clear": "symfony-cmd",
      "assets:install %PUBLIC_DIR%": "symfony-cmd"
    },
    "post-install-cmd": [
      "@auto-scripts"
    ],
    "post-update-cmd": [
      "@auto-scripts"
    ]
  },
  "conflict": {
    "symfony/symfony": "*"
  },
  "extra": {
    "symfony": {
      "allow-contrib": false,
      "require": "4.2.*"
    }
  }
}
</code>```

And this is my nelmio_api_doc.yaml

```<code>nelmio_api_doc:
  sandbox:
    enabled: true
    authentication:
      delivery: http
      type: bearer
    body_format:
      formats: [json, form] # array of enabled body formats,
      default_format: json
  swagger:
    api_base_path: /api
    swagger_version: "1.2"
    api_version: "0.1"
    info:
      title: API
      description: "REST API"
</code>```

I tried: composer update and composer install.

答:
You must have updated nelmio/api-doc-bundle from 2.x to 3.x.

Your configuration seems good for a 2.x version.
Make sure to follow this guide for migration to 3.x.

For a similar issue which faced, I replaced sandbox with documentation.

Similarly, by following the guide, you can replace the rest.

Most likely something similar to the following will work.

```<code>nelmio_api_doc:
  documentation: #<-- notice this change.
    enabled: true
    authentication:
      delivery: http
      type: bearer
    body_format:
      formats: [json, form] # array of enabled body formats,
      default_format: json

    api_base_path: /api
    swagger_version: "1.2"
    info:
      title: API
      description: "REST API"
      version: "0.1" # <-- notice this has been moved.

</code>```

Body:
I'm trying to implement a Rest API for an application I develop using Symfony 4.
After installing packages such as : nelmio/api-doc-bundle (my composer.json is pasted bellow), I am getting the following error :

InvalidConfigurationException Unrecognized options "sandbox, swagger" under "nelmio_api_doc". Available options are "areas",
  "documentation", "models"..

I'm trying to figure out what is happening for days now.
Please need help.

This is my composer.json :

{
  "type": "project",
  "license": "proprietary",
  "require": {
    "php": "^7.1.3",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "cocur/slugify": "^3.2",
    "dompdf/dompdf": "^0.8.3",
    "friendsofsymfony/oauth-server-bundle": "^1.6",
    "friendsofsymfony/rest-bundle": "^2.5",
    "friendsofsymfony/user-bundle": "~2.0",
    "inacho/php-credit-card-validator": "^1.0",
    "jms/serializer-bundle": "^3.3",
    "nelmio/api-doc-bundle": "^3.4",
    "sensio/framework-extra-bundle": "^5.3",
    "symfony/apache-pack": "^1.0",
    "symfony/asset": "4.2.*",
    "symfony/console": "4.2.*",
    "symfony/dotenv": "4.2.*",
    "symfony/expression-language": "4.2.*",
    "symfony/filesystem": "4.2.*",
    "symfony/finder": "4.2.*",
    "symfony/flex": "^1.1",
    "symfony/form": "4.2.*",
    "symfony/framework-bundle": "4.2.*",
    "symfony/monolog-bundle": "^3.1",
    "symfony/orm-pack": "*",
    "symfony/process": "4.2.*",
    "symfony/security-bundle": "4.2.*",
    "symfony/serializer-pack": "*",
    "symfony/swiftmailer-bundle": "^3.2",
    "symfony/translation": "4.2.*",
    "symfony/twig-bundle": "4.2.*",
    "symfony/validator": "4.2.*",
    "symfony/web-link": "4.2.*",
    "symfony/yaml": "4.2.*",
    "twig/extensions": "^1.5",
    "zircote/swagger-php": "*"
  },
  "require-dev": {
    "symfony/debug-pack": "*",
    "symfony/maker-bundle": "^1.0",
    "symfony/profiler-pack": "*",
    "symfony/test-pack": "*",
    "symfony/web-server-bundle": "4.2.*"
  },
  "config": {
    "preferred-install": {
      "*": "dist"
    },
    "sort-packages": true
  },
  "autoload": {
    "psr-4": {
      "App\\": "src/"
    }
  },
  "autoload-dev": {
    "psr-4": {
      "App\\Tests\\": "tests/"
    }
  },
  "replace": {
    "paragonie/random_compat": "2.*",
    "symfony/polyfill-ctype": "*",
    "symfony/polyfill-iconv": "*",
    "symfony/polyfill-php71": "*",
    "symfony/polyfill-php70": "*",
    "symfony/polyfill-php56": "*"
  },
  "scripts": {
    "auto-scripts": {
      "cache:clear": "symfony-cmd",
      "assets:install %PUBLIC_DIR%": "symfony-cmd"
    },
    "post-install-cmd": [
      "@auto-scripts"
    ],
    "post-update-cmd": [
      "@auto-scripts"
    ]
  },
  "conflict": {
    "symfony/symfony": "*"
  },
  "extra": {
    "symfony": {
      "allow-contrib": false,
      "require": "4.2.*"
    }
  }
}

And this is my nelmio_api_doc.yaml

nelmio_api_doc:
  sandbox:
    enabled: true
    authentication:
      delivery: http
      type: bearer
    body_format:
      formats: [json, form] # array of enabled body formats,
      default_format: json
  swagger:
    api_base_path: /api
    swagger_version: "1.2"
    api_version: "0.1"
    info:
      title: API
      description: "REST API"

I tried: composer update and composer install.

Body:
You must have updated nelmio/api-doc-bundle from 2.x to 3.x.

Your configuration seems good for a 2.x version.
Make sure to follow this guide for migration to 3.x.

For a similar issue which faced, I replaced sandbox with documentation.

Similarly, by following the guide, you can replace the rest.

Most likely something similar to the following will work.

nelmio_api_doc:
  documentation: #<-- notice this change.
    enabled: true
    authentication:
      delivery: http
      type: bearer
    body_format:
      formats: [json, form] # array of enabled body formats,
      default_format: json

    api_base_path: /api
    swagger_version: "1.2"
    info:
      title: API
      description: "REST API"
      version: "0.1" # <-- notice this has been moved.


问:
Check for true values for different keys in two different array items in JSON Validation
Consider if I have an array that looks something like the example below:

```<code>          {
            "id": 1,
            "published": true,
            "available": false
          },
          {
            "id": 2,
            "published": false,
            "available": true
          }
</code>```

There can be many items in the array, say up to 10. I  need to check all the items separately for published and available.
The JSON validation should check all the items and PASS if any of one of the array items has truevalue for published atleast once AND true value for available atleast once as well. It could be in the same item or different items. The validation should fail if any of these properties were not true even once in any of the array items. Any ideas on how could I get that done?
I have tried

anyOF: checks for one of the properties and passes the validation,

allOf: checks for every instance and fails validation for every instance it is false (need to pass even if it the key is true once),

contains: can be used only once in the validation and ends up checking for both the keys to be true in a single item.
Any suggestions on how can I get around this, would be really helpful!
Thanks.

答:
You can certainly use "contains" more than once -- just put it inside an "allOf" or "anyOf".  So, something like this?</p>

```<code>{
  "type": "array",
  "items": {
    "type": "object"
  },
  "allOf": [
    {
      "contains": {
        "properties": {
          "published": { "const": true }
        }
    },
    {
      "contains": {
        "properties": {
          "available": { "const": true }
        }
      }
    }
  ]
}
</code>```

Body:
Consider if I have an array that looks something like the example below:

          {
            "id": 1,
            "published": true,
            "available": false
          },
          {
            "id": 2,
            "published": false,
            "available": true
          }

There can be many items in the array, say up to 10. I  need to check all the items separately for published and available.
The JSON validation should check all the items and PASS if any of one of the array items has truevalue for published atleast once AND true value for available atleast once as well. It could be in the same item or different items. The validation should fail if any of these properties were not true even once in any of the array items. Any ideas on how could I get that done?
I have tried

anyOF: checks for one of the properties and passes the validation,

allOf: checks for every instance and fails validation for every instance it is false (need to pass even if it the key is true once),

contains: can be used only once in the validation and ends up checking for both the keys to be true in a single item.
Any suggestions on how can I get around this, would be really helpful!
Thanks.

Body:
You can certainly use "contains" more than once -- just put it inside an "allOf" or "anyOf".  So, something like this?

{
  "type": "array",
  "items": {
    "type": "object"
  },
  "allOf": [
    {
      "contains": {
        "properties": {
          "published": { "const": true }
        }
    },
    {
      "contains": {
        "properties": {
          "available": { "const": true }
        }
      }
    }
  ]
}


问:
Gradle can execute TornadoFX app without main() while IntelliJ can't...why?
I've just set up a simple Hello World project with the following code in Kotlin + TornadoFX with IntelliJ IDEA Community.  For some reason, if I type gradlew run at the command line, it manages to run the app by loading the MainApp class directly, but IntelliJ insists "class MainApp has no main() method", refusing to launch the app unless I explicitly write a main() function.  Why is this?  How can I (or can I at all) get IntelliJ to run the app the same way gradle is managing?

Here's the Kotlin source file

```<code>import tornadofx.*

// Define application with main View `Main`
class MainApp : App(Main::class)

// Define the view to display
class Main : View() {

    // override the root view with our container with the label within
    override val root = hbox {
        // use the tornado kotlin dsl to add a label and set the text
        label {
            text = "Hello World"
        }
    }
}
</code>```

And here's build.gradle.kts

```<code>plugins {
    kotlin("jvm") version "1.3.72"
    application
    id("org.openjfx.javafxplugin") version "0.0.8"
}

javafx {
    // Declare the javafx modules we need to use
    modules("javafx.controls")
}

group = "org.example"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    implementation("no.tornado:tornadofx:1.7.20")
}

application {
    mainClassName = "MainApp"
}

tasks {
    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
}
</code>```

答:
After downloading your test project there are a couple of things I see:

Your run configuration for "MainApp" is not using gradle but is using an Intellij managed project configured to build and run the application.

MainApp.kt does not have a "main" function for Intellij to run

I'm not an expert on Intellij or gradle so I can't explain why you can launch with gradle without main function but can't do so from Intellij.  I expect that gradle can somehow inject a main function that can execute the JavaFX Application class defined by your MainApp (TornadoFX App class extends JavaFX Application class).

To get this working, you can either setup a run configuration to use gradle or add the main function to MyApp.kt and update the MainApp run configuration.

Use Gradle to Run from Intellij

Click the gradle tab on the right hand side of Intellij

Expand the kotlin-gradle configuration for Tasks -> application
Note: You may need to click the "refresh" button on the top left of the gradle panel to refresh the list of available tasks.

Double click "run" and the gradle run task will be executed

When you do this, Intellij will automatically add a new configuration "test-project [run]"

Screenshot of Gradle Panel

Note: It is still a good idea to add the main function as described below and update your build.gradle.kts to use "MainAppKt".  This will give you some flexibility in launching your application with Java 9+ without requiring module definitions (i.e. non-modular appplication)

Use Intellij to Run

Add the following code to your MainApp.kt

fun main(args: Array<String>) {
    launch<MainApp>(args)
}
```

<ol start="2">
<li>Edit your existing "MainApp" run configuration and change the Main class to "MainAppKt"</li>
<li>Click Ok to save and you can now run the "MainApp" configuration</li>
</ol>

<p><br/>
<strong>Last note</strong>: If you are using Java 9+, you need to use a snapshot build of TornadoFX otherwise, you will run into problems.</p>

<p>Add the snapshot repository to your respoitories section with</p>

<pre class="lang-kotlin prettyprint-override"><code>maven("https://oss.sonatype.org/content/repositories/snapshots")
</code>```

And update the TornadoFX version to "2.0.0-SNAPSHOT"

implementation("no.tornado:tornadofx:2.0.0-SNAPSHOT")
```

<p><br/><br/></p>

<p><strong>Old Answer</strong></p>

<p>You are missing the mainClassName setting in your build.gradle.kts:</p>

<pre class="lang-kts prettyprint-override"><code>application {
    mainClassName = "com.example.demo.app.MyApp"
}
</code>```

Some notes:

If you have a main function that launches your app such as below, then you need to append "Kt" to the main class name where the function is located since a new class is created by kotlin to hold the static main function for the JVM. For example, if in the MyApp.kt file I had the main function below, I would need to use "com.example.demo.app.MyAppKt" in order to call the main function to run the application.

fun main(args: Array<String>) {
    launch<MyApp>(args)
}
```

The syntax for the mainClassName is different depending on the gradle version and the language. I normally use groovy so I had to look it up for kts.  The current gradle version 6.4 uses a different syntax than 6.3.  The syntax I provided is for 6.3.  I'm not sure when the change was made so you may need to verify the correct syntax for your gradle version.

Body:
I've just set up a simple Hello World project with the following code in Kotlin + TornadoFX with IntelliJ IDEA Community.  For some reason, if I type gradlew run at the command line, it manages to run the app by loading the MainApp class directly, but IntelliJ insists "class MainApp has no main() method", refusing to launch the app unless I explicitly write a main() function.  Why is this?  How can I (or can I at all) get IntelliJ to run the app the same way gradle is managing?

Here's the Kotlin source file

import tornadofx.*

// Define application with main View `Main`
class MainApp : App(Main::class)

// Define the view to display
class Main : View() {

    // override the root view with our container with the label within
    override val root = hbox {
        // use the tornado kotlin dsl to add a label and set the text
        label {
            text = "Hello World"
        }
    }
}

And here's build.gradle.kts

plugins {
    kotlin("jvm") version "1.3.72"
    application
    id("org.openjfx.javafxplugin") version "0.0.8"
}

javafx {
    // Declare the javafx modules we need to use
    modules("javafx.controls")
}

group = "org.example"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    implementation("no.tornado:tornadofx:1.7.20")
}

application {
    mainClassName = "MainApp"
}

tasks {
    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
}

Body:
After downloading your test project there are a couple of things I see:

Your run configuration for "MainApp" is not using gradle but is using an Intellij managed project configured to build and run the application.

MainApp.kt does not have a "main" function for Intellij to run

I'm not an expert on Intellij or gradle so I can't explain why you can launch with gradle without main function but can't do so from Intellij.  I expect that gradle can somehow inject a main function that can execute the JavaFX Application class defined by your MainApp (TornadoFX App class extends JavaFX Application class).

To get this working, you can either setup a run configuration to use gradle or add the main function to MyApp.kt and update the MainApp run configuration.

Use Gradle to Run from Intellij

Click the gradle tab on the right hand side of Intellij

Expand the kotlin-gradle configuration for Tasks -> application
Note: You may need to click the "refresh" button on the top left of the gradle panel to refresh the list of available tasks.

Double click "run" and the gradle run task will be executed

When you do this, Intellij will automatically add a new configuration "test-project [run]"

Screenshot of Gradle Panel

Note: It is still a good idea to add the main function as described below and update your build.gradle.kts to use "MainAppKt".  This will give you some flexibility in launching your application with Java 9+ without requiring module definitions (i.e. non-modular appplication)

Use Intellij to Run

Add the following code to your MainApp.kt

fun main(args: Array<String>) {
    launch<MainApp>(args)
}

Edit your existing "MainApp" run configuration and change the Main class to "MainAppKt"

Click Ok to save and you can now run the "MainApp" configuration

Last note: If you are using Java 9+, you need to use a snapshot build of TornadoFX otherwise, you will run into problems.

Add the snapshot repository to your respoitories section with

maven("https://oss.sonatype.org/content/repositories/snapshots")

And update the TornadoFX version to "2.0.0-SNAPSHOT"

implementation("no.tornado:tornadofx:2.0.0-SNAPSHOT")

Old Answer

You are missing the mainClassName setting in your build.gradle.kts:

application {
    mainClassName = "com.example.demo.app.MyApp"
}

Some notes:

If you have a main function that launches your app such as below, then you need to append "Kt" to the main class name where the function is located since a new class is created by kotlin to hold the static main function for the JVM. For example, if in the MyApp.kt file I had the main function below, I would need to use "com.example.demo.app.MyAppKt" in order to call the main function to run the application.

fun main(args: Array<String>) {
    launch<MyApp>(args)
}

The syntax for the mainClassName is different depending on the gradle version and the language. I normally use groovy so I had to look it up for kts.  The current gradle version 6.4 uses a different syntax than 6.3.  The syntax I provided is for 6.3.  I'm not sure when the change was made so you may need to verify the correct syntax for your gradle version.


问:
Loop through a range to open corresponding files
I have a list of *.xlsm file names on a sheet named "DB" in range E961 to E1010 (50 rows) and I'm trying to create a macro that runs through this list and open the corresponding files in the set directory, runs some code and close the file, moving on to the next file on the list - repeating this operation every 5 minutes.

The directory contains 400+ xlsm files, and the list in E961 will typically be less than 50 files - so I'm not trying to open all the files in the directory. That already happens once a day at a set time.

But I am trying to open these "shortlisted" files and update them every 5 minutes for example. I tried different combinations of code but can't seem to get it working.

The main file containing this code is also in the same directory to allow relative linking to the other 400+ files, hence the ThisWorkbook.Path code.

Edited code below:

```<code>Sub UPDATE()

Application.ScreenUpdating = True
With ThisWorkbook.Worksheets("DB")
    Dim inputRange As Range
    Set inputRange = .Range("E961", .Cells(.Rows.Count, 5).End(xlUp))
End With

Dim directory As String: directory = ThisWorkbook.Path & "\"
Dim fileName As String
Dim r As Range
Dim xlwb As Workbook
For Each r In inputRange
    If r <> vbNullString Then
        fileName = Dir(directory & r & ".xl??*")
        Set xlwb = Workbooks.Open(directory & fileName)

                Application.DisplayAlerts = False
                ActiveWorkbook.RefreshAll

                    If Range("A4") > Sheets("DB").Cells(Rows.Count, "A").End(xlUp).Offset(0) Then

                    Worksheets("DB").Range("A4:L4").Select
                    Worksheets("DB").Range("A4").Activate
                    Selection.Copy
                    Sheets("DB").Select
                    Sheets("DB").Cells(Rows.Count, "A").End(xlUp).Offset(1). _
                    PasteSpecial Paste:=xlPasteValues, _
                    SkipBlanks:=True, Transpose:=False
                    Application.CutCopyMode = False

                    Else
                    End If

                    If Range("A4") = Sheets("DB").Cells(Rows.Count, "A").End(xlUp).Offset(0) Then

                    Worksheets("DB").Range("A4:L4").Select
                    Worksheets("DB").Range("A4").Activate
                    Selection.Copy
                    Sheets("DB").Select
                    Sheets("DB").Cells(Rows.Count, "A").End(xlUp).Offset(0). _
                    PasteSpecial Paste:=xlPasteValues, _
                    SkipBlanks:=True, Transpose:=False
                    Application.CutCopyMode = False

                    End If

        xlwb.Close True
    End If
Next r

Application.ScreenUpdating = True

End Sub
</code>```

The error comes from "Set xlwb = (sht.Cells(Row, 1).Value)" because it is trying to open a sheet as a workbook, but I have no idea how to fix it... or everything is wrong ...

Thanks for the help!

答:
Try this piece it should work thought it will only open and close workbooks until you give it some code to work them:</p>

```<code>Option Explicit
Sub UPDATE()

    Application.ScreenUpdating = False
    'if you are only using here your wb and sht variables, use a With, there is no need to use variables
    With ThisWorkbook.Worksheets("DB")
        Dim inputRange As Range
        'It is preferable to do xlUp because you could find some empty cells in between.
        Set inputRange = .Range("E961", .Cells(.Rows.Count, 5).End(xlUp))
    End With

    Dim directory As String: directory = ThisWorkbook.Path & "\"
    Dim fileName As String
    Dim r As Range
    Dim xlwb As Workbook
    For Each r In inputRange
        If r <> vbNullString Then
            fileName = Dir(directory & r & ".xl??*") 'don't know if your cell has the extension
            Set xlwb = Workbooks.Open(directory & fileName)
            'some code
            xlwb.Close False 'False won't save the workbook, use True if you want it to be saved.
        End If
    Next r

    Application.ScreenUpdating = True

End Sub
</code>```

Body:
I have a list of *.xlsm file names on a sheet named "DB" in range E961 to E1010 (50 rows) and I'm trying to create a macro that runs through this list and open the corresponding files in the set directory, runs some code and close the file, moving on to the next file on the list - repeating this operation every 5 minutes.

The directory contains 400+ xlsm files, and the list in E961 will typically be less than 50 files - so I'm not trying to open all the files in the directory. That already happens once a day at a set time.

But I am trying to open these "shortlisted" files and update them every 5 minutes for example. I tried different combinations of code but can't seem to get it working.

The main file containing this code is also in the same directory to allow relative linking to the other 400+ files, hence the ThisWorkbook.Path code.

Edited code below:

Sub UPDATE()

Application.ScreenUpdating = True
With ThisWorkbook.Worksheets("DB")
    Dim inputRange As Range
    Set inputRange = .Range("E961", .Cells(.Rows.Count, 5).End(xlUp))
End With

Dim directory As String: directory = ThisWorkbook.Path & "\"
Dim fileName As String
Dim r As Range
Dim xlwb As Workbook
For Each r In inputRange
    If r <> vbNullString Then
        fileName = Dir(directory & r & ".xl??*")
        Set xlwb = Workbooks.Open(directory & fileName)

                Application.DisplayAlerts = False
                ActiveWorkbook.RefreshAll

                    If Range("A4") > Sheets("DB").Cells(Rows.Count, "A").End(xlUp).Offset(0) Then

                    Worksheets("DB").Range("A4:L4").Select
                    Worksheets("DB").Range("A4").Activate
                    Selection.Copy
                    Sheets("DB").Select
                    Sheets("DB").Cells(Rows.Count, "A").End(xlUp).Offset(1). _
                    PasteSpecial Paste:=xlPasteValues, _
                    SkipBlanks:=True, Transpose:=False
                    Application.CutCopyMode = False

                    Else
                    End If

                    If Range("A4") = Sheets("DB").Cells(Rows.Count, "A").End(xlUp).Offset(0) Then

                    Worksheets("DB").Range("A4:L4").Select
                    Worksheets("DB").Range("A4").Activate
                    Selection.Copy
                    Sheets("DB").Select
                    Sheets("DB").Cells(Rows.Count, "A").End(xlUp).Offset(0). _
                    PasteSpecial Paste:=xlPasteValues, _
                    SkipBlanks:=True, Transpose:=False
                    Application.CutCopyMode = False

                    End If

        xlwb.Close True
    End If
Next r

Application.ScreenUpdating = True

End Sub

The error comes from "Set xlwb = (sht.Cells(Row, 1).Value)" because it is trying to open a sheet as a workbook, but I have no idea how to fix it... or everything is wrong ...

Thanks for the help!

Body:
Try this piece it should work thought it will only open and close workbooks until you give it some code to work them:

Option Explicit
Sub UPDATE()

    Application.ScreenUpdating = False
    'if you are only using here your wb and sht variables, use a With, there is no need to use variables
    With ThisWorkbook.Worksheets("DB")
        Dim inputRange As Range
        'It is preferable to do xlUp because you could find some empty cells in between.
        Set inputRange = .Range("E961", .Cells(.Rows.Count, 5).End(xlUp))
    End With

    Dim directory As String: directory = ThisWorkbook.Path & "\"
    Dim fileName As String
    Dim r As Range
    Dim xlwb As Workbook
    For Each r In inputRange
        If r <> vbNullString Then
            fileName = Dir(directory & r & ".xl??*") 'don't know if your cell has the extension
            Set xlwb = Workbooks.Open(directory & fileName)
            'some code
            xlwb.Close False 'False won't save the workbook, use True if you want it to be saved.
        End If
    Next r

    Application.ScreenUpdating = True

End Sub


问:
SQL Duplicate Key Help
I have a statement that looks something like this:

```<code>insert table_name(...)
select .... from ... join ...
</code>```

How can I use where not exists or something of that effect with this insert and select statement so that if this exact code is reran with the same values, it won't throw an error. I don't want to have to copy and paste the select/joins in a check as it is a pretty big block of code, so is there any way to do something like

```<code>if not exists (insert table_name(...)
              select ... from...join)
</code>```

or would it be something else like

```<code>insert table_name(...)
if not exists(select ... from ... join)
</code>```

答:
In your
select .... from ... join ...

do a left join to the table you are inserting to with the new values you want to insert

if those joined values are null then you can safely insert without error.

ContentLicense: CC BY-SA 3.0

Title: SQL Duplicate Key Help

Body:
I have a statement that looks something like this:

insert table_name(...)
select .... from ... join ...

How can I use where not exists or something of that effect with this insert and select statement so that if this exact code is reran with the same values, it won't throw an error. I don't want to have to copy and paste the select/joins in a check as it is a pretty big block of code, so is there any way to do something like

if not exists (insert table_name(...)
              select ... from...join)

or would it be something else like

insert table_name(...)
if not exists(select ... from ... join)


问:
How to fix java.sql.SQLException: Server is running in --secure-auth mode, but 'user'@'host' has a password in the old format; (...)?
After upgrading MySQL 5.1 to 5.6, trying to start JBoss failed with this exception:

```<code>java.sql.SQLException:
  Server is running in --secure-auth mode, but 'user'@'localhost'
  has a password in the old format;  please change the password to the new format
</code>```

How to fix this issue?

答:
In my case, this was fixed by turning secure auth off.

Edit /etc/my.cnf

Add under the [mysqld] section:

```<code>old_passwords=1
secure-auth=false
</code>```

Body:
After upgrading MySQL 5.1 to 5.6, trying to start JBoss failed with this exception:

java.sql.SQLException:
  Server is running in --secure-auth mode, but 'user'@'localhost'
  has a password in the old format;  please change the password to the new format

How to fix this issue?

Body:
In my case, this was fixed by turning secure auth off.

Edit /etc/my.cnf

Add under the [mysqld] section:

old_passwords=1
secure-auth=false


问:
React redux store's state not saved
I created a store with redux to experiment with the app state management in react. So far I'm just trying to make a fake authentication behavior when clicking on the "sign in" button on the login page, which is working because my isLogged state change to true. But then when I try to access a path that I protected by checking if isLogged is true, I get false... why is the state of isLogged not saved when routing with react-router_dom?

index.js

```<code>const store = createStore(
allReducers,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

ReactDOM.render(
<React.StrictMode>
    <Provider store={store}>
        <App/>
    </Provider>
</React.StrictMode>,
document.getElementById('root')
);
</code>```

App.js

```<code>class App extends Component {
render() {
    return (
        <Box style={{width: "99.6vw", height: "95.6vh"}}>
            <Router>
                <SideNavBar/>
                <Switch>
                    <Route exact path={"/"} render={() => <Redirect to={"/login"}/>}/>
                    <Route path={"/login"} component={LoginPage}/>
                    <ProtectedRoute path={"/somepage"} component={somePage}/>
                </Switch>
            </Router>
        </Box>
    );
}
}
</code>```

LoginPage.js

```<code>class LoginPage extends Component {
render() {
    const {dispatch} = this.props;

    return (
        <LoginPageContainer>
            <img src={logo} alt={""} height={"350rem"}/>
            <FilledInput placeholder={"Login or email"}/>
            <FilledInput placeholder={"Password"}/>
            <Button onClick={() => dispatch({ type: "SIGN_IN" })}>
                Sign in
            </Button>
        </LoginPageContainer>
    );
}
}

export default connect(null, null)(LoginPage);
</code>```

ProtectedRoute.js

```<code>import {connectProtectedRoute as connect} from "../redux/connectProtectedRoute";

class ProtectedRoute extends Component {
render() {
    const {isLogged, component} = this.props;

    return (
        <Route render={
            () => {
                if (isLogged)
                    return (component);
                else
                    return (<Redirect to={"/login"}/>);
            }
        }/>
    );
}
}

ProtectedRoute.propTypes = {
component: PropTypes.elementType.isRequired
};

export default connect(ProtectedRoute);
</code>```

connectProtectedRoute.js

```<code>import {connect} from "react-redux";

function mapStateToProps(state) {
return ({
    isLogged: state.isLogged
});
}

export const connectProtectedRoute = connect(mapStateToProps, null);
</code>```

reducers.js

```<code>const allReducers = combineReducers({
isLogged: isLoggedReducer
});

export default allReducers;
</code>```

isLoggedReducer.js

```<code>const isLoggedReducer = (state = false, action) => {
switch (action.type) {
    case "SIGN_IN": return true;
    case "SIGN_OUT": return false;
    default: return state;
}
}

export default isLoggedReducer;
</code>```

答:
So I was just unaware of the losing state fact upon refresh. Comment from original post said it all, here they are for anyone ending here:

Modifying the URL manually (outside of react router) will cause a full page refresh and  all state will be lost (unless you persist it in local storage or by some other method).  This is your problem, nothing in the code looks wrong. – Brian Thompson

Modifying the url causes the page refresh and follows the rerunning the app, so all data in store are removed. Try to use history for page navigation. Here is how to use it. reacttraining.com/react-router/web/api/Hooks/usehistory – TopWebGhost

Title: React redux store's state not saved

Body:
I created a store with redux to experiment with the app state management in react. So far I'm just trying to make a fake authentication behavior when clicking on the "sign in" button on the login page, which is working because my isLogged state change to true. But then when I try to access a path that I protected by checking if isLogged is true, I get false... why is the state of isLogged not saved when routing with react-router_dom?

index.js

const store = createStore(
allReducers,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

ReactDOM.render(
<React.StrictMode>
    <Provider store={store}>
        <App/>
    </Provider>
</React.StrictMode>,
document.getElementById('root')
);

App.js

class App extends Component {
render() {
    return (
        <Box style={{width: "99.6vw", height: "95.6vh"}}>
            <Router>
                <SideNavBar/>
                <Switch>
                    <Route exact path={"/"} render={() => <Redirect to={"/login"}/>}/>
                    <Route path={"/login"} component={LoginPage}/>
                    <ProtectedRoute path={"/somepage"} component={somePage}/>
                </Switch>
            </Router>
        </Box>
    );
}
}

LoginPage.js

class LoginPage extends Component {
render() {
    const {dispatch} = this.props;

    return (
        <LoginPageContainer>

            <FilledInput placeholder={"Login or email"}/>
            <FilledInput placeholder={"Password"}/>
            <Button onClick={() => dispatch({ type: "SIGN_IN" })}>
                Sign in
            </Button>
        </LoginPageContainer>
    );
}
}

export default connect(null, null)(LoginPage);

ProtectedRoute.js

import {connectProtectedRoute as connect} from "../redux/connectProtectedRoute";

class ProtectedRoute extends Component {
render() {
    const {isLogged, component} = this.props;

    return (
        <Route render={
            () => {
                if (isLogged)
                    return (component);
                else
                    return (<Redirect to={"/login"}/>);
            }
        }/>
    );
}
}

ProtectedRoute.propTypes = {
component: PropTypes.elementType.isRequired
};

export default connect(ProtectedRoute);

connectProtectedRoute.js

import {connect} from "react-redux";

function mapStateToProps(state) {
return ({
    isLogged: state.isLogged
});
}

export const connectProtectedRoute = connect(mapStateToProps, null);

reducers.js

const allReducers = combineReducers({
isLogged: isLoggedReducer
});

export default allReducers;

isLoggedReducer.js

const isLoggedReducer = (state = false, action) => {
switch (action.type) {
    case "SIGN_IN": return true;
    case "SIGN_OUT": return false;
    default: return state;
}
}

export default isLoggedReducer;


问:
Override or add some style properties in WPF
I am porting a Bootstrap theme to WPF and faced a problem: I can't change some properties using additional style for StackPanel. I have ResourceDictionary containing BtnBase base style and BtnPrimary, BtnSecondary etc. All of them were inherited from BtnBase and contain only color properties. BtnBase does not contain any margin rule. When I try to add margin rule for a current StackPanel, there is no effect. I read about styles and knew that more than one style can't be applied, styles in ResourceDictionary have higher priority and I should use BasedOn. But I need to copy and paste my style in the StackPanel and replace BasedOn for each button variant. Is there a way to bypass it and add margin property for all styles?

code:

```<code><StackPanel Orientation="Horizontal" Height="32">
        <StackPanel.Resources>
            <Style TargetType="{x:Type Button}" BasedOn="{StaticResource BtnBase}>
                <Setter Property="Margin" Value="0,0,10,0"/>
            </Style>
        </StackPanel.Resources>
        <Button Style="{DynamicResource BtnPrimary}" Content="Primary" />
        <Button Style="{DynamicResource BtnSecondary}" Content="Secondary" />
        <Button Style="{DynamicResource BtnSuccess}" Content="Success" />
        <Button Style="{DynamicResource BtnInfo}" Content="Info" />
        <Button Style="{DynamicResource BtnWarning}" Content="Warning" />
        <Button Style="{DynamicResource BtnDanger}" Content="Danger" />
        <Button Style="{DynamicResource BtnLight}" Content="Light" />
        <Button Style="{DynamicResource BtnDark}" Content="Dark" />
    </StackPanel>
</code>```

答:
You can treat all buttons as Items in ListBox.

ListBox will create a ListBoxItem for each Button, and you can add Margin to those ListBoxItems, using ItemContainerStyle. That doesn't modify Buttons styles, but creates same effect.

In ItemContainerStyle I also change ListBoxItem template to undo hover, selection colors, etc, which can change appearance - just plain ContentPresenter is left.

ItemsPanel by default is vertical StackPanel, but I changed ItemsPanel and layout to horizontal StackPanel.

```<code><ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" Height="32"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>

    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Margin" Value="4"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <ContentPresenter/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>

    <Button Style="{DynamicResource BtnPrimary}" Content="Primary" />
    <Button Style="{DynamicResource BtnSecondary}" Content="Secondary" />
    <Button Style="{DynamicResource BtnSuccess}" Content="Success" />
    <Button Style="{DynamicResource BtnInfo}" Content="Info" />
    <Button Style="{DynamicResource BtnWarning}" Content="Warning" />
    <Button Style="{DynamicResource BtnDanger}" Content="Danger" />
    <Button Style="{DynamicResource BtnLight}" Content="Light" />
    <Button Style="{DynamicResource BtnDark}" Content="Dark" />
</ListBox>
</code>```

Body:
I am porting a Bootstrap theme to WPF and faced a problem: I can't change some properties using additional style for StackPanel. I have ResourceDictionary containing BtnBase base style and BtnPrimary, BtnSecondary etc. All of them were inherited from BtnBase and contain only color properties. BtnBase does not contain any margin rule. When I try to add margin rule for a current StackPanel, there is no effect. I read about styles and knew that more than one style can't be applied, styles in ResourceDictionary have higher priority and I should use BasedOn. But I need to copy and paste my style in the StackPanel and replace BasedOn for each button variant. Is there a way to bypass it and add margin property for all styles?

code:

<StackPanel Orientation="Horizontal" Height="32">
        <StackPanel.Resources>

        </StackPanel.Resources>
        <Button Style="{DynamicResource BtnPrimary}" Content="Primary" />
        <Button Style="{DynamicResource BtnSecondary}" Content="Secondary" />
        <Button Style="{DynamicResource BtnSuccess}" Content="Success" />
        <Button Style="{DynamicResource BtnInfo}" Content="Info" />
        <Button Style="{DynamicResource BtnWarning}" Content="Warning" />
        <Button Style="{DynamicResource BtnDanger}" Content="Danger" />
        <Button Style="{DynamicResource BtnLight}" Content="Light" />
        <Button Style="{DynamicResource BtnDark}" Content="Dark" />
    </StackPanel>

Body:
You can treat all buttons as Items in ListBox.

ListBox will create a ListBoxItem for each Button, and you can add Margin to those ListBoxItems, using ItemContainerStyle. That doesn't modify Buttons styles, but creates same effect.

In ItemContainerStyle I also change ListBoxItem template to undo hover, selection colors, etc, which can change appearance - just plain ContentPresenter is left.

ItemsPanel by default is vertical StackPanel, but I changed ItemsPanel and layout to horizontal StackPanel.

<ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" Height="32"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>

    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Margin" Value="4"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <ContentPresenter/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>

    <Button Style="{DynamicResource BtnPrimary}" Content="Primary" />
    <Button Style="{DynamicResource BtnSecondary}" Content="Secondary" />
    <Button Style="{DynamicResource BtnSuccess}" Content="Success" />
    <Button Style="{DynamicResource BtnInfo}" Content="Info" />
    <Button Style="{DynamicResource BtnWarning}" Content="Warning" />
    <Button Style="{DynamicResource BtnDanger}" Content="Danger" />
    <Button Style="{DynamicResource BtnLight}" Content="Light" />
    <Button Style="{DynamicResource BtnDark}" Content="Dark" />
</ListBox>


问:
.NET Regex: Get all matched groups
I've stuck with regex problem using .NET. For example, I have next regex pattern: (?'group1'A|C)|(?'group2'B|C)|(?'group3'A|B|C)

When I do match of "AXYZ" I receive match object which contains Value and Groups; if I go to Groups I'll see that only one group has success in true - group1 (group3 is in false). If I do match of "BXYZ" I'll receive only group2 with success in true (group3 is in false).

How could I receive in match not only one group but all groups satisfying the match?

For example above it should be: group1 & group3 in "AXYZ" and group2 & group3 in "BXYZ".

All above is only example in real system there are different patterns (3+ letters each) and more complicated input text (1000+ words).

答:
I believe you have to make the regex "greedy". Here is some info on it:

http://blogs.msdn.com/b/ericgu/archive/2005/08/19/453869.aspx

Title: .NET Regex: Get all matched groups


问:
Is it needed to specify a BlockingQueue for QueuedThreadPool if ServerConnector is already configured with AcceptQueueSize?
While creating a Jetty Server and Jetty ServerConnector,

```<code>QueuedThreadPool pool = new QueuedThreadPool(minThread,maxThread,new BlockingArrayQueue());
Server server = new Server(pool);
/*rest code blah blah*/
ServerConnector servConn = ServerConnector(server, acceptors, selectors, sslContextFactory);
/*rest code blah blah */
int acceptQueueSize = getAcceptQueueSize();
servConn.setAcceptQueueSize(acceptQueueSize);
/*rest code blah blah */
</code>```

What is the relation between "BlockingArrayQueue for QTP" and "setting the setAcceptQueueSize for ServerConnector"?
if BlockingArrayQueue is set with maxCapacity parameter in constructor then will the acceptQueueSize affect this maxCapacity ?

(in the above code I have used the basic constructor of BlockingArrayQueueSize, please check below links for the other constructors. Please refer the below links for other referenced classes in above code block)

ServerConnector(https://www.eclipse.org/jetty/javadoc/9.4.27.v20200227/org/eclipse/jetty/server/ServerConnector.html)

QueuedThreadPool (https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/util/thread/QueuedThreadPool.html)

BlockingArrayQueue(https://www.eclipse.org/jetty/javadoc/9.4.27.v20200227/org/eclipse/jetty/util/BlockingArrayQueue.html)

答:
The QueuedThreadPool constructor parameter for BlockingQueue<Runnable> queue exists for embedded systems users that need to tweak their Jetty environment for extremely low system utilization and/or JVM limitations.

Jetty can (and does) run on embedded systems which have only 16 MB of RAM.

If you are using OpenJDK or any derivative, then don't change the queue type unless you fully (and I mean 100% understand the behavior of the JVM you are running on on the hardware that it will run on).  Using the default BlockingQueue<Runnable> implementation is nearly always recommended.

If you are considering using some kind of alternative / tweaked / configured BlockingQueue<Runnable> to implement some kind of limitation of load or resource utilization then you are going down the wrong path.   Jetty is not a 1 thread per 1 connection style of Container, a single connection can result in the usage of multiple different threads through the lifespan of that single connection.  Your use of various technologies within Jetty can also alter the threading demands you place on Jetty. It is very easy for you to have a single connection, with a single request, use multiple threads to service that request (all dependent on what you decide to do during that request).

Body:
While creating a Jetty Server and Jetty ServerConnector,

QueuedThreadPool pool = new QueuedThreadPool(minThread,maxThread,new BlockingArrayQueue());
Server server = new Server(pool);
/*rest code blah blah*/
ServerConnector servConn = ServerConnector(server, acceptors, selectors, sslContextFactory);
/*rest code blah blah */
int acceptQueueSize = getAcceptQueueSize();
servConn.setAcceptQueueSize(acceptQueueSize);
/*rest code blah blah */

What is the relation between "BlockingArrayQueue for QTP" and "setting the setAcceptQueueSize for ServerConnector"?
if BlockingArrayQueue is set with maxCapacity parameter in constructor then will the acceptQueueSize affect this maxCapacity ?

(in the above code I have used the basic constructor of BlockingArrayQueueSize, please check below links for the other constructors. Please refer the below links for other referenced classes in above code block)

ServerConnector(https://www.eclipse.org/jetty/javadoc/9.4.27.v20200227/org/eclipse/jetty/server/ServerConnector.html)

QueuedThreadPool (https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/util/thread/QueuedThreadPool.html)

BlockingArrayQueue(https://www.eclipse.org/jetty/javadoc/9.4.27.v20200227/org/eclipse/jetty/util/BlockingArrayQueue.html)


问:
JavaScript - Time Logout, click reset Time Logout
I have a code that gives the time of 20min and then disconnects the user. It's working normal. However, I need that if the user is working on the page, the team returns to the initial value, as I use a lot of ajax and the page ends up not updating as it should to return to the initial one.

HTML

```<code><h2 id="theTime" style="font-weight: bold;font-size: 16px; color:#FFF;">20:00 </h2>
</code>```

JavaScript

```<code>$("#index-body").click(function() {
    var newTime = "s";
    sivamtime(newTime);
});
</code>```

JavaScript - timeLogout

```<code>min=20;
sec=0;
var now = new Date();
var expire_time = new Date(now.getTime() + (min * 60000));
var timer_ticket = null;

function sivamtime(newTime) {
    var progressive_time = new Date();
    if((expire_time - progressive_time) < 1 || (min == 0 && sec == 0)){
        //$(document).ready(function() {
        $('#myModal').modal('show');
        $("#modal-body-info").html('<b>Por segurança</b>,<br> Tempo esgotado, não utilizou o site no prazo de 20 minutos');
        $('.logout').click(function() {
          window.location='login.php';
        });
        //});
    } else{
        min = "20";
        sec = "00";
        var countdown = (expire_time - progressive_time) / 1000;
        min = Math.ceil(countdown / 60) - 1;
        sec = Math.ceil(countdown % 60) - 1;
        if (min<=9 ) { min="0"+min; }
        if (min==0) {min="00";}
        if (sec<=9) { sec="0"+sec; }

        time = min + ":" + sec + " " ;

        if (document.getElementById) { document.getElementById('theTime').innerHTML = time; }
        else if (document.layers) {
            document.layers.theTime.document.write(time);
            document.layers.theTime.document.close();
        }
            timer_ticket = setTimeout("sivamtime()", 1000);
        }
    }

    $(document).ready(function() {
        sivamtime();
});
</code>```

答:
I have written a simple structure on jsFiddle where you can refer from:

Click Here

HTML:

```<code><div id="thebody"  style="border:1px solid">
    <br><br><br><br>
</div>
</code>```

JS/jQuery:

```<code> let theTimer = function(callback) {
  let timerId

  this.stop = () => {
    window.clearTimeout(timerId)
  }

  this.start = () => {
    window.clearTimeout(timerId)
    timerId = window.setTimeout(callback, 2000)
  }
}

let newTimer = new theTimer(function() {
  console.log("Done!")
})

$("#thebody").click(function(){
   console.log('timer start/restart')
   newTimer.stop()
   newTimer.start()
})
</code>```

Body:
I have a code that gives the time of 20min and then disconnects the user. It's working normal. However, I need that if the user is working on the page, the team returns to the initial value, as I use a lot of ajax and the page ends up not updating as it should to return to the initial one.

HTML

20:00

JavaScript

$("#index-body").click(function() {
    var newTime = "s";
    sivamtime(newTime);
});

JavaScript - timeLogout

min=20;
sec=0;
var now = new Date();
var expire_time = new Date(now.getTime() + (min * 60000));
var timer_ticket = null;

function sivamtime(newTime) {
    var progressive_time = new Date();
    if((expire_time - progressive_time) < 1 || (min == 0 && sec == 0)){
        //$(document).ready(function() {
        $('#myModal').modal('show');
        $("#modal-body-info").html('Por segurança,
 Tempo esgotado, não utilizou o site no prazo de 20 minutos');
        $('.logout').click(function() {
          window.location='login.php';
        });
        //});
    } else{
        min = "20";
        sec = "00";
        var countdown = (expire_time - progressive_time) / 1000;
        min = Math.ceil(countdown / 60) - 1;
        sec = Math.ceil(countdown % 60) - 1;
        if (min<=9 ) { min="0"+min; }
        if (min==0) {min="00";}
        if (sec<=9) { sec="0"+sec; }

        time = min + ":" + sec + " " ;

        if (document.getElementById) { document.getElementById('theTime').innerHTML = time; }
        else if (document.layers) {
            document.layers.theTime.document.write(time);
            document.layers.theTime.document.close();
        }
            timer_ticket = setTimeout("sivamtime()", 1000);
        }
    }

    $(document).ready(function() {
        sivamtime();
});

Body:
I have written a simple structure on jsFiddle where you can refer from:

Click Here

HTML:

<div id="thebody"  style="border:1px solid">
    <br><br><br><br>
</div>

JS/jQuery:

 let theTimer = function(callback) {
  let timerId

  this.stop = () => {
    window.clearTimeout(timerId)
  }

  this.start = () => {
    window.clearTimeout(timerId)
    timerId = window.setTimeout(callback, 2000)
  }
}

let newTimer = new theTimer(function() {
  console.log("Done!")
})

$("#thebody").click(function(){
   console.log('timer start/restart')
   newTimer.stop()
   newTimer.start()
})


问:
is there a way to accept all image mime types in node
i would like to accept only images to be stored however i have to specify every image extension,
is there a single line code like in other languages like java and PHP where i use image/*

here is the code requiring me to put every file extension in node

const fileFilter = (req, file, cb) => {
    if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png'){
        //store image
    }
};```

答:
You can define a regex to match images/* only:

```<code>const imagesMimeRegex = new RegExp("image/(.*)");

const fileFilter = (req, file, cb) => {
    if(imagesMimeRegex.test(file.mimetype)){
        // do something
    }
};
</code>```

Body:
You can define a regex to match images/* only:

const imagesMimeRegex = new RegExp("image/(.*)");

const fileFilter = (req, file, cb) => {
    if(imagesMimeRegex.test(file.mimetype)){
        // do something
    }
};


问:
Self inner join, aggregate and sum of set
I've got the following schema:

```<code>CREATE TABLE aTable
    ("id" int, "idOfOperation" varchar(10), "uniqueName" varchar(6), "randomNumber" int)
;

INSERT INTO aTable
    ("id", "idOfOperation", "uniqueName", "randomNumber")
VALUES
    (1, 'operation1', 'model1', 3),
    (2, 'operation1', 'model2', 5),
    (3, 'operation2', 'model2', 43),
    (4, 'operation2', 'model3', 57),
    (5, 'operation2', 'model4', 65)
;
</code>```

Constraints:

(idOfOperation, uniqueName) are unique.

Table contains results of different operations (operation1, operation2) and which operation has multiple sub models (model1, model2, model3, model4) with some unique values (randomNumber).

What I need to achieve:

Create a query which will find a sum of set of two operations (operation1, operation2) withe following output:
'model2', 5.18, 'model2', 43.2

I already tried the following inner join:

```<code>select r1.*, r2.*
from aTable r1
         inner join aTable r2
         on (r1."uniqueName" = r2."uniqueName" and r1."idOfOperation" != r2."idOfOperation")
where (r1."idOfOperation" = 'operation1' or r1."idOfOperation" = 'operation2')
</code>```

But the result contains two rows instead of one (with swapped values):

```<code>id  idOfOperation   uniqueName  randomNumber    id  idOfOperation   uniqueName  randomNumber
3   operation2  model2  43  2   operation1  model2  5
2   operation1  model2  5   3   operation2  model2  43
</code>```

Expected result is:

```<code>operation2, operation1, model2, 43, 5
</code>```

I'd really appreciate any help.

答:
Please use below query,

```<code>select split_part(idOfOperation, ',', 2) as col1, split_part(idOfOperation, ',', 1) as
col2,  uniqueName as col3, split_part(randomNumber, ',', 2) as col4,
split_part(randomNumber, ',', 1) as col5 from
(select STRING_AGG ("idOfOperation", ',') as idOfOperation , "uniqueName" as
uniqueName, STRING_AGG ("randomNumber"::text, ',') as randomNumber
from aTable  group by "uniqueName") qry where split_part(idOfOperation, ',', 2) != '';
</code>```

Snipping of your expected result,

Body:
I've got the following schema:

CREATE TABLE aTable
    ("id" int, "idOfOperation" varchar(10), "uniqueName" varchar(6), "randomNumber" int)
;

INSERT INTO aTable
    ("id", "idOfOperation", "uniqueName", "randomNumber")
VALUES
    (1, 'operation1', 'model1', 3),
    (2, 'operation1', 'model2', 5),
    (3, 'operation2', 'model2', 43),
    (4, 'operation2', 'model3', 57),
    (5, 'operation2', 'model4', 65)
;

Constraints:

(idOfOperation, uniqueName) are unique.

Table contains results of different operations (operation1, operation2) and which operation has multiple sub models (model1, model2, model3, model4) with some unique values (randomNumber).

What I need to achieve:

Create a query which will find a sum of set of two operations (operation1, operation2) withe following output:
'model2', 5.18, 'model2', 43.2

I already tried the following inner join:

select r1.*, r2.*
from aTable r1
         inner join aTable r2
         on (r1."uniqueName" = r2."uniqueName" and r1."idOfOperation" != r2."idOfOperation")
where (r1."idOfOperation" = 'operation1' or r1."idOfOperation" = 'operation2')

But the result contains two rows instead of one (with swapped values):

id  idOfOperation   uniqueName  randomNumber    id  idOfOperation   uniqueName  randomNumber
3   operation2  model2  43  2   operation1  model2  5
2   operation1  model2  5   3   operation2  model2  43

Expected result is:

operation2, operation1, model2, 43, 5

I'd really appreciate any help.

Body:
Please use below query,

select split_part(idOfOperation, ',', 2) as col1, split_part(idOfOperation, ',', 1) as
col2,  uniqueName as col3, split_part(randomNumber, ',', 2) as col4,
split_part(randomNumber, ',', 1) as col5 from
(select STRING_AGG ("idOfOperation", ',') as idOfOperation , "uniqueName" as
uniqueName, STRING_AGG ("randomNumber"::text, ',') as randomNumber
from aTable  group by "uniqueName") qry where split_part(idOfOperation, ',', 2) != '';

Snipping of your expected result,


问:
Angular, FormControl - confirm value change
I have form control for selecting some value (for example - gender) and couple of <input type="radio">.
The requirements are next:

When user changes the input, I need to show a modal window which asks him to confirm or cancel  changes (without doing anything).

I need to show modal only if user changes input value from one gender to another.

My problem is that FormControl has just valueChanges event that emits after value was already changed.
And I need to set up previous value programmatically:

```<code>this.genderControl.setValue(GenderEnum.MALE, {emitEvent: false});
</code>```

Some pseudo code example:

component.html

```<code><input
  formControlName="gender"
  type="radio"
  value="female"
  id="female"
/>
<input
  formControlName="gender"
  type="radio"
  value="male"
  id="male"
/>
<input
  formControlName="gender"
  type="radio"
  value="other"
  id="other"
/>
</code>```

component.ts

```<code>this.genderControl.valueChanges
  .pipe(
    distinctUntilChanged(),
    startWith(null),
    pairwise(),
    takeUntil(this._destroy$)
  ).subscribe(([prev, next]: [GenderEnum, GenderEnum]) => {
    this.openWarningModal().afterClosed().subscribe((selectedAction: CommonModalsActionsEnum) => {
      if (selectedAction === CommonModalsActionsEnum.CONFIRM) {
        this.handleChangeGender(next);
      }

      if (selectedAction === CommonModalsActionsEnum.CLOSE) {
        this.genderControl.setValue(prev, {emitEvent: false});
      }
    });
  });
</code>```

The possible solution may be in removing FormControl, using ngModel and subscription on input click event.
In this way on click handler shows modal and changes or doesn't change the var, related to ngModel.

But I hope that the more clear solution is exist!

答:
If you plan to use ngModel, instead of subscribing to the click event, you can subscribe to the

```<code>ngModelChanges()
</code>```

event, which is the @Output of ngModel directive. It fires when the model changes.

Body:
I have form control for selecting some value (for example - gender) and couple of <input type="radio">.
The requirements are next:

When user changes the input, I need to show a modal window which asks him to confirm or cancel  changes (without doing anything).

I need to show modal only if user changes input value from one gender to another.

My problem is that FormControl has just valueChanges event that emits after value was already changed.
And I need to set up previous value programmatically:

this.genderControl.setValue(GenderEnum.MALE, {emitEvent: false});

Some pseudo code example:

component.html

<input
  formControlName="gender"
  type="radio"
  value="female"
  id="female"
/>
<input
  formControlName="gender"
  type="radio"
  value="male"
  id="male"
/>
<input
  formControlName="gender"
  type="radio"
  value="other"
  id="other"
/>

component.ts

this.genderControl.valueChanges
  .pipe(
    distinctUntilChanged(),
    startWith(null),
    pairwise(),
    takeUntil(this._destroy$)
  ).subscribe(([prev, next]: [GenderEnum, GenderEnum]) => {
    this.openWarningModal().afterClosed().subscribe((selectedAction: CommonModalsActionsEnum) => {
      if (selectedAction === CommonModalsActionsEnum.CONFIRM) {
        this.handleChangeGender(next);
      }

      if (selectedAction === CommonModalsActionsEnum.CLOSE) {
        this.genderControl.setValue(prev, {emitEvent: false});
      }
    });
  });

The possible solution may be in removing FormControl, using ngModel and subscription on input click event.
In this way on click handler shows modal and changes or doesn't change the var, related to ngModel.

But I hope that the more clear solution is exist!

Body:
If you plan to use ngModel, instead of subscribing to the click event, you can subscribe to the

ngModelChanges()

event, which is the @Output of ngModel directive. It fires when the model changes.


问:
Collectstatic failing - botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found
I'm attempting to run collectstatic on a stage deploy to AWS. I'm getting the following error, and no files are being placed in the bucket:

```<code>Traceback (most recent call last):
  File "/home/hcc/.local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 523, in _open
    f = S3Boto3StorageFile(name, mode, self)
  File "/home/hcc/.local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 74, in __init__
    self.obj.load()
  File "/home/hcc/.local/lib/python3.6/site-packages/boto3/resources/factory.py", line 505, in do_action
    response = action(self, *args, **kwargs)
  File "/home/hcc/.local/lib/python3.6/site-packages/boto3/resources/action.py", line 83, in __call__
    response = getattr(parent.meta.client, operation_name)(*args, **params)
  File "/home/hcc/.local/lib/python3.6/site-packages/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/home/hcc/.local/lib/python3.6/site-packages/botocore/client.py", line 635, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/hcc/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/home/hcc/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/hcc/.local/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/hcc/.local/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute
    output = self.handle(*args, **options)
  File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 161, in handle
    if self.is_local_storage() and self.storage.location:
  File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 215, in is_local_storage
    return isinstance(self.storage, FileSystemStorage)
  File "/home/hcc/.local/lib/python3.6/site-packages/django/utils/functional.py", line 224, in inner
    self._setup()
  File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 501, in _setup
    self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)()
  File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 379, in __init__
    self.hashed_files = self.load_manifest()
  File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 389, in load_manifest
    content = self.read_manifest()
  File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 383, in read_manifest
    with self.open(self.manifest_name) as manifest:
  File "/home/hcc/.local/lib/python3.6/site-packages/django/core/files/storage.py", line 36, in open
    return self._open(name, mode)
  File "/home/hcc/.local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 526, in _open
    raise IOError('File does not exist: %s' % name)
OSError: File does not exist: static/staticfiles.json
</code>```

My static files settings are as follows in settings.py:

```<code>STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
]

STATICFILES_DIRS = [join(BASE_DIR, "assets", "build")]

DEFAULT_FILE_STORAGE = "staticfiles.storage.MediaStorage"
STATICFILES_STORAGE = "staticfiles.storage.ManifestStaticFilesStorage"

STATIC_FILES_BUCKET = "stage-bucket"
STATIC_FILES_LOCATION = "static"

STATIC_ROOT = join(BASE_DIR, "static")
STATIC_URL = f"https://{STATIC_FILES_BUCKET}.s3.amazonaws.com/{STATIC_FILES_LOCATION}/"

MEDIA_FILES_BUCKET = ""
MEDIA_FILES_LOCATION = ""

MEDIA_ROOT = join(BASE_DIR, "media")
MEDIA_URL = "/media/"
</code>```

The custom storage classes that I'm using are:

```<code>from django.contrib.staticfiles.storage import ManifestFilesMixin
from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage

class ManifestStaticFilesStorage(ManifestFilesMixin, S3Boto3Storage):
    bucket_name = settings.STATIC_FILES_BUCKET
    location = settings.STATIC_FILES_LOCATION

class MediaStorage(S3Boto3Storage):
    bucket_name = settings.MEDIA_FILES_BUCKET
    location = settings.MEDIA_FILES_LOCATION
    file_overwrite = False
</code>```

Requirements.txt includes:

```<code>Django==3.0.3
gunicorn==20.0.4

django-model-utils==4.0.0
django-storages==1.9.1
boto3==1.13.15
htmlmin==0.1.12

sentry-sdk==0.14.3
slackclient==2.5.0
structlog==18.2.0
ddtrace==0.31.0
colorama==0.3.9
json-logging-py==0.2
</code>```

When I removed the ManifestFilesMixin from the ManifestStaticFilesStorage class, collectstatic worked, but obviously not with hashed files or the staticfiles.json that I need.

I've spent multiple days trying to figure this out and I'm stumped as to what could be the cause. Any information would be appreciated.

答:
Found an answer on another site from someone that was having a similar issue. It seems S3Boto3Storage is throwing IOError but ManifestFilesMixin is expecting FileNotFound. This solved my issue and I'm now seeing the hashed files in my S3 bucket along with a staticfiles.json. </p>

```<code>class ManifestStaticFilesStorage(ManifestFilesMixin, S3Boto3Storage):
    bucket_name = settings.STATIC_FILES_BUCKET
    location = settings.STATIC_FILES_LOCATION

    def read_manifest(self):
        try:
            return super(ManifestStaticFilesStorage,self).read_manifest()
        except IOError:
            return None
</code>```

Body:
I'm attempting to run collectstatic on a stage deploy to AWS. I'm getting the following error, and no files are being placed in the bucket:

Traceback (most recent call last):
  File "/home/hcc/.local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 523, in _open
    f = S3Boto3StorageFile(name, mode, self)
  File "/home/hcc/.local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 74, in __init__
    self.obj.load()
  File "/home/hcc/.local/lib/python3.6/site-packages/boto3/resources/factory.py", line 505, in do_action
    response = action(self, *args, **kwargs)
  File "/home/hcc/.local/lib/python3.6/site-packages/boto3/resources/action.py", line 83, in __call__
    response = getattr(parent.meta.client, operation_name)(*args, **params)
  File "/home/hcc/.local/lib/python3.6/site-packages/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/home/hcc/.local/lib/python3.6/site-packages/botocore/client.py", line 635, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/hcc/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/home/hcc/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/hcc/.local/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/hcc/.local/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute
    output = self.handle(*args, **options)
  File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 161, in handle
    if self.is_local_storage() and self.storage.location:
  File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 215, in is_local_storage
    return isinstance(self.storage, FileSystemStorage)
  File "/home/hcc/.local/lib/python3.6/site-packages/django/utils/functional.py", line 224, in inner
    self._setup()
  File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 501, in _setup
    self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)()
  File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 379, in __init__
    self.hashed_files = self.load_manifest()
  File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 389, in load_manifest
    content = self.read_manifest()
  File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 383, in read_manifest
    with self.open(self.manifest_name) as manifest:
  File "/home/hcc/.local/lib/python3.6/site-packages/django/core/files/storage.py", line 36, in open
    return self._open(name, mode)
  File "/home/hcc/.local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 526, in _open
    raise IOError('File does not exist: %s' % name)
OSError: File does not exist: static/staticfiles.json

My static files settings are as follows in settings.py:

STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
]

STATICFILES_DIRS = [join(BASE_DIR, "assets", "build")]

DEFAULT_FILE_STORAGE = "staticfiles.storage.MediaStorage"
STATICFILES_STORAGE = "staticfiles.storage.ManifestStaticFilesStorage"

STATIC_FILES_BUCKET = "stage-bucket"
STATIC_FILES_LOCATION = "static"

STATIC_ROOT = join(BASE_DIR, "static")
STATIC_URL = f"https://{STATIC_FILES_BUCKET}.s3.amazonaws.com/{STATIC_FILES_LOCATION}/"

MEDIA_FILES_BUCKET = ""
MEDIA_FILES_LOCATION = ""

MEDIA_ROOT = join(BASE_DIR, "media")
MEDIA_URL = "/media/"

The custom storage classes that I'm using are:

from django.contrib.staticfiles.storage import ManifestFilesMixin
from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage

class ManifestStaticFilesStorage(ManifestFilesMixin, S3Boto3Storage):
    bucket_name = settings.STATIC_FILES_BUCKET
    location = settings.STATIC_FILES_LOCATION

class MediaStorage(S3Boto3Storage):
    bucket_name = settings.MEDIA_FILES_BUCKET
    location = settings.MEDIA_FILES_LOCATION
    file_overwrite = False

Requirements.txt includes:

Django==3.0.3
gunicorn==20.0.4

django-model-utils==4.0.0
django-storages==1.9.1
boto3==1.13.15
htmlmin==0.1.12

sentry-sdk==0.14.3
slackclient==2.5.0
structlog==18.2.0
ddtrace==0.31.0
colorama==0.3.9
json-logging-py==0.2

When I removed the ManifestFilesMixin from the ManifestStaticFilesStorage class, collectstatic worked, but obviously not with hashed files or the staticfiles.json that I need.

I've spent multiple days trying to figure this out and I'm stumped as to what could be the cause. Any information would be appreciated.

Body:
Found an answer on another site from someone that was having a similar issue. It seems S3Boto3Storage is throwing IOError but ManifestFilesMixin is expecting FileNotFound. This solved my issue and I'm now seeing the hashed files in my S3 bucket along with a staticfiles.json.

class ManifestStaticFilesStorage(ManifestFilesMixin, S3Boto3Storage):
    bucket_name = settings.STATIC_FILES_BUCKET
    location = settings.STATIC_FILES_LOCATION

    def read_manifest(self):
        try:
            return super(ManifestStaticFilesStorage,self).read_manifest()
        except IOError:
            return None


问:
How do you get used area of a KonvaJs Stage to pass as height/width properties into the toImage function?
I'm using KonvaJs 3.2.4 (though I probably could upgrade) and am trying to use the toImage function of the Stage Class. It looks as though toImage() by default only returns an image of the visible area of the stage, hence the config property to pass in the starting coordinates, and the height/width of area to return in the image.

My primary goal is to return an image of the stage that includes every child shape in that image (I'm using it as a cover image for printing, etc). Is there a way I can easily get the area of the Stage that is being used? I'm imagining an outerbounds of the used area. I currently keep all my shapes in one view layer, and before I run this toImage, I ungroup all the shapes so there are no nested arrays of children below the view Layer.

I tried to loop through all the children and use their x/y attributes to establish the minX, maxX, minY, maxY, but this runs into issues when a shape is rotated since the x/y coordinates can no longer be guaranteed to represent the inner/outer bounds of the shape. I do allow users to rotate using the standard Transformer.

Any guidance would be massively appreciated!

答:
You can use node.getClientRect() to calculate total size of any Konva node. If you need to export a full image of the stage you can use this:

stage.toImage({
  ...stage.getClientRect(),
  callback: img => {
    console.log(img);
  }
})
```

Demo: https://jsbin.com/behoyoyeda/1/edit?html,js,output

Body:
You can use node.getClientRect() to calculate total size of any Konva node. If you need to export a full image of the stage you can use this:

stage.toImage({
  ...stage.getClientRect(),
  callback: img => {
    console.log(img);
  }
})

Demo: https://jsbin.com/behoyoyeda/1/edit?html,js,output


问:
Active checkbox changes table background color except for a cell
When the checkbox is inactive the table doesn't change, once the checkbox is clicked all the cells background color becomes yellow except for the middle one that becomes red.
That's the result I need to reach

label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table {
      background-color: yellow;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="it" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Check6</title>
  </head>
  <body>
    <label for="checkbox_id">CLICCA</label>
    <input type="checkbox" id="checkbox_id">
    <table class="tg">
<thead>
  <tr>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-0lax"></td>
    <td id="red"></td>
    <td class="tg-0lax"></td>
  </tr>
  <tr>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
  </tr>
</tbody>
</table>
  </body>
</html></code>```

Thanks already for the help.

答:
You just have to create a function that get if Checkbox is checked and give the id "red" a color

function myFunction() {
  var checkBox = document.getElementById("checkbox_id");
  var red = document.getElementById("red");
  if (checkBox.checked == true){
    red.style.backgroundColor = "red";
  } else {
     red.style.backgroundColor = "transparent";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table {
      background-color: yellow;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Check6</title>

    CLICCA
    <input type="checkbox" id="checkbox_id" onClick="myFunction()">

```

Body:
When the checkbox is inactive the table doesn't change, once the checkbox is clicked all the cells background color becomes yellow except for the middle one that becomes red.
That's the result I need to reach

label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table {
      background-color: yellow;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Check6</title>

    CLICCA
    <input type="checkbox" id="checkbox_id">

Thanks already for the help.

Body:
You just have to create a function that get if Checkbox is checked and give the id "red" a color

function myFunction() {
  var checkBox = document.getElementById("checkbox_id");
  var red = document.getElementById("red");
  if (checkBox.checked == true){
    red.style.backgroundColor = "red";
  } else {
     red.style.backgroundColor = "transparent";
  }
}

label {
      -webkit-appearance: button;
      -moz-appearance: button;
      appearance: button;
      display: inline-block;
      cursor: pointer;
      margin:5px;
    }

    #checkbox_id:checked + table {
      background-color: yellow;
    }

    /*Table styles*/
    .tg  {border-collapse:collapse;border-spacing:0;}
    .tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
      font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal; width: 50px; height: 50px;}
    .tg .tg-0lax{text-align:left;vertical-align:top}

<!DOCTYPE html>
<html lang="it" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Check6</title>
  </head>
  <body>
    <label for="checkbox_id">CLICCA</label>
    <input type="checkbox" id="checkbox_id" onClick="myFunction()">
    <table class="tg">
<thead>
  <tr>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
    <th class="tg-0lax"></th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-0lax"></td>
    <td id="red"></td>
    <td class="tg-0lax"></td>
  </tr>
  <tr>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
    <td class="tg-0lax"></td>
  </tr>
</tbody>
</table>
  </body>
</html>


问:
looping through nested arrays and accessing elements RUBY
I want to iterate through a nested array and operate on each element, so square each number in this case. I know how to do it for a normal array but for some reason i am getting undefined map method when include deeper iteration to access the inner arrays. Am a newbie too so if you could explain how it works that would help my learning. Thanks</p>

```<code>def SquareArrayElements(n)
  n.each do |number|
    number.map do |num|
     squared_nums = num * num
  end
end
squared_nums
end
SquareArrayElements([10,[[10],10],[10]])
</code>```

答:
You only need to call map on the arrays, not on the integers.  That's why you're getting an undefined map method, integers don't support that method.

Try

```<code>def square_array(element)
  if element.responds_to?(:map)
    element.map{|m| square_array(m)}
  else
    element * element
  end
end
</code>```

Body:
I want to iterate through a nested array and operate on each element, so square each number in this case. I know how to do it for a normal array but for some reason i am getting undefined map method when include deeper iteration to access the inner arrays. Am a newbie too so if you could explain how it works that would help my learning. Thanks

def SquareArrayElements(n)
  n.each do |number|
    number.map do |num|
     squared_nums = num * num
  end
end
squared_nums
end
SquareArrayElements([10,[[10],10],[10]])

Body:
You only need to call map on the arrays, not on the integers.  That's why you're getting an undefined map method, integers don't support that method.

Try

def square_array(element)
  if element.responds_to?(:map)
    element.map{|m| square_array(m)}
  else
    element * element
  end
end


问:
Index in postgresql
Firstly, I have a table in database USERS with almost 30 Million records in it. I have different indices for each column. But some of the column have only 2 to 3 non null values while others are Null but still their index size is 847 MB a little less than the one index that contain unique value for each row.

Can anyone know why is it like this?

Secondly, in PostgreSQL we have a index for primary key index for each column by default what if we delete that index what will be the consequences?
What that index is really use for?
As i'm searching based on values in other columns only will it be safe to delete index for primary key?

答:
NULL values are stored in indexes just like all other values, so the first part is not surprising.

You cannot delete the primary key index, what you could do is drop the primary key constraint. But then you cannot be certain that no duplicate rows get added to the table. If you think that is no problem, look at the many questions asking for help with exactly that problem.

Every table should have a primary key.

But it might be a good idea to get rid of some other indexes if you don't need them.

Title: Index in postgresql


问:
Native debug on Android
It has been a few years since I last needed to debug any native applications on Android. After poking around a bit I found this Google reference referring to gdbserver and gdbclient.py.

I found the former in the NDK

```<code>$NDK/prebuilt/android-arm[64]/gdbserver/gdbserver
</code>```

And the latter in the SDK

```<code>$SDK/development/scripts/gdbclient.py
</code>```

When I went to run the python script I am met with:

```<code>$ python gdbclient.py
Traceback (most recent call last):
  File "gdbclient.py", line 27, in <module>
    import gdbrunner
ImportError: No module named gdbrunner
</code>```

For the life of me I cannot find any information on what gdbrunner is. Nor have I found any other reference to it in the [S/N]DKs.

Any idea? Is there another method to debug native components of Android not reliant upon this script?

答:
I fear I overlooked it in the NDK. I must have been using an older version. The gdbrunner package is located at

```<code>$NDK/python-packages/gdbrunner
</code>```

Along with other useful things.

Title: Native debug on Android

Body:
It has been a few years since I last needed to debug any native applications on Android. After poking around a bit I found this Google reference referring to gdbserver and gdbclient.py.

I found the former in the NDK

$NDK/prebuilt/android-arm[64]/gdbserver/gdbserver

And the latter in the SDK

$SDK/development/scripts/gdbclient.py

When I went to run the python script I am met with:

$ python gdbclient.py
Traceback (most recent call last):
  File "gdbclient.py", line 27, in <module>
    import gdbrunner
ImportError: No module named gdbrunner

For the life of me I cannot find any information on what gdbrunner is. Nor have I found any other reference to it in the [S/N]DKs.

Any idea? Is there another method to debug native components of Android not reliant upon this script?

Body:
I fear I overlooked it in the NDK. I must have been using an older version. The gdbrunner package is located at

$NDK/python-packages/gdbrunner

Along with other useful things.