问:
How to get percentage of combinations computed?
I have this password generator, which comute combination with length of 2 to 6 characters from a list containing small letters, capital letters and numbers (without 0) - together 61 characters.

All I need is to show percentage (with a step of 5) of the combinations already created. I tried to compute all the combinations of selected length, from that number a boundary value (the 5 % step values) and count each combination written in text file and when when the count of combinations meets the boundary value, print the xxx % completed, but this code doesn't seem to work.

Do you know how to easily show the percentage please?

Sorry for my english, I'm not a native speaker.

Thank you all!

```<code>def pw_gen(characters, length):

    """generate all characters combinations with selected length and export them to a text file"""

    # counting number of combinations according to a formula in documentation
    k = length
    n = len(characters) + k - 1
    comb_numb = math.factorial(n)/(math.factorial(n-length)*math.factorial(length))

    x = 0

    # first value
    percent = 5

    # step of percent done to display
    step = 5

    # 'step' % of combinations
    boundary_value = comb_numb/(100/step)

    try:
        # output text file
        with open("password_combinations.txt", "a+") as f:
            for p in itertools.product(characters, repeat=length):
                combination = ''.join(p)

                # write each combination and create a new line
                f.write(combination + '\n')
                x += 1

                if boundary_value <= x <= comb_numb:
                    print("{} % complete".format(percent))
                    percent += step
                    boundary_value += comb_numb/(100/step)

                elif x > comb_numb:
                    break
</code>```

答:
Removed try:, since you are not handling any errors with expect.
Also removed elif:, this condition is never met anyway.
Besides, your formula for comb_numb is not the right one, since you're generating combinations with repetition. With those changes, your code is good.

```<code>import math, iterations, string
def pw_gen(characters, length):

    """generate all characters combinations with selected length and export them to a text file"""

    # counting number of combinations according to a formula in documentation
    comb_numb = len(characters) ** k

    x = 0

    # first value
    percent = 5

    # step of percent done to display
    step = 5

    # 'step' % of combinations
    boundary_value = comb_numb/(100/step)
    # output text file
    with open("password_combinations.txt", "a+") as f:
        for p in itertools.product(characters, repeat=length):
            combination = ''.join(p)
            # write each combination and create a new line
            f.write(combination + '\n')
            x += 1
            if boundary_value <= x:
                print("{} % complete".format(percent))
                percent += step
                boundary_value += comb_numb/(100/step)

pw_gen(string.ascii_letters, 4)
</code>```

Body:
I have this password generator, which comute combination with length of 2 to 6 characters from a list containing small letters, capital letters and numbers (without 0) - together 61 characters.

All I need is to show percentage (with a step of 5) of the combinations already created. I tried to compute all the combinations of selected length, from that number a boundary value (the 5 % step values) and count each combination written in text file and when when the count of combinations meets the boundary value, print the xxx % completed, but this code doesn't seem to work.

Do you know how to easily show the percentage please?

Sorry for my english, I'm not a native speaker.

Thank you all!

def pw_gen(characters, length):

    """generate all characters combinations with selected length and export them to a text file"""

    # counting number of combinations according to a formula in documentation
    k = length
    n = len(characters) + k - 1
    comb_numb = math.factorial(n)/(math.factorial(n-length)*math.factorial(length))

    x = 0

    # first value
    percent = 5

    # step of percent done to display
    step = 5

    # 'step' % of combinations
    boundary_value = comb_numb/(100/step)

    try:
        # output text file
        with open("password_combinations.txt", "a+") as f:
            for p in itertools.product(characters, repeat=length):
                combination = ''.join(p)

                # write each combination and create a new line
                f.write(combination + '\n')
                x += 1

                if boundary_value <= x <= comb_numb:
                    print("{} % complete".format(percent))
                    percent += step
                    boundary_value += comb_numb/(100/step)

                elif x > comb_numb:
                    break

Body:
Removed try:, since you are not handling any errors with expect.
Also removed elif:, this condition is never met anyway.
Besides, your formula for comb_numb is not the right one, since you're generating combinations with repetition. With those changes, your code is good.

import math, iterations, string
def pw_gen(characters, length):

    """generate all characters combinations with selected length and export them to a text file"""

    # counting number of combinations according to a formula in documentation
    comb_numb = len(characters) ** k

    x = 0

    # first value
    percent = 5

    # step of percent done to display
    step = 5

    # 'step' % of combinations
    boundary_value = comb_numb/(100/step)
    # output text file
    with open("password_combinations.txt", "a+") as f:
        for p in itertools.product(characters, repeat=length):
            combination = ''.join(p)
            # write each combination and create a new line
            f.write(combination + '\n')
            x += 1
            if boundary_value <= x:
                print("{} % complete".format(percent))
                percent += step
                boundary_value += comb_numb/(100/step)

pw_gen(string.ascii_letters, 4)


来源: stackexchange

问:
How to make code wait for okay/cancel button selection?
I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.

I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.

Here is my complete source code
http://pastebin.com/uw7bvtn7

The section where I have the problem is at line 127-151.

```<code>$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 600,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("<h3><b>Users</b></h3>" + makeDialogTable(users) + "<h3><b>Owners</b></h3>" + makeDialogTable(owners));
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },

    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    } // buttons

}); // dialog

alert(is_okay);
</code>```

What the code does right now is to first show the dialog and then the alert(is_okay) on top.

What I would like is that the code first continues when the user have pressed OK or Cancel.

How could that be done?

答:
You can put your additional code in the "Okay" and "Cancel" button functions. For example:</p>

```<code>"Okay": function() {
    $(this).dialog("close");
    alert(is_okay);
},
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.

I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.

Here is my complete source code
http://pastebin.com/uw7bvtn7

The section where I have the problem is at line 127-151.

$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 600,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("
Users
" + makeDialogTable(users) + "
Owners
" + makeDialogTable(owners));
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },

    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    } // buttons

}); // dialog

alert(is_okay);

What the code does right now is to first show the dialog and then the alert(is_okay) on top.

What I would like is that the code first continues when the user have pressed OK or Cancel.

How could that be done?

Body:
You can put your additional code in the "Okay" and "Cancel" button functions. For example:

"Okay": function() {
    $(this).dialog("close");
    alert(is_okay);
},


问:
ATS policy issue when using a redirect url in Swift
I am using this link for example to load the link. Although the link is a http link it will be redirected to a https link. It works in the browser.
However, as soon as I let my iOS Application load the resource it will say "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.".

I am using this library to load the picture. Is it not supported that Swift loads the https resource? I could think of that ATS blocks the connection to the server so the redirect can't even be received.

I would be very thankful for any thoughts on this.

Christian

答:
While you certainly can disable the entirety of ATS using the solutions provided by Kishan and Johnson, if you know the domain of the http resource you are trying to load, you have better options.  For details of why the disabling of ATS entirely is not the best idea, see this post.

Better options are:

If you know the http resource is always going to give you a redirect to the same https:// url, why not simply use the https:// url in your code.  This won't work if the redirect is dynamic, but if your code is trying to load http://www.example.com/resource and that always redirects to https://www.example.com/resource, why not just change your code to go to the https version.

Only disable ATS for the domain in where you need to allow non https connections. This allows you to only allow http connections for domains you know don't support https, better protecting your application users.
Your ATS settings in your info.plist wqould look something like this:

If and only if your urls are driven by data that you don't control (i.e. the domains in those urls could be anything), you will need to disable all of ATS, and Apple may eventually want you to provide justification for disabling it.  Originally they were going to have all ATS disabled apps go through an additional justification request processs, but they haven't mentioned that recently.  This should be a last resort.

Honestly, looking at your example UR

ContentLicense: CC BY-SA 4.0


问:
Li click is not working with select2 plugin
I have a select menu built with select2 plugin. I need to add a class to <select> when click menu options. Tested with alert it's not working.

https://jsfiddle.net/ysm4qhof/1/

```<code>$(document).ready(function(){
$('.select2-results__option').on('click', function(){
   alert("Hello! I am an alert box!");
});
});
</code>```

Tried with clicking ul but that also not working.

```<code>$(document).ready(function(){
    $('.select2 .select2-results__options').on('click', function(){
       alert("Hello! I am an alert box!");
    });
    });
</code>```

It should be working but what am I missing here?

答:
You can use on select event of select 2 plugin.

```<code>$('.js-select2').on('select2:select', function (e) {
  alert("Hello! I am an alert box!");
});
</code>```

Check here for select2 documentation

https://select2.org/programmatic-control/events

Body:
I have a select menu built with select2 plugin. I need to add a class to <select> when click menu options. Tested with alert it's not working.

https://jsfiddle.net/ysm4qhof/1/

$(document).ready(function(){
$('.select2-results__option').on('click', function(){
   alert("Hello! I am an alert box!");
});
});

Tried with clicking ul but that also not working.

$(document).ready(function(){
    $('.select2 .select2-results__options').on('click', function(){
       alert("Hello! I am an alert box!");
    });
    });

It should be working but what am I missing here?

Body:
You can use on select event of select 2 plugin.

$('.js-select2').on('select2:select', function (e) {
  alert("Hello! I am an alert box!");
});

Check here for select2 documentation

https://select2.org/programmatic-control/events


问:
Multiple value parameter ssrs performance issues
So I'm making a report in Reportbuilder 2012 3.0. One of my parameters has thousands of values that I can select separately or all at once. Problem is that when I want to select it takes an immensely long time to load. Also when I choose a few it takes an incredible long time to load the report. Is there a way to make the performance better? I really need all of them in the list.</p>

答:
An approach which can give significant speed-up in reports with a large number (5+) parameters is as follows:</p>

```<code>    select * into #mytable
    from (select
              field1,
              field2,
              field3,
              ...
          from
              table1
          join
          join
          more joins
          where
              (optional hard-coded criteria)
         ) as x

    select * from #mytable
    where
        field1 in (@param1)
        and field2 in (@param2)
        and field3 in (@param3)
        ...

    drop table #mytable
</code>```

Body:
An approach which can give significant speed-up in reports with a large number (5+) parameters is as follows:

    select * into #mytable
    from (select
              field1,
              field2,
              field3,
              ...
          from
              table1
          join
          join
          more joins
          where
              (optional hard-coded criteria)
         ) as x

    select * from #mytable
    where
        field1 in (@param1)
        and field2 in (@param2)
        and field3 in (@param3)
        ...

    drop table #mytable


问:
setting sample_weight_mode="temporal" doesn't seem to work
I am working with LSTM in tensorflow 2.0 and I am trying to assign a weight to the training samples (I've already tried with class_weights dictionary but it complains that 3-d arrays are not supported for it. my array shape is (26000, 7, 1)).

As suggested in the documentation, I am setting sample_weight_mode to "temporal" in compile, but after that when I try to fit the model I still get the error below:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-100-1bb94008291c> in <module>
      1 with tf.device("/device:GPU:0"):
----> 2     model.fit(X, y, epochs=500, batch_size=4096, verbose=1, validation_split=0.2, sample_weight=cw.reshape(26000,7,1))

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    641         max_queue_size=max_queue_size,
    642         workers=workers,
--> 643         use_multiprocessing=use_multiprocessing)
    644
    645   def evaluate(self,

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py in fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, **kwargs)
    630         steps=steps_per_epoch,
    631         validation_split=validation_split,
--> 632         shuffle=shuffle)
    633
    634     if validation_data:

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, steps, validation_split, shuffle, extract_tensors_from_dataset)
   2459           training_utils.standardize_weights(ref, sw, cw, mode)
   2460           for (ref, sw, cw, mode) in zip(y, sample_weights, class_weights,
-> 2461                                          feed_sample_weight_modes)
   2462       ]
   2463       # Check that all arrays have the same length.

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training.py in <listcomp>(.0)
   2458       sample_weights = [
   2459           training_utils.standardize_weights(ref, sw, cw, mode)
-> 2460           for (ref, sw, cw, mode) in zip(y, sample_weights, class_weights,
   2461                                          feed_sample_weight_modes)
   2462       ]

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training_utils.py in standardize_weights(y, sample_weight, class_weight, sample_weight_mode)
    839     if sample_weight is not None and len(sample_weight.shape) != 1:
    840       raise ValueError('Found a sample_weight array with shape ' +
--> 841                        str(sample_weight.shape) + '. '
    842                        'In order to use timestep-wise sample weights, '
    843                        'you should specify '

ValueError: Found a sample_weight array with shape (26000, 7, 1). In order to use timestep-wise sample weights, you should specify sample_weight_mode="temporal" in compile(). If you just mean to use sample-wise weights, make sure your sample_weight array is 1D.
</code>```

I have already tried changing the shape of the sample_weights passed in fit (also tried to flatten it), setting shuffle to False and removing the validation split without success.

Here's the code I am using

```<code>import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import math

# Import TensorFlow
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop, Adam, SGD
from tensorflow.keras.layers import SimpleRNN, LSTM, Dense
from tensorflow.keras.models import Sequential

from sklearn.utils import class_weight

class_weights = class_weight.compute_class_weight('balanced',
                                                 np.unique(y_train),
                                                 y_train)

cw = class_weight.compute_sample_weight({False:1, True:50},#'balanced',
                                                 #np.unique(y_train),
                                                 y.flatten())

model = Sequential()
model.add(LSTM(160, return_sequences=True, dropout=0.05))
model.add(LSTM(80, return_sequences=True, dropout=0.05, activation='relu'))
model.add(LSTM(40, return_sequences=True, dropout=0.05, activation='relu'))
model.add(LSTM(10, return_sequences=True, dropout=0.05))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc', tf.keras.metrics.AUC()], sample_weight_mode="temporal")

with tf.device("/device:GPU:0"):
    model.fit(X, y, epochs=500, batch_size=4096, verbose=1, validation_split=0.2, sample_weight=cw.reshape(26000,7,1))
</code>```

答:
The dimension of sample_weight cannot be greater than 2. If sample_weight_mode in the compile function is None, then sample_weight must be 1 dimensional. If sample_weight_mode in the compile function is 'temporal', then sample_weight must be 2 dimensional.
Additionally, it is always be true that y.shape[:sample_weight.ndim] == sample_weight.shape.
For more details, please refer to the source code of keras.engine.training_utils.standardize_weights.

Body:
I am working with LSTM in tensorflow 2.0 and I am trying to assign a weight to the training samples (I've already tried with class_weights dictionary but it complains that 3-d arrays are not supported for it. my array shape is (26000, 7, 1)).

As suggested in the documentation, I am setting sample_weight_mode to "temporal" in compile, but after that when I try to fit the model I still get the error below:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-100-1bb94008291c> in <module>
      1 with tf.device("/device:GPU:0"):
----> 2     model.fit(X, y, epochs=500, batch_size=4096, verbose=1, validation_split=0.2, sample_weight=cw.reshape(26000,7,1))

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    641         max_queue_size=max_queue_size,
    642         workers=workers,
--> 643         use_multiprocessing=use_multiprocessing)
    644
    645   def evaluate(self,

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py in fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, **kwargs)
    630         steps=steps_per_epoch,
    631         validation_split=validation_split,
--> 632         shuffle=shuffle)
    633
    634     if validation_data:

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, steps, validation_split, shuffle, extract_tensors_from_dataset)
   2459           training_utils.standardize_weights(ref, sw, cw, mode)
   2460           for (ref, sw, cw, mode) in zip(y, sample_weights, class_weights,
-> 2461                                          feed_sample_weight_modes)
   2462       ]
   2463       # Check that all arrays have the same length.

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training.py in <listcomp>(.0)
   2458       sample_weights = [
   2459           training_utils.standardize_weights(ref, sw, cw, mode)
-> 2460           for (ref, sw, cw, mode) in zip(y, sample_weights, class_weights,
   2461                                          feed_sample_weight_modes)
   2462       ]

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training_utils.py in standardize_weights(y, sample_weight, class_weight, sample_weight_mode)
    839     if sample_weight is not None and len(sample_weight.shape) != 1:
    840       raise ValueError('Found a sample_weight array with shape ' +
--> 841                        str(sample_weight.shape) + '. '
    842                        'In order to use timestep-wise sample weights, '
    843                        'you should specify '

ValueError: Found a sample_weight array with shape (26000, 7, 1). In order to use timestep-wise sample weights, you should specify sample_weight_mode="temporal" in compile(). If you just mean to use sample-wise weights, make sure your sample_weight array is 1D.

I have already tried changing the shape of the sample_weights passed in fit (also tried to flatten it), setting shuffle to False and removing the validation split without success.

Here's the code I am using

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import math

# Import TensorFlow
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop, Adam, SGD
from tensorflow.keras.layers import SimpleRNN, LSTM, Dense
from tensorflow.keras.models import Sequential

from sklearn.utils import class_weight

class_weights = class_weight.compute_class_weight('balanced',
                                                 np.unique(y_train),
                                                 y_train)

cw = class_weight.compute_sample_weight({False:1, True:50},#'balanced',
                                                 #np.unique(y_train),
                                                 y.flatten())

model = Sequential()
model.add(LSTM(160, return_sequences=True, dropout=0.05))
model.add(LSTM(80, return_sequences=True, dropout=0.05, activation='relu'))
model.add(LSTM(40, return_sequences=True, dropout=0.05, activation='relu'))
model.add(LSTM(10, return_sequences=True, dropout=0.05))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc', tf.keras.metrics.AUC()], sample_weight_mode="temporal")

with tf.device("/device:GPU:0"):
    model.fit(X, y, epochs=500, batch_size=4096, verbose=1, validation_split=0.2, sample_weight=cw.reshape(26000,7,1))


问:
joint.shapes.uml.js: Uncaught TypeError: Cannot read property 'Generic' of undefined
I display uml diagram from JointJS demo https://github.com/clientIO/joint/tree/master/demo/umlcd in Angular 8 and I get an error: joint.shapes.uml.js:13 Uncaught TypeError: Cannot read property 'Generic' of undefined

at joint.shapes.uml.js:13

 at joint.shapes.uml.js:280

joint.shapes.uml.js: https://github.com/clientIO/joint/blob/master/dist/joint.shapes.uml.js

What am I doing wrong?

Here's my code:

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "Inspector": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/Inspector",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": false,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css",
              "./node_modules/jointjs/dist/joint.css",
              "./src/app/shared/umlcd.css"
            ],
            "scripts": [
              "./node_modules/jquery/dist/jquery.js",
              "./node_modules/lodash/lodash.js",
              "./node_modules/backbone/backbone.js",
              "./plugin/joint.shapes.uml.js",
              "./node_modules/jointjs/dist/joint.js"
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "Inspector:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "Inspector:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "Inspector:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "Inspector:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "Inspector:serve:production"
            }
          }
        }
      }
    }},
  "defaultProject": "Inspector"
}

```

<p><strong>Typescript file with jointJS demo code:</strong></p>

<p>(I had to make changes in the demo code like: each diagram entity must have an array of attributes and methods and property <em>name</em> must be of type String [] instead of String. Without these changes the demo code didn't work.)</p>

<pre class="lang-js prettyprint-override"><code>import { Component, OnInit} from '@angular/core';

import * as _ from 'lodash';
import * as joint from 'jointjs';

@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.css']
})
export class DemoComponent implements OnInit{

  constructor() { }

  ngOnInit() {
    this.createDiagram();
  }

  private createDiagram(): void {
    var graph = new joint.dia.Graph();

    new joint.dia.Paper({
        el: document.getElementById('paper'),
        width: 1000,
        height: 600,
        model: graph,
        gridSize: 1,
    });

    var uml = joint.shapes.uml;

    var classes = {

        mammal: new uml.Interface({
            position: { x:300  , y: 150 },
            size: { width: 240, height: 100 },
            name: ['Mammal'],
            attributes: ['dob: Date'],
            methods: ['+ setDateOfBirth(dob: Date): Void','+ getAgeAsDays(): Numeric'],
            attrs: {
                '.uml-class-name-rect': {
                    fill: '#feb662',
                    stroke: '#000000',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-rect': {
                    fill: '#fdc886',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-rect': {
                    fill: '#fdc886',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-text': {
                    ref: '.uml-class-attrs-rect',
                    'ref-y': 0.5,
                    'y-alignment': 'middle'
                },
                '.uml-class-methods-text': {
                    ref: '.uml-class-methods-rect',
                    'ref-y': 0.5,
                    'y-alignment': 'middle'
                }

            }
        }),

        person: new uml.Abstract({
            position: { x:300  , y: 300 },
            size: { width: 260, height: 100 },
            name: ['Person'],
            attributes: ['firstName: String','lastName: String'],
            methods: ['+ setName(first: String, last: String): Void','+ getName(): String'],
            attrs: {
                '.uml-class-name-rect': {
                    fill: '#68ddd5',
                    stroke: '#ffffff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-rect': {
                    fill: '#9687fe',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-rect': {
                    fill: '#9687fe',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-text, .uml-class-attrs-text': {
                    fill: '#fff'
                }
            }
        }),

        bloodgroup: new uml.Class({
            position: { x:20  , y: 190 },
            size: { width: 220, height: 100 },
            name: ['BloodGroup'],
            attributes: ['bloodGroup: String'],
            methods: ['+ isCompatible(bG: String): Boolean'],
            attrs: {
                '.uml-class-name-rect': {
                    fill: '#ff8450',
                    stroke: '#fff',
                    'stroke-width': 0.5,
                },
                '.uml-class-attrs-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-text': {
                    ref: '.uml-class-attrs-rect',
                    'ref-y': 0.5,
                    'y-alignment': 'middle'
                },
                '.uml-class-methods-text': {
                    ref: '.uml-class-methods-rect',
                    'ref-y': 0.5,
                    'y-alignment': 'middle'
                }
            }
        }),

        address: new uml.Class({
            position: { x:630  , y: 190 },
            size: { width: 160, height: 100 },
            name: ['Address'],
            attributes: ['houseNumber: Integer','streetName: String','town: String','postcode: String'],
            methods: [],
            attrs: {
                '.uml-class-name-rect': {
                    fill: '#ff8450',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-text': {
                    'ref-y': 0.5,
                    'y-alignment': 'middle'
                }
            }

        }),

        man: new uml.Class({
            position: { x:200  , y: 500 },
            size: { width: 180, height: 50 },
            name: ['Man'],
            attributes: [],
            methods: [],
            attrs: {
                '.uml-class-name-rect': {
                    fill: '#ff8450',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                }
            }
        }),

        woman: new uml.Class({
            position: { x:450  , y: 500 },
            size: { width: 180, height: 50 },
            name: ['Woman'],
            attributes: [],
            methods: ['+ giveABrith(): Person []'],
            attrs: {
                '.uml-class-name-rect': {
                    fill: '#ff8450',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-text': {
                    'ref-y': 0.5,
                    'y-alignment': 'middle'
                }
            }
        })
    };

    Object.keys(classes).forEach(function(key) {
        graph.addCell(classes[key]);
    });

    var relations = [
        new uml.Generalization({ source: { id: classes.man.id }, target: { id: classes.person.id }}),
        new uml.Generalization({ source: { id: classes.woman.id }, target: { id: classes.person.id }}),
        new uml.Implementation({ source: { id: classes.person.id }, target: { id: classes.mammal.id }}),
        new uml.Aggregation({ source: { id: classes.person.id }, target: { id: classes.address.id }}),
        new uml.Composition({ source: { id: classes.person.id }, target: { id: classes.bloodgroup.id }})
    ];

    Object.keys(relations).forEach(function(key) {
        graph.addCell(relations[key]);
    });
  }

}

</code>```

答:
In your angular.json the order of scripts to include in the build is wrong.

joint.shapes.uml.js should be executed after joint.js is executed.

Correct order

 "scripts": [
              "./node_modules/jquery/dist/jquery.js",
              "./node_modules/lodash/lodash.js",
              "./node_modules/backbone/backbone.js",
              "./node_modules/jointjs/dist/joint.js"
              "./plugin/joint.shapes.uml.js",
            ]
```

Body:
I display uml diagram from JointJS demo https://github.com/clientIO/joint/tree/master/demo/umlcd in Angular 8 and I get an error: joint.shapes.uml.js:13 Uncaught TypeError: Cannot read property 'Generic' of undefined

at joint.shapes.uml.js:13

 at joint.shapes.uml.js:280

joint.shapes.uml.js: https://github.com/clientIO/joint/blob/master/dist/joint.shapes.uml.js

What am I doing wrong?

Here's my code:

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "Inspector": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/Inspector",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": false,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css",
              "./node_modules/jointjs/dist/joint.css",
              "./src/app/shared/umlcd.css"
            ],
            "scripts": [
              "./node_modules/jquery/dist/jquery.js",
              "./node_modules/lodash/lodash.js",
              "./node_modules/backbone/backbone.js",
              "./plugin/joint.shapes.uml.js",
              "./node_modules/jointjs/dist/joint.js"
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "Inspector:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "Inspector:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "Inspector:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "Inspector:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "Inspector:serve:production"
            }
          }
        }
      }
    }},
  "defaultProject": "Inspector"
}

Typescript file with jointJS demo code:

(I had to make changes in the demo code like: each diagram entity must have an array of attributes and methods and property name must be of type String [] instead of String. Without these changes the demo code didn't work.)

import { Component, OnInit} from '@angular/core';

import * as _ from 'lodash';
import * as joint from 'jointjs';

@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.css']
})
export class DemoComponent implements OnInit{

  constructor() { }

  ngOnInit() {
    this.createDiagram();
  }

  private createDiagram(): void {
    var graph = new joint.dia.Graph();

    new joint.dia.Paper({
        el: document.getElementById('paper'),
        width: 1000,
        height: 600,
        model: graph,
        gridSize: 1,
    });

    var uml = joint.shapes.uml;

    var classes = {

        mammal: new uml.Interface({
            position: { x:300  , y: 150 },
            size: { width: 240, height: 100 },
            name: ['Mammal'],
            attributes: ['dob: Date'],
            methods: ['+ setDateOfBirth(dob: Date): Void','+ getAgeAsDays(): Numeric'],
            attrs: {
                '.uml-class-name-rect': {
                    fill: '#feb662',
                    stroke: '#000000',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-rect': {
                    fill: '#fdc886',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-rect': {
                    fill: '#fdc886',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-text': {
                    ref: '.uml-class-attrs-rect',
                    'ref-y': 0.5,
                    'y-alignment': 'middle'
                },
                '.uml-class-methods-text': {
                    ref: '.uml-class-methods-rect',
                    'ref-y': 0.5,
                    'y-alignment': 'middle'
                }

            }
        }),

        person: new uml.Abstract({
            position: { x:300  , y: 300 },
            size: { width: 260, height: 100 },
            name: ['Person'],
            attributes: ['firstName: String','lastName: String'],
            methods: ['+ setName(first: String, last: String): Void','+ getName(): String'],
            attrs: {
                '.uml-class-name-rect': {
                    fill: '#68ddd5',
                    stroke: '#ffffff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-rect': {
                    fill: '#9687fe',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-rect': {
                    fill: '#9687fe',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-text, .uml-class-attrs-text': {
                    fill: '#fff'
                }
            }
        }),

        bloodgroup: new uml.Class({
            position: { x:20  , y: 190 },
            size: { width: 220, height: 100 },
            name: ['BloodGroup'],
            attributes: ['bloodGroup: String'],
            methods: ['+ isCompatible(bG: String): Boolean'],
            attrs: {
                '.uml-class-name-rect': {
                    fill: '#ff8450',
                    stroke: '#fff',
                    'stroke-width': 0.5,
                },
                '.uml-class-attrs-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-text': {
                    ref: '.uml-class-attrs-rect',
                    'ref-y': 0.5,
                    'y-alignment': 'middle'
                },
                '.uml-class-methods-text': {
                    ref: '.uml-class-methods-rect',
                    'ref-y': 0.5,
                    'y-alignment': 'middle'
                }
            }
        }),

        address: new uml.Class({
            position: { x:630  , y: 190 },
            size: { width: 160, height: 100 },
            name: ['Address'],
            attributes: ['houseNumber: Integer','streetName: String','town: String','postcode: String'],
            methods: [],
            attrs: {
                '.uml-class-name-rect': {
                    fill: '#ff8450',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-text': {
                    'ref-y': 0.5,
                    'y-alignment': 'middle'
                }
            }

        }),

        man: new uml.Class({
            position: { x:200  , y: 500 },
            size: { width: 180, height: 50 },
            name: ['Man'],
            attributes: [],
            methods: [],
            attrs: {
                '.uml-class-name-rect': {
                    fill: '#ff8450',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                }
            }
        }),

        woman: new uml.Class({
            position: { x:450  , y: 500 },
            size: { width: 180, height: 50 },
            name: ['Woman'],
            attributes: [],
            methods: ['+ giveABrith(): Person []'],
            attrs: {
                '.uml-class-name-rect': {
                    fill: '#ff8450',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-attrs-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-rect': {
                    fill: '#fe976a',
                    stroke: '#fff',
                    'stroke-width': 0.5
                },
                '.uml-class-methods-text': {
                    'ref-y': 0.5,
                    'y-alignment': 'middle'
                }
            }
        })
    };

    Object.keys(classes).forEach(function(key) {
        graph.addCell(classes[key]);
    });

    var relations = [
        new uml.Generalization({ source: { id: classes.man.id }, target: { id: classes.person.id }}),
        new uml.Generalization({ source: { id: classes.woman.id }, target: { id: classes.person.id }}),
        new uml.Implementation({ source: { id: classes.person.id }, target: { id: classes.mammal.id }}),
        new uml.Aggregation({ source: { id: classes.person.id }, target: { id: classes.address.id }}),
        new uml.Composition({ source: { id: classes.person.id }, target: { id: classes.bloodgroup.id }})
    ];

    Object.keys(relations).forEach(function(key) {
        graph.addCell(relations[key]);
    });
  }

}


问:
how to index data from database using solr
I configured Import Handler for fatching data from MySql data base. In the solr example which i downloaded from net in C:\apache-solr-1.4.0\example\example-DIH\solr\db\lib there is hsqldb-1.8.0.10.jar.
I want to know:

since i am using MySQL do i need to
  put jar for MySql.

答:
please be sure to check out the Solr Wiki as it very much describes the process of indexing data from a MySQL database.

As for you question regarding where to put the MySQL connector jar (in my case it is called the "mysql-connector-java-5.1.12-bin.jar")... you will need to place this jar in the C:\apache-solr-3.1.0\example\lib\ folder.

Hope that helps!


问:
powershell equivalent for curl command
Looking for a powershell equivalent to the following CURL command:

```<code>curl -x "http://username:password@192.168.1.1:5001" "https://www.google.com"
</code>```

Have looked online but could not find anything similar to this.

答:
The PowerShell equivalent would be the following command:</p>
```<code>Invoke-Webrequest -Proxy "http://username:password@192.168.1.1:5001" -Uri "https://www.google.com"
</code>```

Title: powershell equivalent for curl command

Body:
Looking for a powershell equivalent to the following CURL command:

curl -x "http://username:password@192.168.1.1:5001" "https://www.google.com"

Have looked online but could not find anything similar to this.

Body:
The PowerShell equivalent would be the following command:

Invoke-Webrequest -Proxy "http://username:password@192.168.1.1:5001" -Uri "https://www.google.com"


问:
How to view Docker image layers on Docker Hub?
I know that I can use this command $ docker images --tree docker history to view the layers of a Docker image, but how do I do that for images on Docker Hub without pulling it?  This is so that I know what is on an image before I download it.

E.g., for the Tomcat repo, https://registry.hub.docker.com/_/tomcat/, the webpage doesn't seem to show what is on the image.  I have to look at the Dockerfile on Github to find out.

Update
I see this repo https://registry.hub.docker.com/u/tutum/tomcat/ has more tabs.  The "Dockerfile" tab shows how it is created, but only seems to show the latest version.  Is there no choice to view the file for other tags?

答: This is now possible by clicking into the image tag on Docker Hub.


问:
Add plugin to vu Instance as "Vue.use()" without the root vue js file
I'm working on a Directus Project.
Directus is a Headless CMS made in PHP and Vue.js.

I would like to use a theme or a plugin like Vuetify on a custom page.
A plugin is often called like this:

import Vue from 'vue'; // Something like that

Vue.use(...)
```

But i don't have access to the file where Vue is instantiated.

Do you know if i can add plugins and themes from children files project ? How ?

I thank you by advance for your future responses!!

Cordially,

Nicolas

答:
Yes, you can add plugins after the Vue instance was create.

See the bellow example:

<template>

    <button type="button" @click="installPlugin">install plugin</button>
    <button type="button" @click="callPlugin">call plugin</button>

</template>

```

In this example, the plugin was installed and called in a child component.

Body:
I'm working on a Directus Project.
Directus is a Headless CMS made in PHP and Vue.js.

I would like to use a theme or a plugin like Vuetify on a custom page.
A plugin is often called like this:

import Vue from 'vue'; // Something like that

Vue.use(...)

But i don't have access to the file where Vue is instantiated.

Do you know if i can add plugins and themes from children files project ? How ?

I thank you by advance for your future responses!!

Cordially,

Nicolas

Body:
Yes, you can add plugins after the Vue instance was create.

See the bellow example:

<template>
  <div>
    <button type="button" @click="installPlugin">install plugin</button>
    <button type="button" @click="callPlugin">call plugin</button>
  </div>
</template>

<script>
export default {
  name: 'app',
  methods: {
    installPlugin() {
      this.$root.constructor.use({
        install(Vue, options) {
          console.log('plugin was installed');
          Vue.prototype.$test = () => console.log('plugin was called');
        },
      });
    },
    callPlugin() {
      this.$test();
    },
  },
};
</script>

In this example, the plugin was installed and called in a child component.


问:
How to overlay image with color in CSS?

Objective

I want a color overlay on this header element. How can I do this with CSS?

Code

#header {
  /* Original url */
  /*background: url(../img/bg.jpg) 0 0 no-repeat fixed;*/
  background: url(https://fakeimg.pl/250x100/) 0 0 no-repeat fixed;
  height: 100%;
  overflow: hidden;
  color: #FFFFFF
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header id="header">
  <div class="row">
    <div class="col-xs-12">
      ...
    </div>
  </div>
</header></code>```

答:
You can do that in one line of CSS.

```<code>background: linear-gradient(to top, #3204fdba, #9907facc), url(https://picsum.photos/1280/853/?random=1) no-repeat top center;
</code>```

You can also modify the opacity of a color by hovering over it in VS Code and clicking on it to make it a hex color. It can be shortened to (#3204fde6, #9907fae6) instead of the rgba (rgba(48, 3, 252, 0.902), rgba(153, 7, 250, 0.902).

header {
  height: 100vh;
  width: 100%;
  color: white;
  font: bold 6.5em/2em monospace;
  display: flex;
  justify-content: center;
  align-items: center;

  background: linear-gradient(to top, #3204fdba, #9907facc), url(https://picsum.photos/1280/853/?random=1) no-repeat top center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>Hello World</header></code>```

See here CodePen

Title: How to overlay image with color in CSS?

Body:
Objective

I want a color overlay on this header element. How can I do this with CSS?

Code

#header {
  /* Original url */
  /*background: url(../img/bg.jpg) 0 0 no-repeat fixed;*/
  background: url(https://fakeimg.pl/250x100/) 0 0 no-repeat fixed;
  height: 100%;
  overflow: hidden;
  color: #FFFFFF
}

      ...

Body:
You can do that in one line of CSS.

background: linear-gradient(to top, #3204fdba, #9907facc), url(https://picsum.photos/1280/853/?random=1) no-repeat top center;

You can also modify the opacity of a color by hovering over it in VS Code and clicking on it to make it a hex color. It can be shortened to (#3204fde6, #9907fae6) instead of the rgba (rgba(48, 3, 252, 0.902), rgba(153, 7, 250, 0.902).

header {
  height: 100vh;
  width: 100%;
  color: white;
  font: bold 6.5em/2em monospace;
  display: flex;
  justify-content: center;
  align-items: center;

  background: linear-gradient(to top, #3204fdba, #9907facc), url(https://picsum.photos/1280/853/?random=1) no-repeat top center;
}

<header>Hello World</header>

See here CodePen


问:
Simple array sorting program showing incorrect output
When I run the given program I get the output as:

```<code>-2 -2 -2 -2
</code>```

The code is given below:

```<code>#include<iostream>
using namespace std;

int main(){
int a;
int arr[4]={7,-1,0,-2};
for(int i=0;i<4;i++){
    a=i;
    for(int j=i+1;j<4;j++){
        if(arr[j]<arr[a])
            a=j;
    }
 arr[i] = arr[a];
}
for(int z=0;z<4;z++)
    cout<<arr[z]<<"\t";
return 0;
}
</code>```

Where am I making the mistake?

答:
Currently you are overwriting the elements. You can swap elements with std::swap:</p>

```<code>#include <iostream>
using std::cout;

int main(){
    int a;
    int arr[4] = {7, -1 , 0, -2};
    for(int i = 0; i < 4; ++i){
        a = i;
        for(int j = i + 1; j < 4; ++j){
            if(arr[j] < arr[a])
               a = j;
        }
        std::swap(arr[i], arr[a]);
    }
    for(const auto &el: arr)
        cout << el << '\t';
    return 0;
}
</code>```

Body:
When I run the given program I get the output as:

-2 -2 -2 -2

The code is given below:

#include<iostream>
using namespace std;

int main(){
int a;
int arr[4]={7,-1,0,-2};
for(int i=0;i<4;i++){
    a=i;
    for(int j=i+1;j<4;j++){
        if(arr[j]<arr[a])
            a=j;
    }
 arr[i] = arr[a];
}
for(int z=0;z<4;z++)
    cout<<arr[z]<<"\t";
return 0;
}

Where am I making the mistake?

Body:
Currently you are overwriting the elements. You can swap elements with std::swap:

#include <iostream>
using std::cout;

int main(){
    int a;
    int arr[4] = {7, -1 , 0, -2};
    for(int i = 0; i < 4; ++i){
        a = i;
        for(int j = i + 1; j < 4; ++j){
            if(arr[j] < arr[a])
               a = j;
        }
        std::swap(arr[i], arr[a]);
    }
    for(const auto &el: arr)
        cout << el << '\t';
    return 0;
}


问:
Disable let's encrypt certbot daily renew emails
Is it possible to tell certbot not to email me every day when running on cronjob?

My cronjob is:

```<code>0 0 * * * sudo /usr/bin/certbot renew --post-hook "sudo service nginx reload"
</code>```

And I get emails:

```<code>Cert not yet due for renewal
</code>```

I only want to get emailed when a certificate is up for renewal, failed to renew, or has been renewed.

I don't need to be notified daily that there is nothing to renew.

答:
As far as I know certbot never sends any emails, it's just a command line utility. It's letsencrypt.org who sends certificate expiration notice. But it only sends email when the certificate is about to expire for a domain whose certificate was procured using your email (by --email flag of certbot).

I assume there is some other custom service or script which is sending this email.

Body:
Is it possible to tell certbot not to email me every day when running on cronjob?

My cronjob is:

0 0 * * * sudo /usr/bin/certbot renew --post-hook "sudo service nginx reload"

And I get emails:

Cert not yet due for renewal

I only want to get emailed when a certificate is up for renewal, failed to renew, or has been renewed.

I don't need to be notified daily that there is nothing to renew.


问:
Group by and Count(*) in Datastax Search/Solr
Hi we have a solr index with diff fields in it like business,businessType, regionName, StateName, .....

Now I need a solr query to get the number of business of type businessType ='event' group by regionName.

if I want to write a sql query for this it would be select region_name , Count(business) from solr where businessType='event' group by region_name

Any pointer would be helpful

答:
Use facets. Your solr query will look like, q=:&fq=businessType:event&facet=true&facet.field=region_name&rows=0

if want to group by on multiple fields then we need to do facet.pivot=state,region_name


问:
Bug or am I doing something wrong? Usercontrol Painting
```<code>private void UserControl1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawEllipse(Pens.Black, new Rectangle(-200, -500, this.Width + 400, this.Height + 420));
}
</code>```

Paste the above code into a usercontrol. Drop the usercontrol onto a form and anchor it to all 4 points.

In the designer (Under Visual Studio 2010) it renders perfectly (even as you resize). Run it and try and resize the form and the ellipse becomes skewed.

Here are two examples both after resizes the first while running, the second in the designer.

Obviously the behavior in the designer can't always be assumed to be the same (Although it would be nice) but my understanding is that the code above is completely legal. Am I wrong?

答:
Stecya has posted the "fix", but omitted an explanation detailing why that works or why you're seeing a discrepancy between the behavior in the designer and in the running application. In my mind, that makes the answer only minimally useful, so I thought I'd weigh in with an attempt at an explanation.

You already know that calling the Invalidate method is the solution. What this does is tell Windows that the entire surface area of the control needs to be redrawn the next time the window gets painted. Simple enough, but why don't you have to do this in the designer?

The answer lies in the fact that you're running the program with the Windows Aero theme enabled. Aero uses an entirely new window manager called the Desktop Window Manager (or DWM for short) based on composition. Each window is double-buffered, meaning that its graphics are rendered off-screen into a temporary bitmap, and only then blitted to the screen. This allows all sorts of cool effects and fancy transitions that users seem to like nowadays.

But, of course, it means that the sections that have already been drawn aren't erased and redrawn unless you explicitly instruct Windows that it needs to do so. That's not a problem for the form inside the designer, because there, Aero's DWM composition is not enabled. When the window gets resized, it is automatically redrawn, and your swoosh looks smooth and correct.

Outside of the designer, with Aero composition enabled, only the newly-exposed portions of your control are redrawn (the rest are still there in the buffer), so the shape is wrong. Part of the old shape is still there, and part of the new shape was just drawn in. Calling Invalidate tells Windows "the graphic surface of this control has changed; forget everything you thought you knew about it and redraw it from scratch next time". So Windows dutifully obeys, discarding that portion from its off-screen buffer and redraws it in from scratch, producing a correctly-rendered, nicely-smoothed path.

You can effect the same change in another somewhat more elegant way: Tell the control that it needs to redraw itself every time that it is resized. Insert the following code into the control's constructor method:

```<code>public MyUserControl()
{
    // Force the control to redraw itself each time it is resized
    this.SetStyle(ControlStyles.ResizeRedraw);
}
</code>```

Body:
private void UserControl1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawEllipse(Pens.Black, new Rectangle(-200, -500, this.Width + 400, this.Height + 420));
}

Paste the above code into a usercontrol. Drop the usercontrol onto a form and anchor it to all 4 points.

In the designer (Under Visual Studio 2010) it renders perfectly (even as you resize). Run it and try and resize the form and the ellipse becomes skewed.

Here are two examples both after resizes the first while running, the second in the designer.

Obviously the behavior in the designer can't always be assumed to be the same (Although it would be nice) but my understanding is that the code above is completely legal. Am I wrong?

Body:
Stecya has posted the "fix", but omitted an explanation detailing why that works or why you're seeing a discrepancy between the behavior in the designer and in the running application. In my mind, that makes the answer only minimally useful, so I thought I'd weigh in with an attempt at an explanation.

You already know that calling the Invalidate method is the solution. What this does is tell Windows that the entire surface area of the control needs to be redrawn the next time the window gets painted. Simple enough, but why don't you have to do this in the designer?

The answer lies in the fact that you're running the program with the Windows Aero theme enabled. Aero uses an entirely new window manager called the Desktop Window Manager (or DWM for short) based on composition. Each window is double-buffered, meaning that its graphics are rendered off-screen into a temporary bitmap, and only then blitted to the screen. This allows all sorts of cool effects and fancy transitions that users seem to like nowadays.

But, of course, it means that the sections that have already been drawn aren't erased and redrawn unless you explicitly instruct Windows that it needs to do so. That's not a problem for the form inside the designer, because there, Aero's DWM composition is not enabled. When the window gets resized, it is automatically redrawn, and your swoosh looks smooth and correct.

Outside of the designer, with Aero composition enabled, only the newly-exposed portions of your control are redrawn (the rest are still there in the buffer), so the shape is wrong. Part of the old shape is still there, and part of the new shape was just drawn in. Calling Invalidate tells Windows "the graphic surface of this control has changed; forget everything you thought you knew about it and redraw it from scratch next time". So Windows dutifully obeys, discarding that portion from its off-screen buffer and redraws it in from scratch, producing a correctly-rendered, nicely-smoothed path.

You can effect the same change in another somewhat more elegant way: Tell the control that it needs to redraw itself every time that it is resized. Insert the following code into the control's constructor method:

public MyUserControl()
{
    // Force the control to redraw itself each time it is resized
    this.SetStyle(ControlStyles.ResizeRedraw);
}


问:
java.lang.OutOfMemoryError: unable to create new native thread error using ChromeDriver and Chrome through Selenium in Spring boot
We have selenium based web application developed using spring boot. The server is located as VM Instance at google cloud server.

We have a thread base mechanism using Executor. Using selenium we open a chrome browser (headless) to perform operation and for each operation we create new thread.

After facing outOfMemory error, if we restart cloud instance then within 1 hour it breaks again with the same error.

Please find below the snippet which we used to create a new instance of executor service for each request.

```<code>executorService = Executors.newFixedThreadPool(1);
Future<Object> futureDetails = executorService.submit(new Callable<Object>() {

        @Override
        public Object call() throws Exception {

            Object response = client.getDetails(number);

            return response;
        }
    });

    executorService.shutdown();
</code>```

We have (16 vCPUs, 64 GB memory) server configuration.

Please find below the details of the version.

Spring Boot - 2.0.0.RELEASE

Selenium - 3.9.1

Linux - Debian 4.9.130-2 (2018-10-27) x86_64 GNU/Linux

Chrome Driver - 2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881)

Google Chrome - 70.0.3538.110

JDK - 1.8.0_232

Please find below resource report using: ulimit -a.

```<code>core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 257648
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 10240
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 257648
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
</code>```

Also, I did check the memory using: free -m

```<code>              total        used        free      shared  buff/cache   available
Mem:          64433        9479       54490         279         463       54132
Swap:             0           0           0
</code>```

Please find below the error stack trace:

org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.OutOfMemoryError: unable to create new native thread
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1006) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176) [spring-security-oauth2-2.2.1.RELEASE.jar!/:na]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_241]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_241]
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at java.lang.Thread.run(Thread.java:748) [na:1.8.0_241]
  Caused by: java.lang.OutOfMemoryError: unable to create new native thread

Please help me to understand the issue and root cause of this problem. It would be better if you can suggest a solution as well.

Thanks in advance.

答:
The amount of RAM your server has doesn't matter if you don't allocate that memory to your java process.

If you run your application with (any variant of) java -jar command, then add a maximum allowed memory parameter -xmx (check this question). If the application runs inside Tomcat (or any application server), you'll need to increase the maximum allowed memory of it (check its parameters and docs).

Body:
We have selenium based web application developed using spring boot. The server is located as VM Instance at google cloud server.

We have a thread base mechanism using Executor. Using selenium we open a chrome browser (headless) to perform operation and for each operation we create new thread.

After facing outOfMemory error, if we restart cloud instance then within 1 hour it breaks again with the same error.

Please find below the snippet which we used to create a new instance of executor service for each request.

executorService = Executors.newFixedThreadPool(1);
Future<Object> futureDetails = executorService.submit(new Callable<Object>() {

        @Override
        public Object call() throws Exception {

            Object response = client.getDetails(number);

            return response;
        }
    });

    executorService.shutdown();

We have (16 vCPUs, 64 GB memory) server configuration.

Please find below the details of the version.

Spring Boot - 2.0.0.RELEASE

Selenium - 3.9.1

Linux - Debian 4.9.130-2 (2018-10-27) x86_64 GNU/Linux

Chrome Driver - 2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881)

Google Chrome - 70.0.3538.110

JDK - 1.8.0_232

Please find below resource report using: ulimit -a.

core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 257648
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 10240
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 257648
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

Also, I did check the memory using: free -m

              total        used        free      shared  buff/cache   available
Mem:          64433        9479       54490         279         463       54132
Swap:             0           0           0

Please find below the error stack trace:

org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.OutOfMemoryError: unable to create new native thread
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1006) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176) [spring-security-oauth2-2.2.1.RELEASE.jar!/:na]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_241]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_241]
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at java.lang.Thread.run(Thread.java:748) [na:1.8.0_241]
  Caused by: java.lang.OutOfMemoryError: unable to create new native thread

Please help me to understand the issue and root cause of this problem. It would be better if you can suggest a solution as well.

Thanks in advance.


问:
How to get component instance in data section in vuejs template?
I have a component that has complex rendering logic.
I try to carry out this logic to helper classes, for simplifying.
To do this, in the data section (for reactivity), I create class references as follows:

```<code>export default {
  data: () => ({
    state: new InitialState(this),
    query: new QueryController(this)
  })
}
</code>```

As I understand it, at this point the context of this is not yet defined.
So, I have two questions.

1) Is there a way to pass the this component context in the data section (without lifecycle hooks)?

2) Is the approach with references to external classes of vuejs philosophy contrary?

答:
I think computed is a better way to do what you want</p>

```<code>export default {
    computed:{
        state(){
            return new InitialState(this);
        },
        query(){
            return new QueryController(this);
        }
    }
}
</code>```

Body:
I have a component that has complex rendering logic.
I try to carry out this logic to helper classes, for simplifying.
To do this, in the data section (for reactivity), I create class references as follows:

export default {
  data: () => ({
    state: new InitialState(this),
    query: new QueryController(this)
  })
}

As I understand it, at this point the context of this is not yet defined.
So, I have two questions.

1) Is there a way to pass the this component context in the data section (without lifecycle hooks)?

2) Is the approach with references to external classes of vuejs philosophy contrary?

Body:
I think computed is a better way to do what you want

export default {
    computed:{
        state(){
            return new InitialState(this);
        },
        query(){
            return new QueryController(this);
        }
    }
}