问:
Decision Tree Classifier I keep getting NaN error
I've a small decision tree code and I believe I convert everything to int, and I have checked my train/test data with isnan, max etc.

I genuinely have no idea why its giving that error.

So I'm trying to pass Mnist dataset from Decision Tree and then I'll attack using a class.

Here is the code:

```<code> from AttackUtils import Attack
    from AttackUtils import calc_output_weighted_weights, targeted_gradient, non_targeted_gradient, non_targeted_sign_gradient
    (X_train_woae, y_train_woae), (X_test_woae, y_test_woae) = mnist.load_data()
    X_train_woae = X_train_woae.reshape((len(X_train_woae), np.prod(X_train_woae.shape[1:])))
    X_test_woae = X_test_woae.reshape((len(X_test_woae), np.prod(X_test_woae.shape[1:])))

    from sklearn import tree
    #model_woae = LogisticRegression(multi_class='multinomial', solver='lbfgs', fit_intercept=False)
    model_woae = tree.DecisionTreeClassifier(class_weight='balanced')
    model_woae.fit(X_train_woae, y_train_woae)
    #model_woae.coef_ = model_woae.feature_importances_
    coef_int = np.round(model_woae.tree_.compute_feature_importances(normalize=False) * X_train_woae.size).astype(int)
    attack_woae = Attack(model_woae)
    attack_woae.prepare(X_train_woae, y_train_woae, X_test_woae, y_test_woae)
    weights_woae = attack_woae.weights
    num_classes_woae = len(np.unique(y_train_woae))
    attack_woae.create_one_hot_targets(y_test_woae)
    attack_woae.attack_to_max_epsilon(non_targeted_gradient, 50)
    non_targeted_scores_woae = attack_woae.scores
</code>```

So the attack class does perturbation and non-targeted gradient attack. And here is the attack class:

```<code>import numpy as np
from sklearn.metrics import accuracy_score

def calc_output_weighted_weights(output, w):
    for c in range(len(output)):
        if c == 0:
            weighted_weights = output[c] * w[c]
        else:
            weighted_weights += output[c] * w[c]
    return weighted_weights

def targeted_gradient(foolingtarget, output, w):
    ww = calc_output_weighted_weights(output, w)
    for k in range(len(output)):
        if k == 0:
            gradient = foolingtarget[k] * (w[k]-ww)
        else:
            gradient += foolingtarget[k] * (w[k]-ww)
    return gradient

def non_targeted_gradient(target, output, w):
    ww = calc_output_weighted_weights(output, w)
    for k in range(len(target)):
        if k == 0:
            gradient = (1-target[k]) * (w[k]-ww)
        else:
            gradient += (1-target[k]) * (w[k]-ww)
    return gradient

def non_targeted_sign_gradient(target, output, w):
    gradient = non_targeted_gradient(target, output, w)
    return np.sign(gradient)

class Attack:

    def __init__(self, model):
        self.fooling_targets = None
        self.model = model

    def prepare(self, X_train, y_train, X_test, y_test):
        self.images = X_test
        self.true_targets = y_test
        self.num_samples = X_test.shape[0]
        self.train(X_train, y_train)
        print("Model training finished.")
        self.test(X_test, y_test)
        print("Model testing finished. Initial accuracy score: " + str(self.initial_score))

    def set_fooling_targets(self, fooling_targets):
        self.fooling_targets = fooling_targets

    def train(self, X_train, y_train):
        self.model.fit(X_train, y_train)
        self.weights = self.model.coef_
        self.num_classes = self.weights.shape[0]

    def test(self, X_test, y_test):
        self.preds = self.model.predict(X_test)
        self.preds_proba = self.model.predict_proba(X_test)
        self.initial_score = accuracy_score(y_test, self.preds)

    def create_one_hot_targets(self, targets):
        self.one_hot_targets = np.zeros(self.preds_proba.shape)
        for n in range(targets.shape[0]):
            self.one_hot_targets[n, targets[n]] = 1

    def attack(self, attackmethod, epsilon):
        perturbed_images, highest_epsilon = self.perturb_images(epsilon, attackmethod)
        perturbed_preds = self.model.predict(perturbed_images)
        score = accuracy_score(self.true_targets, perturbed_preds)
        return perturbed_images, perturbed_preds, score, highest_epsilon

    def perturb_images(self, epsilon, gradient_method):
        perturbed = np.zeros(self.images.shape)
        max_perturbations = []
        for n in range(self.images.shape[0]):
            perturbation = self.get_perturbation(epsilon, gradient_method, self.one_hot_targets[n], self.preds_proba[n])
            perturbed[n] = self.images[n] + perturbation
            max_perturbations.append(np.max(perturbation))
        highest_epsilon = np.max(np.array(max_perturbations))
        return perturbed, highest_epsilon

    def get_perturbation(self, epsilon, gradient_method, target, pred_proba):
        gradient = gradient_method(target, pred_proba, self.weights)
        inf_norm = np.max(gradient)
        perturbation = epsilon / inf_norm * gradient
        return perturbation

    def attack_to_max_epsilon(self, attackmethod, max_epsilon):
        self.max_epsilon = max_epsilon
        self.scores = []
        self.epsilons = []
        self.perturbed_images_per_epsilon = []
        self.perturbed_outputs_per_epsilon = []
        for epsilon in range(0, self.max_epsilon):
            perturbed_images, perturbed_preds, score, highest_epsilon = self.attack(attackmethod, epsilon)
            self.epsilons.append(highest_epsilon)
            self.scores.append(score)
            self.perturbed_images_per_epsilon.append(perturbed_images)
            self.perturbed_outputs_per_epsilon.append(perturbed_preds)
</code>```

And this is the traceback it gives:

ValueError

Traceback (most recent call last)  in

        4 num_classes_woae = len(np.unique(y_train_woae))
        5 attack_woae.create_one_hot_targets(y_test_woae)
  ----> 6 attack_woae.attack_to_max_epsilon(non_targeted_gradient, 50)
        7 non_targeted_scores_woae = attack_woae.scores

~\MULTIATTACK\AttackUtils.py in
  attack_to_max_epsilon(self, attackmethod, max_epsilon)
      106         self.perturbed_outputs_per_epsilon = []
      107         for epsilon in range(0, self.max_epsilon):
  --> 108             perturbed_images, perturbed_preds, score, highest_epsilon = self.attack(attackmethod, epsilon)
      109             self.epsilons.append(highest_epsilon)
      110             self.scores.append(score)

~\MULTIATTACK\AttackUtils.py in attack(self,
  attackmethod, epsilon)
       79     def attack(self, attackmethod, epsilon):
       80         perturbed_images, highest_epsilon = self.perturb_images(epsilon, attackmethod)
  ---> 81         perturbed_preds = self.model.predict(perturbed_images)
       82         score = accuracy_score(self.true_targets, perturbed_preds)
       83         return perturbed_images, perturbed_preds, score, highest_epsilon

...\appdata\local\programs\python\python35\lib\site-packages\sklearn\tree\tree.py
  in predict(self, X, check_input)
      413         """
      414         check_is_fitted(self, 'tree_')
  --> 415         X = self._validate_X_predict(X, check_input)
      416         proba = self.tree_.predict(X)
      417         n_samples = X.shape[0]

...\appdata\local\programs\python\python35\lib\site-packages\sklearn\tree\tree.py
  in _validate_X_predict(self, X, check_input)
      374         """Validate X whenever one tries to predict, apply, predict_proba"""
      375         if check_input:
  --> 376             X = check_array(X, dtype=DTYPE, accept_sparse="csr")
      377             if issparse(X) and (X.indices.dtype != np.intc or
      378                                 X.indptr.dtype != np.intc):

...\appdata\local\programs\python\python35\lib\site-packages\sklearn\utils\validation.py
  in check_array(array, accept_sparse, accept_large_sparse, dtype,
  order, copy, force_all_finite, ensure_2d, allow_nd,
  ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
      566         if force_all_finite:
      567             _assert_all_finite(array,
  --> 568                                allow_nan=force_all_finite == 'allow-nan')
      569
      570     shape_repr = _shape_repr(array.shape)

...\appdata\local\programs\python\python35\lib\site-packages\sklearn\utils\validation.py
  in _assert_all_finite(X, allow_nan)
       54                 not allow_nan and not np.isfinite(X).all()):
       55             type_err = 'infinity' if allow_nan else 'NaN, infinity'
  ---> 56             raise ValueError(msg_err.format(type_err, X.dtype))
       57
       58

ValueError: Input contains NaN, infinity or a value too large for
  dtype('float32').

EDIT:

I've added coefficient numbers as 0 and it now gives the same error just below the line, at attack.attack_to_max_epsilon(non_targeted_gradient, epsilon_number)

答:
Try to apply one-hot enconde to your labels before to train..

```<code>from sklearn.preprocessing import LabelEncoder

mylabels= ["label1", "label2", "label2"..."n.label"]
le = LabelEncoder()
labels = le.fit_transform(mylabels)
</code>```

and then try to split your data:

```<code>from sklearn.model_selection import train_test_split
(x_train, x_test, y_train, y_test) = train_test_split(data,
                                                     labels,
                                                     test_size=0.25)
</code>```

now probably your labels will be encoded with numbers which is good to train a machine learning algorithm.

Body:
I've a small decision tree code and I believe I convert everything to int, and I have checked my train/test data with isnan, max etc.

I genuinely have no idea why its giving that error.

So I'm trying to pass Mnist dataset from Decision Tree and then I'll attack using a class.

Here is the code:

 from AttackUtils import Attack
    from AttackUtils import calc_output_weighted_weights, targeted_gradient, non_targeted_gradient, non_targeted_sign_gradient
    (X_train_woae, y_train_woae), (X_test_woae, y_test_woae) = mnist.load_data()
    X_train_woae = X_train_woae.reshape((len(X_train_woae), np.prod(X_train_woae.shape[1:])))
    X_test_woae = X_test_woae.reshape((len(X_test_woae), np.prod(X_test_woae.shape[1:])))

    from sklearn import tree
    #model_woae = LogisticRegression(multi_class='multinomial', solver='lbfgs', fit_intercept=False)
    model_woae = tree.DecisionTreeClassifier(class_weight='balanced')
    model_woae.fit(X_train_woae, y_train_woae)
    #model_woae.coef_ = model_woae.feature_importances_
    coef_int = np.round(model_woae.tree_.compute_feature_importances(normalize=False) * X_train_woae.size).astype(int)
    attack_woae = Attack(model_woae)
    attack_woae.prepare(X_train_woae, y_train_woae, X_test_woae, y_test_woae)
    weights_woae = attack_woae.weights
    num_classes_woae = len(np.unique(y_train_woae))
    attack_woae.create_one_hot_targets(y_test_woae)
    attack_woae.attack_to_max_epsilon(non_targeted_gradient, 50)
    non_targeted_scores_woae = attack_woae.scores

So the attack class does perturbation and non-targeted gradient attack. And here is the attack class:

import numpy as np
from sklearn.metrics import accuracy_score

def calc_output_weighted_weights(output, w):
    for c in range(len(output)):
        if c == 0:
            weighted_weights = output[c] * w[c]
        else:
            weighted_weights += output[c] * w[c]
    return weighted_weights

def targeted_gradient(foolingtarget, output, w):
    ww = calc_output_weighted_weights(output, w)
    for k in range(len(output)):
        if k == 0:
            gradient = foolingtarget[k] * (w[k]-ww)
        else:
            gradient += foolingtarget[k] * (w[k]-ww)
    return gradient

def non_targeted_gradient(target, output, w):
    ww = calc_output_weighted_weights(output, w)
    for k in range(len(target)):
        if k == 0:
            gradient = (1-target[k]) * (w[k]-ww)
        else:
            gradient += (1-target[k]) * (w[k]-ww)
    return gradient

def non_targeted_sign_gradient(target, output, w):
    gradient = non_targeted_gradient(target, output, w)
    return np.sign(gradient)

class Attack:

    def __init__(self, model):
        self.fooling_targets = None
        self.model = model

    def prepare(self, X_train, y_train, X_test, y_test):
        self.images = X_test
        self.true_targets = y_test
        self.num_samples = X_test.shape[0]
        self.train(X_train, y_train)
        print("Model training finished.")
        self.test(X_test, y_test)
        print("Model testing finished. Initial accuracy score: " + str(self.initial_score))

    def set_fooling_targets(self, fooling_targets):
        self.fooling_targets = fooling_targets

    def train(self, X_train, y_train):
        self.model.fit(X_train, y_train)
        self.weights = self.model.coef_
        self.num_classes = self.weights.shape[0]

    def test(self, X_test, y_test):
        self.preds = self.model.predict(X_test)
        self.preds_proba = self.model.predict_proba(X_test)
        self.initial_score = accuracy_score(y_test, self.preds)

    def create_one_hot_targets(self, targets):
        self.one_hot_targets = np.zeros(self.preds_proba.shape)
        for n in range(targets.shape[0]):
            self.one_hot_targets[n, targets[n]] = 1

    def attack(self, attackmethod, epsilon):
        perturbed_images, highest_epsilon = self.perturb_images(epsilon, attackmethod)
        perturbed_preds = self.model.predict(perturbed_images)
        score = accuracy_score(self.true_targets, perturbed_preds)
        return perturbed_images, perturbed_preds, score, highest_epsilon

    def perturb_images(self, epsilon, gradient_method):
        perturbed = np.zeros(self.images.shape)
        max_perturbations = []
        for n in range(self.images.shape[0]):
            perturbation = self.get_perturbation(epsilon, gradient_method, self.one_hot_targets[n], self.preds_proba[n])
            perturbed[n] = self.images[n] + perturbation
            max_perturbations.append(np.max(perturbation))
        highest_epsilon = np.max(np.array(max_perturbations))
        return perturbed, highest_epsilon

    def get_perturbation(self, epsilon, gradient_method, target, pred_proba):
        gradient = gradient_method(target, pred_proba, self.weights)
        inf_norm = np.max(gradient)
        perturbation = epsilon / inf_norm * gradient
        return perturbation

    def attack_to_max_epsilon(self, attackmethod, max_epsilon):
        self.max_epsilon = max_epsilon
        self.scores = []
        self.epsilons = []
        self.perturbed_images_per_epsilon = []
        self.perturbed_outputs_per_epsilon = []
        for epsilon in range(0, self.max_epsilon):
            perturbed_images, perturbed_preds, score, highest_epsilon = self.attack(attackmethod, epsilon)
            self.epsilons.append(highest_epsilon)
            self.scores.append(score)
            self.perturbed_images_per_epsilon.append(perturbed_images)
            self.perturbed_outputs_per_epsilon.append(perturbed_preds)

And this is the traceback it gives:

ValueError

Traceback (most recent call last)  in

        4 num_classes_woae = len(np.unique(y_train_woae))
        5 attack_woae.create_one_hot_targets(y_test_woae)
  ----> 6 attack_woae.attack_to_max_epsilon(non_targeted_gradient, 50)
        7 non_targeted_scores_woae = attack_woae.scores

~\MULTIATTACK\AttackUtils.py in
  attack_to_max_epsilon(self, attackmethod, max_epsilon)
      106         self.perturbed_outputs_per_epsilon = []
      107         for epsilon in range(0, self.max_epsilon):
  --> 108             perturbed_images, perturbed_preds, score, highest_epsilon = self.attack(attackmethod, epsilon)
      109             self.epsilons.append(highest_epsilon)
      110             self.scores.append(score)

~\MULTIATTACK\AttackUtils.py in attack(self,
  attackmethod, epsilon)
       79     def attack(self, attackmethod, epsilon):
       80         perturbed_images, highest_epsilon = self.perturb_images(epsilon, attackmethod)
  ---> 81         perturbed_preds = self.model.predict(perturbed_images)
       82         score = accuracy_score(self.true_targets, perturbed_preds)
       83         return perturbed_images, perturbed_preds, score, highest_epsilon

...\appdata\local\programs\python\python35\lib\site-packages\sklearn\tree\tree.py
  in predict(self, X, check_input)
      413         """
      414         check_is_fitted(self, 'tree_')
  --> 415         X = self._validate_X_predict(X, check_input)
      416         proba = self.tree_.predict(X)
      417         n_samples = X.shape[0]

...\appdata\local\programs\python\python35\lib\site-packages\sklearn\tree\tree.py
  in _validate_X_predict(self, X, check_input)
      374         """Validate X whenever one tries to predict, apply, predict_proba"""
      375         if check_input:
  --> 376             X = check_array(X, dtype=DTYPE, accept_sparse="csr")
      377             if issparse(X) and (X.indices.dtype != np.intc or
      378                                 X.indptr.dtype != np.intc):

...\appdata\local\programs\python\python35\lib\site-packages\sklearn\utils\validation.py
  in check_array(array, accept_sparse, accept_large_sparse, dtype,
  order, copy, force_all_finite, ensure_2d, allow_nd,
  ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
      566         if force_all_finite:
      567             _assert_all_finite(array,
  --> 568                                allow_nan=force_all_finite == 'allow-nan')
      569
      570     shape_repr = _shape_repr(array.shape)

...\appdata\local\programs\python\python35\lib\site-packages\sklearn\utils\validation.py
  in _assert_all_finite(X, allow_nan)
       54                 not allow_nan and not np.isfinite(X).all()):
       55             type_err = 'infinity' if allow_nan else 'NaN, infinity'
  ---> 56             raise ValueError(msg_err.format(type_err, X.dtype))
       57
       58

ValueError: Input contains NaN, infinity or a value too large for
  dtype('float32').

EDIT:

I've added coefficient numbers as 0 and it now gives the same error just below the line, at attack.attack_to_max_epsilon(non_targeted_gradient, epsilon_number)

Body:
Try to apply one-hot enconde to your labels before to train..

from sklearn.preprocessing import LabelEncoder

mylabels= ["label1", "label2", "label2"..."n.label"]
le = LabelEncoder()
labels = le.fit_transform(mylabels)

and then try to split your data:

from sklearn.model_selection import train_test_split
(x_train, x_test, y_train, y_test) = train_test_split(data,
                                                     labels,
                                                     test_size=0.25)

now probably your labels will be encoded with numbers which is good to train a machine learning algorithm.


来源: stackexchange

问:
Command not found in VSCode extension
I am trying to create a VSCode extension. This extension provides two commands, never mind their implementation:

```<code>export function activate(context: ExtensionContext) {

    const provider = new ContentProvider();
    const providerRegistrations = Disposable.from(
        workspace.registerTextDocumentContentProvider(ContentProvider.scheme, provider)
    );

    // Open the dynamic document, and shows it in the next editor
    const openMyExtensionCommandRegistration = commands.registerTextEditorCommand('extension.openMyExtension', editor => {
        // Activate the extension and do something
    });

    const useMyExtensionCommandRegistration = commands.registerTextEditorCommand('extension.useMyExtension', editor => {
        // Do something
    });

    context.subscriptions.push(
        provider,
        openMyExtensionCommandRegistration,
        useMyExtensionCommandRegistration,
        providerRegistrations
    );
}
</code>```

And this is a part of my package.json file:

```<code>"activationEvents": [
        "onCommand:extension.openMyExtension"
    ],
    "main": "./out/extension",
    "contributes": {
        "commands": [
            {
                "command": "extension.openMyExtension",
                "title": "Open my extension",
                "category": "MyExtension"
            },
            {
                "command": "extension.useMyExtension",
                "title": "Do something with my extension",
                "category": "MyExtension"
            }
        ],
</code>```

The first command, which is supposed to activates my extension, works. It appears in the command palette, and actually does what it is supposed to do when invoked.

The second command however, despite appearing in the command palette, raise the following error message when called:

command 'extension.useMyExtension' not found

I find it weird that my first command works fine but not the second since the code is quite similar. Any ideas why?

Note that I obviously changed some variable names, I double checked for typos in the real code.

答:
My issue is I was running Cmder as my VS Code terminal. When I started debugging, the build would never complete - you can monitor Running Tasks from the bottom toolbar. When I looked at the task being run, I saw this:

Executing task: npm run watch <

VS Code is attempting to run the watch script but it never finished - I'm guessing some syntactical issue is at work here.

Anyway, while compiling does work, I'd recommend running the watch script instead so that your extension will re-compile with every file change:

npm run watch

You should now be able to run your extension in your extension host via F5 without having to re-compile constantly. (You'll still need to reload your host though)

ContentLicense: CC BY-SA 3.0

Title: Command not found in VSCode extension

Body:
I am trying to create a VSCode extension. This extension provides two commands, never mind their implementation:

export function activate(context: ExtensionContext) {

    const provider = new ContentProvider();
    const providerRegistrations = Disposable.from(
        workspace.registerTextDocumentContentProvider(ContentProvider.scheme, provider)
    );

    // Open the dynamic document, and shows it in the next editor
    const openMyExtensionCommandRegistration = commands.registerTextEditorCommand('extension.openMyExtension', editor => {
        // Activate the extension and do something
    });

    const useMyExtensionCommandRegistration = commands.registerTextEditorCommand('extension.useMyExtension', editor => {
        // Do something
    });

    context.subscriptions.push(
        provider,
        openMyExtensionCommandRegistration,
        useMyExtensionCommandRegistration,
        providerRegistrations
    );
}

And this is a part of my package.json file:

"activationEvents": [
        "onCommand:extension.openMyExtension"
    ],
    "main": "./out/extension",
    "contributes": {
        "commands": [
            {
                "command": "extension.openMyExtension",
                "title": "Open my extension",
                "category": "MyExtension"
            },
            {
                "command": "extension.useMyExtension",
                "title": "Do something with my extension",
                "category": "MyExtension"
            }
        ],

The first command, which is supposed to activates my extension, works. It appears in the command palette, and actually does what it is supposed to do when invoked.

The second command however, despite appearing in the command palette, raise the following error message when called:

command 'extension.useMyExtension' not found

I find it weird that my first command works fine but not the second since the code is quite similar. Any ideas why?

Note that I obviously changed some variable names, I double checked for typos in the real code.

ContentLicense: CC BY-SA 4.0


问:
What is \363\353\377\377\377\177?

(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"
```

It doesn't look like ascii nor multibyte,what's that?

答:
try p/x

This should print value in hexa decimal format

Title: What is \363\353\377\377\377\177?

Body:
(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"

It doesn't look like ascii nor multibyte,what's that?


问:
PHP: fgets() return value not evaluated correctly?
I have a PHP script that's supposed to do something depending on whether the first line of a file called info.txt is '0' or something else. My PHP file:

```<code><?php
$handle = fopen('info.txt','r');
$line = fgets($handle);
fclose($handle);

// print detailed contents of $line
foreach(str_split($line) as $chr) {
  printf("[%02x] %s <br />",ord($chr),$chr);
}

if ($line == '0\n') {
  echo "equal";
} else {
  echo "not equal";
}
?>
</code>```

I got the foreach loop on another answer on stackoverflow and it splits $line by character and prints the character's code and what it evaluates to. When I run this file the output is:

```<code>[30] 0
[0a]
not equal
</code>```

It looks like the first line of info.txt is just 0\n since as I understand it, 0x0a should be the same as \n. I'm running this file on Mac OS X but I thought that shouldn't change the fact that ASCII 0x0a is the \n character. Any ideas why $line isn't evaluating as equal to '0\n'? I'm new to PHP so it's very possible that the issue is some obvious syntax thing. Thanks!

答:
You must use double quotes instead of simple quotes so that "\n" is interpreted as new line character. With single quotes, the characters are interpreted as '\' + 'n' characters.</p>

```<code>if ($line == "0\n") {
        echo "equal\n";
    } else {
        echo "not equal\n";
    }
</code>```

Body:
I have a PHP script that's supposed to do something depending on whether the first line of a file called info.txt is '0' or something else. My PHP file:

<?php
$handle = fopen('info.txt','r');
$line = fgets($handle);
fclose($handle);

// print detailed contents of $line
foreach(str_split($line) as $chr) {
  printf("[%02x] %s
",ord($chr),$chr);
}

if ($line == '0\n') {
  echo "equal";
} else {
  echo "not equal";
}
?>

I got the foreach loop on another answer on stackoverflow and it splits $line by character and prints the character's code and what it evaluates to. When I run this file the output is:

[30] 0
[0a]
not equal

It looks like the first line of info.txt is just 0\n since as I understand it, 0x0a should be the same as \n. I'm running this file on Mac OS X but I thought that shouldn't change the fact that ASCII 0x0a is the \n character. Any ideas why $line isn't evaluating as equal to '0\n'? I'm new to PHP so it's very possible that the issue is some obvious syntax thing. Thanks!

Body:
You must use double quotes instead of simple quotes so that "\n" is interpreted as new line character. With single quotes, the characters are interpreted as '\' + 'n' characters.

if ($line == "0\n") {
        echo "equal\n";
    } else {
        echo "not equal\n";
    }


问:
Vertical alignment on editable UITextView
I want to set the vertical alignment on my UITextView. The text view is editable and scroll is disabled:

let textView = UITextView(frame: frame)
textView.backgroundColor = .clear
textView.attributedText = myAttributedString
textView.isUserInteractionEnabled = true
textView.isEditable = true
textView.allowsEditingTextAttributes = true
textView.isScrollEnabled = false
textView.textContainerInset = .zero
self.addSubview(textView)
```

<p>So, I would like to do something like :</p>

<pre class="lang-swift prettyprint-override"><code>textView.verticalAlignment = .center
</code>```

I already tried subclassing the text view and adding an attribute like this:

class MyTextView: UITextView {
    public var verticalAlignment: UIControl.ContentVerticalAlignment = .center {
        didSet {
            let topCorrection: CGFloat
            switch verticalAlignment {
            case .center:
                topCorrection = (bounds.size.height - contentSize.height * zoomScale) / 2.0
            case .bottom:
                topCorrection = (bounds.size.height - contentSize.height * zoomScale)
            case .top, .fill:
                topCorrection = 0
            @unknown default:
                topCorrection = 0
            }
            contentInset.top = max(0, topCorrection)
        }
    }
}
```

But it seems not to work with isScrollEnabled set to false.

Every other solution I found on the internet didn't work either and I'm a bit hopeless… Can you help me?

Thanks

答:
Maybe you intended to use a UITextField?

```<code>let field = UITextField()
field.contentVerticalAlignment = UIControlContentVerticalAlignment.center
</code>```

Or set it to .bottom, .top, etc.

Body:
I want to set the vertical alignment on my UITextView. The text view is editable and scroll is disabled:

let textView = UITextView(frame: frame)
textView.backgroundColor = .clear
textView.attributedText = myAttributedString
textView.isUserInteractionEnabled = true
textView.isEditable = true
textView.allowsEditingTextAttributes = true
textView.isScrollEnabled = false
textView.textContainerInset = .zero
self.addSubview(textView)

So, I would like to do something like :

textView.verticalAlignment = .center

I already tried subclassing the text view and adding an attribute like this:

class MyTextView: UITextView {
    public var verticalAlignment: UIControl.ContentVerticalAlignment = .center {
        didSet {
            let topCorrection: CGFloat
            switch verticalAlignment {
            case .center:
                topCorrection = (bounds.size.height - contentSize.height * zoomScale) / 2.0
            case .bottom:
                topCorrection = (bounds.size.height - contentSize.height * zoomScale)
            case .top, .fill:
                topCorrection = 0
            @unknown default:
                topCorrection = 0
            }
            contentInset.top = max(0, topCorrection)
        }
    }
}

But it seems not to work with isScrollEnabled set to false.

Every other solution I found on the internet didn't work either and I'm a bit hopeless… Can you help me?

Thanks

Body:
Maybe you intended to use a UITextField?

let field = UITextField()
field.contentVerticalAlignment = UIControlContentVerticalAlignment.center

Or set it to .bottom, .top, etc.


问:
WorksheetFunction.countif criteria not working
I am using the following code to create an email list of unique emails. The list has a lot of duplicates, but I only want them once. Some of the rows have not been assigned an email so they show as <UNASSIGNED> and I want to ignore those.

I have used this in another sheet where it is working well, the difference is that on this new application I need to copy the data to a temporary location, because it is filtered and the CountIf does not work on filtered rows.

The code is ignoring the criteria for the <UNASSIGNED>. I want to figure out, why this is happening.

I first use the CountIf to get the loan officer email list (MLO list). That works fine, but then the code to get the Processor list is not working as it should. The code below Processor list is supposed to ignore any value that equals <UNASSIGNED>, but it doesn't:

```<code>Sheets(2).Cells.ClearContents
  lastSrcRw = Sheets("Pipeline").Cells(Rows.Count, 2).End(xlUp).Row
     For Each cell In Sheets("Pipeline").Range("E11:E" & lastSrcRw).SpecialCells(xlCellTypeVisible)
        dstRw = dstRw + 1
        cell.Copy Sheets(2).Range("A" & dstRw)
     Next

'Loop through Sheet2 list, extract unique addresses
  lastTmpRw = Sheets(2).Cells(Rows.Count, 1).End(xlUp).Row
     For tmpRw = 1 To lastTmpRw
         If WorksheetFunction.CountIf(Sheets(2).Range("A1:A" & tmpRw), _
            Sheets(2).Range("A" & tmpRw)) < 2 Then
               addylist_tmp = addylist_tmp & Sheets(2).Range("A" & tmpRw).Value & "; "
         End If
     Next tmpRw

'Clean up temp addylist
     addylist = Left(addylist_tmp, Len(addylist_tmp) - 2)
     'MsgBox addylist

'Processor List
Sheets(2).Cells.ClearContents
  lastSrcRw = Sheets("Pipeline").Cells(Rows.Count, 4).End(xlUp).Row
     For Each cell In Sheets("Pipeline").Range("C11:C" & lastSrcRw).SpecialCells(xlCellTypeVisible)
        dstRw = dstRw + 1
        cell.Copy Sheets(2).Range("D" & dstRw)
     Next

'Loop through Sheet2 list, extract unique addresses
  lastTmpRw = Sheets(2).Cells(Rows.Count, 4).End(xlUp).Row
     For tmpRw = 1 To lastTmpRw
         If WorksheetFunction.CountIf(Sheets(2).Range("D1:D" & tmpRw), "<>" & "<UNASSIGNED>") Then
         If WorksheetFunction.CountIf(Sheets(2).Range("D1:D" & tmpRw), Sheets(2).Range("D" & tmpRw)) < 2 Then
                addylist_tmp2 = addylist_tmp2 & Sheets(2).Range("D" & tmpRw).Value & "; "
         End If
         End If
     Next tmpRw

'Clean up temp addylist
     addylist2 = Left(addylist_tmp2, Len(addylist_tmp2) - 2)

</code>```

答:
I was able to find a simple solution from a user named Fluff in MrExcel forum:</p>

```<code>Sub mecerrato()
Dim Cl As Range
Dim Mlst As String, Plst As String
Dim Mdic As Object, Pdic As Object

Set Mdic = CreateObject("scripting.dictionary")
Set Pdic = CreateObject("scripting.dictionary")
With Sheets("Pipeline")
  For Each Cl In .Range("C11", .Range("C" &
Rows.Count).End(xlUp)).SpecialCells(xlVisible)
     If Cl.Value <> "" And Cl.Value <> "<UNASSIGNED>" Then Pdic(Cl.Value) = Empty
     If Cl.Offset(, 2).Value <> "" Then Mdic(Cl.Offset(, 2).Value) = Empty
  Next Cl
End With
Mlst = Join(Mdic.Keys, "; ")
Plst = Join(Pdic.Keys, "; ")
End Sub
</code>```

Body:
I am using the following code to create an email list of unique emails. The list has a lot of duplicates, but I only want them once. Some of the rows have not been assigned an email so they show as <UNASSIGNED> and I want to ignore those.

I have used this in another sheet where it is working well, the difference is that on this new application I need to copy the data to a temporary location, because it is filtered and the CountIf does not work on filtered rows.

The code is ignoring the criteria for the <UNASSIGNED>. I want to figure out, why this is happening.

I first use the CountIf to get the loan officer email list (MLO list). That works fine, but then the code to get the Processor list is not working as it should. The code below Processor list is supposed to ignore any value that equals <UNASSIGNED>, but it doesn't:

Sheets(2).Cells.ClearContents
  lastSrcRw = Sheets("Pipeline").Cells(Rows.Count, 2).End(xlUp).Row
     For Each cell In Sheets("Pipeline").Range("E11:E" & lastSrcRw).SpecialCells(xlCellTypeVisible)
        dstRw = dstRw + 1
        cell.Copy Sheets(2).Range("A" & dstRw)
     Next

'Loop through Sheet2 list, extract unique addresses
  lastTmpRw = Sheets(2).Cells(Rows.Count, 1).End(xlUp).Row
     For tmpRw = 1 To lastTmpRw
         If WorksheetFunction.CountIf(Sheets(2).Range("A1:A" & tmpRw), _
            Sheets(2).Range("A" & tmpRw)) < 2 Then
               addylist_tmp = addylist_tmp & Sheets(2).Range("A" & tmpRw).Value & "; "
         End If
     Next tmpRw

'Clean up temp addylist
     addylist = Left(addylist_tmp, Len(addylist_tmp) - 2)
     'MsgBox addylist

'Processor List
Sheets(2).Cells.ClearContents
  lastSrcRw = Sheets("Pipeline").Cells(Rows.Count, 4).End(xlUp).Row
     For Each cell In Sheets("Pipeline").Range("C11:C" & lastSrcRw).SpecialCells(xlCellTypeVisible)
        dstRw = dstRw + 1
        cell.Copy Sheets(2).Range("D" & dstRw)
     Next

'Loop through Sheet2 list, extract unique addresses
  lastTmpRw = Sheets(2).Cells(Rows.Count, 4).End(xlUp).Row
     For tmpRw = 1 To lastTmpRw
         If WorksheetFunction.CountIf(Sheets(2).Range("D1:D" & tmpRw), "<>" & "<UNASSIGNED>") Then
         If WorksheetFunction.CountIf(Sheets(2).Range("D1:D" & tmpRw), Sheets(2).Range("D" & tmpRw)) < 2 Then
                addylist_tmp2 = addylist_tmp2 & Sheets(2).Range("D" & tmpRw).Value & "; "
         End If
         End If
     Next tmpRw

'Clean up temp addylist
     addylist2 = Left(addylist_tmp2, Len(addylist_tmp2) - 2)

Body:
I was able to find a simple solution from a user named Fluff in MrExcel forum:

Sub mecerrato()
Dim Cl As Range
Dim Mlst As String, Plst As String
Dim Mdic As Object, Pdic As Object

Set Mdic = CreateObject("scripting.dictionary")
Set Pdic = CreateObject("scripting.dictionary")
With Sheets("Pipeline")
  For Each Cl In .Range("C11", .Range("C" &
Rows.Count).End(xlUp)).SpecialCells(xlVisible)
     If Cl.Value <> "" And Cl.Value <> "<UNASSIGNED>" Then Pdic(Cl.Value) = Empty
     If Cl.Offset(, 2).Value <> "" Then Mdic(Cl.Offset(, 2).Value) = Empty
  Next Cl
End With
Mlst = Join(Mdic.Keys, "; ")
Plst = Join(Pdic.Keys, "; ")
End Sub


问:
React - Minified exception occurred
I have React js installed via NPM and using browserify to manage components in react. When an exception occurs in React, the console shows as

"Uncaught Error: Minified exception occurred; use the non-minified dev
  environment for the full error message and additional helpful
  warnings."

How do I enable full error messages ?

答: use the min.js files in production or bundle your application code with process.env.NODE_ENV === 'production' and you should be good to go!

Title: React - Minified exception occurred


问:
Getting stack trace from NullPointerException
my servlet is throwing a NullPointerException. I want to show the full stack call trace so that I can find out the line number the exception is being thrown at.

How can I do that? I have already used fillInStackTrace(). it is not printing the line number.

答: Have you tried using e.printStackTrace()?


问:
Why does Java report a mismatch when trying to print big random numbers?
Java reports a Type mismatch exception when trying to print big numbers and stored an array.

I'm currently learning some Java. One of the excercises of the course I'm doing, asks me to generate some random numbers and storing them inside an array. Everything works fine as long as I generate integers, I can print them without trouble using out.print.

But, when I generate big numbers and try to print them, Java informs a type mismatch in the line where I have the for each loop.

```<code>package clases;

public class Arrays_3 {
    public static void main (String [] args) {
        long [] array_random=new long[150];
        for (int i=0;i<array_random.length;i++) {
            array_random[i]=(long)Math.round(Math.random()*100000) ;
        }

        for (long elemento:array_random) {
            System.out.println(array_random[elemento]);
        }
    }
}
</code>```

This is the error I get on Eclipse console after running the code above:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Type mismatch: cannot convert from long to int

    at clases.Arrays_3.main(Arrays_3.java:17)
```

Line 17 is where the System.out.print method is.

答:
I guess you are trying to print the element. what you are looping is the value(int type) instead of the index(long type). </p>

<pre class="lang-java prettyprint-override"><code>      for (long elemento:array_random) {
            System.out.println(elemento);
        }
</code>```

Body:
Java reports a Type mismatch exception when trying to print big numbers and stored an array.

I'm currently learning some Java. One of the excercises of the course I'm doing, asks me to generate some random numbers and storing them inside an array. Everything works fine as long as I generate integers, I can print them without trouble using out.print.

But, when I generate big numbers and try to print them, Java informs a type mismatch in the line where I have the for each loop.

package clases;

public class Arrays_3 {
    public static void main (String [] args) {
        long [] array_random=new long[150];
        for (int i=0;i<array_random.length;i++) {
            array_random[i]=(long)Math.round(Math.random()*100000) ;
        }

        for (long elemento:array_random) {
            System.out.println(array_random[elemento]);
        }
    }
}

This is the error I get on Eclipse console after running the code above:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Type mismatch: cannot convert from long to int

    at clases.Arrays_3.main(Arrays_3.java:17)

Line 17 is where the System.out.print method is.

Body:
I guess you are trying to print the element. what you are looping is the value(int type) instead of the index(long type).

      for (long elemento:array_random) {
            System.out.println(elemento);
        }


问:
VBA compile error: wrong number of arguments or invalid property assignment When trying to unmerge excel cells over multiple sheets
I am writing a macro for the first time and came across a problem I did not manage to find an answer to online link.
I have excel files with merged cells that I need to un-merge and then duplicate the value of the merged cell to all of the newly formed separated cells and then convert this file from .xslx to .csv.
I found a code that does exactly what I wish but the code is unmerging only the working Sheet (the sheet that I'm currently working on).
I tried putting this function in a loop through all the sheets, however, when I run the loop I get a compilation error: "Wrong number of arguments or invalid property assingment"
I would be grateful for some insight as to why this is happening, how to solve it or any other idea for how to go about it.
Thanks

This is the function that I copied and it is working for one sheet

```<code>Public Sub UnMergeFill()

Dim cell As Range, joinedCells As Range

    For Each cell In ThisWorkbook.ActiveSheet.UsedRange
        If cell.MergeCells Then
            Set joinedCells = cell.MergeArea
            cell.MergeCells = False
            joinedCells.Value = cell.Value
        End If
    Next

    End Sub
</code>```

this is the function I wrote and return the error

```<code> Sub UnMergeFillAllSheets()
        Dim ws As Worksheet
        For Each ws In Worksheets
            ws.Select
            Call UnMergeFill(ws)
        Next
    End Sub
</code>```

the input is:
[[0][0][0][0]][1][1]

when the zeros are in one merged cell

the output:
[0][0][0][0][1][1]

答:
Call UnMergeFill(ws) is invoking the UnMergeFill procedure, passing in ws as an argument...

```<code>Public Sub UnMergeFill()
</code>```

...but the UnMergeFill procedure does not accept any parameters. Hence, "wrong number of arguments".

You need to change the signature of UnMergeFill to accept a Worksheet parameter:

```<code>Public Sub UnMergeFill(ByVal ws As Worksheet)
</code>```

And then there's no need to .Select it anymore:

```<code>    For Each ws In Worksheets
        UnMergeFill ws
    Next
</code>```

Except you now need UnMergeFill to work off the Worksheet parameter it's given:

```<code>For Each cell In ws.UsedRange
</code>```

If you want UnMergeFill to still work off whatever the ActiveSheet is given no arguments, then you can make the parameter optional:

```<code>Public Sub UnMergeFill(Optional ByVal ws As Worksheet = Nothing)
</code>```

...and then verify whether the procedure was invoked with a valid object reference:

```<code>    If ws Is Nothing Then Set ws = ActiveSheet
</code>```

Body:
I am writing a macro for the first time and came across a problem I did not manage to find an answer to online link.
I have excel files with merged cells that I need to un-merge and then duplicate the value of the merged cell to all of the newly formed separated cells and then convert this file from .xslx to .csv.
I found a code that does exactly what I wish but the code is unmerging only the working Sheet (the sheet that I'm currently working on).
I tried putting this function in a loop through all the sheets, however, when I run the loop I get a compilation error: "Wrong number of arguments or invalid property assingment"
I would be grateful for some insight as to why this is happening, how to solve it or any other idea for how to go about it.
Thanks

This is the function that I copied and it is working for one sheet

Public Sub UnMergeFill()

Dim cell As Range, joinedCells As Range

    For Each cell In ThisWorkbook.ActiveSheet.UsedRange
        If cell.MergeCells Then
            Set joinedCells = cell.MergeArea
            cell.MergeCells = False
            joinedCells.Value = cell.Value
        End If
    Next

    End Sub

this is the function I wrote and return the error

 Sub UnMergeFillAllSheets()
        Dim ws As Worksheet
        For Each ws In Worksheets
            ws.Select
            Call UnMergeFill(ws)
        Next
    End Sub

the input is:
[[0][0][0][0]][1][1]

when the zeros are in one merged cell

the output:
[0][0][0][0][1][1]

Body:
Call UnMergeFill(ws) is invoking the UnMergeFill procedure, passing in ws as an argument...

Public Sub UnMergeFill()

...but the UnMergeFill procedure does not accept any parameters. Hence, "wrong number of arguments".

You need to change the signature of UnMergeFill to accept a Worksheet parameter:

Public Sub UnMergeFill(ByVal ws As Worksheet)

And then there's no need to .Select it anymore:

    For Each ws In Worksheets
        UnMergeFill ws
    Next

Except you now need UnMergeFill to work off the Worksheet parameter it's given:

For Each cell In ws.UsedRange

If you want UnMergeFill to still work off whatever the ActiveSheet is given no arguments, then you can make the parameter optional:

Public Sub UnMergeFill(Optional ByVal ws As Worksheet = Nothing)

...and then verify whether the procedure was invoked with a valid object reference:

    If ws Is Nothing Then Set ws = ActiveSheet


问:
flutter: ">=0.2.4 <2.0.0" pub get failed (65) when cloud_firestore package is used in pubspec.yaml
When I tried to add the google_sign_in,flutter_auth and cloud_firestore it is throwing me the error that flutter: ">=0.2.4 <2.0.0".I  tried to run flutter dector -v the output is

[✓] Flutter (Channel stable, v1.5.4-hotfix.2, on Linux, locale en_US.UTF-8)
    • Flutter version 1.5.4-hotfix.2 at /home/ramu/Downloads/tools/flutter
    • Framework revision 7a4c33425d (4 weeks ago), 2019-04-29 11:05:24 -0700
    • Engine revision 52c7a1e849
    • Dart version 2.3.0 (build 2.3.0-dev.0.5 a1668566e5)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /home/ramu/Android/Sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • ANDROID_HOME = /home/ramu/Android/Sdk
    • Java binary at: /snap/android-studio/73/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[✓] Android Studio (version 3.3)
    • Android Studio at /snap/android-studio/73/android-studio
    • Flutter plugin version 34.0.1
    • Dart plugin version 182.5215
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[✓] VS Code (version 1.34.0)
    • VS Code at /usr/share/code
    • Flutter extension version 3.0.2

[!] Connected device
    ! No devices available

! Doctor found issues in 1 category.

firebase_auth: ^0.6.2+1
  google_sign_in: ^3.2.2
  cloud_firestore: ^0.8.2+3

答:
Try updating your environment sdk in pubspec.yaml from >=0.2.4 <2.0.0 to >=2.1.0 <3.0.0

The upper bound for your environment sdk is below version 2.0.0 but google_sign_in ,firebase_auth, and cloud_firestore requires at least >=2.0.0-dev.28.0 (which is newer then what you have specified for your project).


问:
Ada: Array length modification when adding anew element
I try to create a dynamic array package. I have a generic package with a generic type and then I have declared in .ads an array (Positive indexes) of elements Elem_Type. I was curious if it is possible to create a procedure Append(Vector, Item) where to modify Vector's length, allowing him to take one more element. Something like when you have a buffer[100] in C and allocate him 1 more element to make it 101 then add something on position 101.</p>

答:
it sounds like you want to use the generic package Ada.Containers.Vectors, or possibly the package Ada.Containers.Indefinite_Vectors. Those packages already define all the capabilities you seem to require.
The description of the generic package Ada.Containers.Vectors, as shown in the Ada 2012 Reference Manual is</p>

```<code>with Ada.Iterator_Interfaces;
generic
   type Index_Type is range <>;
   type Element_Type is private;
   with function "=" (Left, Right : Element_Type) return Boolean is <>;
package Ada.Containers.Vectors is
   pragma Preelaborate(Vectors);
   pragma Remote_Types(Vectors);

   subtype Extended_Index is
      Index_Type'Base range
         Index_Type'First-1 ..
         Index_Type'Min (Index_Type'Base'Last - 1, Index_Type'Last) + 1;
   No_Index : constant Extended_Index := Extended_Index'First;

   type Vector is tagged private
      with Constant_Indexing => Constant_Reference,
           Variable_Indexing => Reference,
           Default_Iterator  => Iterate,
           Iterator_Element  => Element_Type;
   pragma Preelaborable_Initialization(Vector);

   type Cursor is private;
   pragma Preelaborable_Initialization(Cursor);

   Empty_Vector : constant Vector;

   No_Element : constant Cursor;

   function Has_Element (Position : Cursor) return Boolean;

   package Vector_Iterator_Interfaces is new
       Ada.Iterator_Interfaces (Cursor, Has_Element);

   function "=" (Left, Right : Vector) return Boolean;

   function To_Vector (Length : Count_Type) return Vector;

   function To_Vector
     (New_Item : Element_Type;
      Length   : Count_Type) return Vector;

   function "&" (Left, Right : Vector) return Vector;

   function "&" (Left  : Vector;
                 Right : Element_Type) return Vector;

   function "&" (Left  : Element_Type;
                 Right : Vector) return Vector;

   function "&" (Left, Right  : Element_Type) return Vector;

   function Capacity (Container : Vector) return Count_Type;

   procedure Reserve_Capacity (Container : in out Vector;
                               Capacity  : in     Count_Type);

   function Length (Container : Vector) return Count_Type;

   procedure Set_Length (Container : in out Vector;
                         Length    : in     Count_Type);

   function Is_Empty (Container : Vector) return Boolean;

   procedure Clear (Container : in out Vector);

   function To_Cursor (Container : Vector;
                       Index     : Extended_Index) return Cursor;

   function To_Index (Position  : Cursor) return Extended_Index;

   function Element (Container : Vector;
                     Index     : Index_Type)
      return Element_Type;

   function Element (Position : Cursor) return Element_Type;

   procedure Replace_Element (Container : in out Vector;
                              Index     : in     Index_Type;
                              New_Item  : in     Element_Type);

   procedure Replace_Element (Container : in out Vector;
                              Position  : in     Cursor;
                              New_item  : in     Element_Type);

   procedure Query_Element
     (Container : in Vector;
      Index     : in Index_Type;
      Process   : not null access procedure (Element : in Element_Type));

   procedure Query_Element
     (Position : in Cursor;
      Process  : not null access procedure (Element : in Element_Type));

   procedure Update_Element
     (Container : in out Vector;
      Index     : in     Index_Type;
      Process   : not null access procedure
                      (Element : in out Element_Type));

   procedure Update_Element
     (Container : in out Vector;
      Position  : in     Cursor;
      Process   : not null access procedure
                      (Element : in out Element_Type));

   type Constant_Reference_Type
         (Element : not null access constant Element_Type) is private
      with Implicit_Dereference => Element;

   type Reference_Type (Element : not null access Element_Type) is private
      with Implicit_Dereference => Element;

   function Constant_Reference (Container : aliased in Vector;
                                Index     : in Index_Type)
      return Constant_Reference_Type;

   function Reference (Container : aliased in out Vector;
                       Index     : in Index_Type)
      return Reference_Type;

   function Constant_Reference (Container : aliased in Vector;
                                Position  : in Cursor)
      return Constant_Reference_Type;

   function Reference (Container : aliased in out Vector;
                       Position  : in Cursor)
      return Reference_Type;

   procedure Assign (Target : in out Vector; Source : in Vector);

   function Copy (Source : Vector; Capacity : Count_Type := 0)
      return Vector;

   procedure Move (Target : in out Vector;
                   Source : in out Vector);

   procedure Insert (Container : in out Vector;
                     Before    : in     Extended_Index;
                     New_Item  : in     Vector);

   procedure Insert (Container : in out Vector;
                     Before    : in     Cursor;
                     New_Item  : in     Vector);

   procedure Insert (Container : in out Vector;
                     Before    : in     Cursor;
                     New_Item  : in     Vector;
                     Position  :    out Cursor);

   procedure Insert (Container : in out Vector;
                     Before    : in     Extended_Index;
                     New_Item  : in     Element_Type;
                     Count     : in     Count_Type := 1);

   procedure Insert (Container : in out Vector;
                     Before    : in     Cursor;
                     New_Item  : in     Element_Type;
                     Count     : in     Count_Type := 1);

   procedure Insert (Container : in out Vector;
                     Before    : in     Cursor;
                     New_Item  : in     Element_Type;
                     Position  :    out Cursor;
                     Count     : in     Count_Type := 1);

   procedure Insert (Container : in out Vector;
                     Before    : in     Extended_Index;
                     Count     : in     Count_Type := 1);

   procedure Insert (Container : in out Vector;
                     Before    : in     Cursor;
                     Position  :    out Cursor;
                     Count     : in     Count_Type := 1);

   procedure Prepend (Container : in out Vector;
                      New_Item  : in     Vector);

   procedure Prepend (Container : in out Vector;
                      New_Item  : in     Element_Type;
                      Count     : in     Count_Type := 1);

   procedure Append (Container : in out Vector;
                     New_Item  : in     Vector);

   procedure Append (Container : in out Vector;
                     New_Item  : in     Element_Type;
                     Count     : in     Count_Type := 1);

   procedure Insert_Space (Container : in out Vector;
                           Before    : in     Extended_Index;
                           Count     : in     Count_Type := 1);

   procedure Insert_Space (Container : in out Vector;
                           Before    : in     Cursor;
                           Position  :    out Cursor;
                           Count     : in     Count_Type := 1);

   procedure Delete (Container : in out Vector;
                     Index     : in     Extended_Index;
                     Count     : in     Count_Type := 1);

   procedure Delete (Container : in out Vector;
                     Position  : in out Cursor;
                     Count     : in     Count_Type := 1);

   procedure Delete_First (Container : in out Vector;
                           Count     : in     Count_Type := 1);

   procedure Delete_Last (Container : in out Vector;
                          Count     : in     Count_Type := 1);

   procedure Reverse_Elements (Container : in out Vector);

   procedure Swap (Container : in out Vector;
                   I, J      : in     Index_Type);

   procedure Swap (Container : in out Vector;
                   I, J      : in     Cursor);

   function First_Index (Container : Vector) return Index_Type;

   function First (Container : Vector) return Cursor;

   function First_Element (Container : Vector)
      return Element_Type;

   function Last_Index (Container : Vector) return Extended_Index;

   function Last (Container : Vector) return Cursor;

   function Last_Element (Container : Vector)
      return Element_Type;

   function Next (Position : Cursor) return Cursor;

   procedure Next (Position : in out Cursor);

   function Previous (Position : Cursor) return Cursor;

   procedure Previous (Position : in out Cursor);

   function Find_Index (Container : Vector;
                        Item      : Element_Type;
                        Index     : Index_Type := Index_Type'First)
      return Extended_Index;

   function Find (Container : Vector;
                  Item      : Element_Type;
                  Position  : Cursor := No_Element)
      return Cursor;

   function Reverse_Find_Index (Container : Vector;
                                Item      : Element_Type;
                                Index     : Index_Type := Index_Type'Last)
      return Extended_Index;

   function Reverse_Find (Container : Vector;
                          Item      : Element_Type;
                          Position  : Cursor := No_Element)
      return Cursor;

   function Contains (Container : Vector;
                      Item      : Element_Type) return Boolean;

   procedure  Iterate
     (Container : in Vector;
      Process   : not null access procedure (Position : in Cursor));

   procedure Reverse_Iterate
     (Container : in Vector;
      Process   : not null access procedure (Position : in Cursor));

   function Iterate (Container : in Vector)
      return Vector_Iterator_Interfaces.Reversible_Iterator'Class;

   function Iterate (Container : in Vector; Start : in Cursor)
      return Vector_Iterator_Interfaces.Reversible_Iterator'Class;

   generic
      with function "<" (Left, Right : Element_Type)
         return Boolean is <>;
   package Generic_Sorting is

      function Is_Sorted (Container : Vector) return Boolean;

      procedure Sort (Container : in out Vector);

      procedure Merge (Target  : in out Vector;
                       Source  : in out Vector);

   end Generic_Sorting;

private

   ... -- not specified by the language

end Ada.Containers.Vectors;
</code>```

Body:
it sounds like you want to use the generic package Ada.Containers.Vectors, or possibly the package Ada.Containers.Indefinite_Vectors. Those packages already define all the capabilities you seem to require.
The description of the generic package Ada.Containers.Vectors, as shown in the Ada 2012 Reference Manual is

with Ada.Iterator_Interfaces;
generic
   type Index_Type is range <>;
   type Element_Type is private;
   with function "=" (Left, Right : Element_Type) return Boolean is <>;
package Ada.Containers.Vectors is
   pragma Preelaborate(Vectors);
   pragma Remote_Types(Vectors);

   subtype Extended_Index is
      Index_Type'Base range
         Index_Type'First-1 ..
         Index_Type'Min (Index_Type'Base'Last - 1, Index_Type'Last) + 1;
   No_Index : constant Extended_Index := Extended_Index'First;

   type Vector is tagged private
      with Constant_Indexing => Constant_Reference,
           Variable_Indexing => Reference,
           Default_Iterator  => Iterate,
           Iterator_Element  => Element_Type;
   pragma Preelaborable_Initialization(Vector);

   type Cursor is private;
   pragma Preelaborable_Initialization(Cursor);

   Empty_Vector : constant Vector;

   No_Element : constant Cursor;

   function Has_Element (Position : Cursor) return Boolean;

   package Vector_Iterator_Interfaces is new
       Ada.Iterator_Interfaces (Cursor, Has_Element);

   function "=" (Left, Right : Vector) return Boolean;

   function To_Vector (Length : Count_Type) return Vector;

   function To_Vector
     (New_Item : Element_Type;
      Length   : Count_Type) return Vector;

   function "&" (Left, Right : Vector) return Vector;

   function "&" (Left  : Vector;
                 Right : Element_Type) return Vector;

   function "&" (Left  : Element_Type;
                 Right : Vector) return Vector;

   function "&" (Left, Right  : Element_Type) return Vector;

   function Capacity (Container : Vector) return Count_Type;

   procedure Reserve_Capacity (Container : in out Vector;
                               Capacity  : in     Count_Type);

   function Length (Container : Vector) return Count_Type;

   procedure Set_Length (Container : in out Vector;
                         Length    : in     Count_Type);

   function Is_Empty (Container : Vector) return Boolean;

   procedure Clear (Container : in out Vector);

   function To_Cursor (Container : Vector;
                       Index     : Extended_Index) return Cursor;

   function To_Index (Position  : Cursor) return Extended_Index;

   function Element (Container : Vector;
                     Index     : Index_Type)
      return Element_Type;

   function Element (Position : Cursor) return Element_Type;

   procedure Replace_Element (Container : in out Vector;
                              Index     : in     Index_Type;
                              New_Item  : in     Element_Type);

   procedure Replace_Element (Container : in out Vector;
                              Position  : in     Cursor;
                              New_item  : in     Element_Type);

   procedure Query_Element
     (Container : in Vector;
      Index     : in Index_Type;
      Process   : not null access procedure (Element : in Element_Type));

   procedure Query_Element
     (Position : in Cursor;
      Process  : not null access procedure (Element : in Element_Type));

   procedure Update_Element
     (Container : in out Vector;
      Index     : in     Index_Type;
      Process   : not null access procedure
                      (Element : in out Element_Type));

   procedure Update_Element
     (Container : in out Vector;
      Position  : in     Cursor;
      Process   : not null access procedure
                      (Element : in out Element_Type));

   type Constant_Reference_Type
         (Element : not null access constant Element_Type) is private
      with Implicit_Dereference => Element;

   type Reference_Type (Element : not null access Element_Type) is private
      with Implicit_Dereference => Element;

   function Constant_Reference (Container : aliased in Vector;
                                Index     : in Index_Type)
      return Constant_Reference_Type;

   function Reference (Container : aliased in out Vector;
                       Index     : in Index_Type)
      return Reference_Type;

   function Constant_Reference (Container : aliased in Vector;
                                Position  : in Cursor)
      return Constant_Reference_Type;

   function Reference (Container : aliased in out Vector;
                       Position  : in Cursor)
      return Reference_Type;

   procedure Assign (Target : in out Vector; Source : in Vector);

   function Copy (Source : Vector; Capacity : Count_Type := 0)
      return Vector;

   procedure Move (Target : in out Vector;
                   Source : in out Vector);

   procedure Insert (Container : in out Vector;
                     Before    : in     Extended_Index;
                     New_Item  : in     Vector);

   procedure Insert (Container : in out Vector;
                     Before    : in     Cursor;
                     New_Item  : in     Vector);

   procedure Insert (Container : in out Vector;
                     Before    : in     Cursor;
                     New_Item  : in     Vector;
                     Position  :    out Cursor);

   procedure Insert (Container : in out Vector;
                     Before    : in     Extended_Index;
                     New_Item  : in     Element_Type;
                     Count     : in     Count_Type := 1);

   procedure Insert (Container : in out Vector;
                     Before    : in     Cursor;
                     New_Item  : in     Element_Type;
                     Count     : in     Count_Type := 1);

   procedure Insert (Container : in out Vector;
                     Before    : in     Cursor;
                     New_Item  : in     Element_Type;
                     Position  :    out Cursor;
                     Count     : in     Count_Type := 1);

   procedure Insert (Container : in out Vector;
                     Before    : in     Extended_Index;
                     Count     : in     Count_Type := 1);

   procedure Insert (Container : in out Vector;
                     Before    : in     Cursor;
                     Position  :    out Cursor;
                     Count     : in     Count_Type := 1);

   procedure Prepend (Container : in out Vector;
                      New_Item  : in     Vector);

   procedure Prepend (Container : in out Vector;
                      New_Item  : in     Element_Type;
                      Count     : in     Count_Type := 1);

   procedure Append (Container : in out Vector;
                     New_Item  : in     Vector);

   procedure Append (Container : in out Vector;
                     New_Item  : in     Element_Type;
                     Count     : in     Count_Type := 1);

   procedure Insert_Space (Container : in out Vector;
                           Before    : in     Extended_Index;
                           Count     : in     Count_Type := 1);

   procedure Insert_Space (Container : in out Vector;
                           Before    : in     Cursor;
                           Position  :    out Cursor;
                           Count     : in     Count_Type := 1);

   procedure Delete (Container : in out Vector;
                     Index     : in     Extended_Index;
                     Count     : in     Count_Type := 1);

   procedure Delete (Container : in out Vector;
                     Position  : in out Cursor;
                     Count     : in     Count_Type := 1);

   procedure Delete_First (Container : in out Vector;
                           Count     : in     Count_Type := 1);

   procedure Delete_Last (Container : in out Vector;
                          Count     : in     Count_Type := 1);

   procedure Reverse_Elements (Container : in out Vector);

   procedure Swap (Container : in out Vector;
                   I, J      : in     Index_Type);

   procedure Swap (Container : in out Vector;
                   I, J      : in     Cursor);

   function First_Index (Container : Vector) return Index_Type;

   function First (Container : Vector) return Cursor;

   function First_Element (Container : Vector)
      return Element_Type;

   function Last_Index (Container : Vector) return Extended_Index;

   function Last (Container : Vector) return Cursor;

   function Last_Element (Container : Vector)
      return Element_Type;

   function Next (Position : Cursor) return Cursor;

   procedure Next (Position : in out Cursor);

   function Previous (Position : Cursor) return Cursor;

   procedure Previous (Position : in out Cursor);

   function Find_Index (Container : Vector;
                        Item      : Element_Type;
                        Index     : Index_Type := Index_Type'First)
      return Extended_Index;

   function Find (Container : Vector;
                  Item      : Element_Type;
                  Position  : Cursor := No_Element)
      return Cursor;

   function Reverse_Find_Index (Container : Vector;
                                Item      : Element_Type;
                                Index     : Index_Type := Index_Type'Last)
      return Extended_Index;

   function Reverse_Find (Container : Vector;
                          Item      : Element_Type;
                          Position  : Cursor := No_Element)
      return Cursor;

   function Contains (Container : Vector;
                      Item      : Element_Type) return Boolean;

   procedure  Iterate
     (Container : in Vector;
      Process   : not null access procedure (Position : in Cursor));

   procedure Reverse_Iterate
     (Container : in Vector;
      Process   : not null access procedure (Position : in Cursor));

   function Iterate (Container : in Vector)
      return Vector_Iterator_Interfaces.Reversible_Iterator'Class;

   function Iterate (Container : in Vector; Start : in Cursor)
      return Vector_Iterator_Interfaces.Reversible_Iterator'Class;

   generic
      with function "<" (Left, Right : Element_Type)
         return Boolean is <>;
   package Generic_Sorting is

      function Is_Sorted (Container : Vector) return Boolean;

      procedure Sort (Container : in out Vector);

      procedure Merge (Target  : in out Vector;
                       Source  : in out Vector);

   end Generic_Sorting;

private

   ... -- not specified by the language

end Ada.Containers.Vectors;


问:
How to accept `Box<dyn Error + Send>` in places that accept `Box<dyn Error>`?
Can I accept a Box<dyn Error + Send> in places that accept Box<dyn Error>? If yes, how? If no, why, and is there a more elegant way to do it than in the following example?

#![allow(unused)]

use std::error::Error as StdError;
use std::result::Result as StdResult;

type    Result = StdResult<(), Box< dyn StdError >>;
type SndResult = StdResult<(), Box< dyn StdError + Send >>;

fn fn_returning_result()    ->    Result { Ok(()) }
fn fn_returning_sndresult() -> SndResult { Ok(()) }

/// Accept a callback that returns a non-Send `Result`.
fn register_callback<CB: FnOnce() -> Result>(cb: CB) { /* ... */ }

fn main() -> Result {
    // Is there a way to get rid of ... vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ... this part?
    let cb = || fn_returning_sndresult().map_err(|e| -> Box<dyn StdError> { e });
    register_callback(cb);

    Ok(())
}
```

Playground

Edit: What I would like to do here is just let cb = || fn_returning_sndresult();, but that won't compile.

Also, I'd like to call either fn_returning_result()? or fn_returning_sndresult()? inside the callback with a single return type and without doing a map_err.

答:
This is based on an answer I got on Reddit by Llaurence_:

I can change register_callback to accept both Box<dyn Error> and Box<dyn Error + Send> errors by making the error type generic:

fn register_callback<CB, E>(cb: CB)
where
    CB: FnOnce() -> StdResult<(), Box<E>>,
    E: StdError + ?Sized,
{ /* ... */ }
```

<p>Now I can pass a callback that returns either kind of error / result:</p>

<pre class="lang-rust prettyprint-override"><code>register_callback(fn_returning_result);
register_callback(fn_returning_sndresult);
</code>```

Body:
Can I accept a Box<dyn Error + Send> in places that accept Box<dyn Error>? If yes, how? If no, why, and is there a more elegant way to do it than in the following example?

#![allow(unused)]

use std::error::Error as StdError;
use std::result::Result as StdResult;

type    Result = StdResult<(), Box< dyn StdError >>;
type SndResult = StdResult<(), Box< dyn StdError + Send >>;

fn fn_returning_result()    ->    Result { Ok(()) }
fn fn_returning_sndresult() -> SndResult { Ok(()) }

/// Accept a callback that returns a non-Send `Result`.
fn register_callback<CB: FnOnce() -> Result>(cb: CB) { /* ... */ }

fn main() -> Result {
    // Is there a way to get rid of ... vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ... this part?
    let cb = || fn_returning_sndresult().map_err(|e| -> Box<dyn StdError> { e });
    register_callback(cb);

    Ok(())
}

Playground

Edit: What I would like to do here is just let cb = || fn_returning_sndresult();, but that won't compile.

Also, I'd like to call either fn_returning_result()? or fn_returning_sndresult()? inside the callback with a single return type and without doing a map_err.

Body:
This is based on an answer I got on Reddit by Llaurence_:

I can change register_callback to accept both Box<dyn Error> and Box<dyn Error + Send> errors by making the error type generic:

fn register_callback<CB, E>(cb: CB)
where
    CB: FnOnce() -> StdResult<(), Box<E>>,
    E: StdError + ?Sized,
{ /* ... */ }

Now I can pass a callback that returns either kind of error / result:

register_callback(fn_returning_result);
register_callback(fn_returning_sndresult);


问:
Get Value out of Callback
I have a callback, where I need to get the array out of my callback.

I am trying to return the awaited array into the predefined one.

```<code>let documents = [];

  socket.on('echo', async function(documents, data){
    documents = await data;
    console.log(documents); // shows me, what I want to see
  });

  console.log(documents); // empty Array
</code>```

I need the result in my predefined Array documents

I have read several Tuts, but I dont get it. I know on stackoverflow it is sked several times. But all threads seem to be more complex then my situation. So I hope to get it cleared out with an more incomplex one.

答:
```<code>let documents = await socket.on('echo', async function(documents, data){
    console.log(documents);
    return data;
  });

console.log(documents);
</code>```

Title: Get Value out of Callback

Body:
I have a callback, where I need to get the array out of my callback.

I am trying to return the awaited array into the predefined one.

let documents = [];

  socket.on('echo', async function(documents, data){
    documents = await data;
    console.log(documents); // shows me, what I want to see
  });

  console.log(documents); // empty Array

I need the result in my predefined Array documents

I have read several Tuts, but I dont get it. I know on stackoverflow it is sked several times. But all threads seem to be more complex then my situation. So I hope to get it cleared out with an more incomplex one.


问:
Is there URL class in JavaScript?
In JavaScript, is there any class equivalent for

NSURL class in iOS SDK or

URL class in Java?

With such class, I want to:

normalize URL,

compose a URL from scheme, host, path components, etc..., and

decompose a URL into its elements.

答:
Yes! There is now a standard, broadly compatible, URL class for Javascript.

The constructor takes a url parameter, and an optional base parameter to use as a base if the url parameter is a relative URL

```<code>const url = new URL(window.location.href);
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"
</code>```

Title: Is there URL class in JavaScript?

Body:
Yes! There is now a standard, broadly compatible, URL class for Javascript.

The constructor takes a url parameter, and an optional base parameter to use as a base if the url parameter is a relative URL

const url = new URL(window.location.href);
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"


答:
The problem is that the code outside the socket function executes with the empty array because is only executed once at runtime.

If you want to have access to the documents inside the socket function you have to make then persist, or use the socket.on inside of another loop.

Title: Get Value out of Callback


答:
You need to understand something first. When this runs what is inside the callback doesn't run unit the server will emit that event, in your case 'echo'.

What I think you want to do is use documents outside the callback. You can create a function and call it when the event is emitted.

Something like this:

```<code>const manageDocuments = (documents) => {
    // do what you want with documents array
    console.log(documents);
}

socket.on('echo', async function(documents, data){
    documents = await data;
    manageDocuments(documents);
});
</code>```

Of course you can also get rid of the async/await

Title: Get Value out of Callback

Body:
You need to understand something first. When this runs what is inside the callback doesn't run unit the server will emit that event, in your case 'echo'.

What I think you want to do is use documents outside the callback. You can create a function and call it when the event is emitted.

Something like this:

const manageDocuments = (documents) => {
    // do what you want with documents array
    console.log(documents);
}

socket.on('echo', async function(documents, data){
    documents = await data;
    manageDocuments(documents);
});

Of course you can also get rid of the async/await


问:
Visual Studio Code and ESLint aren't detecting typos e.g. "style.backgroundCOlor". How can I fix this?
When I'm using Visual Studio Code and the extension "ESLint" my typos are not being recognised. These typos are actually workable (but not working because of the typo) code not just comments. I am new to Visual Studio Code and most of my experience has been with Brackets.

I've tried looking in the ESLint extension files: eslintrc.js, package-lock.json and package.json. I've also looked at my "code-workspace" file but I really don't know what I'm looking for.

document.body.style.backgroundCOlor = "#f00";

The line of code simply won't work because of the obvious upper-case "O". The code obviously works when the "O" is lower-case. It took so long to find this typo because it wasn't being flagged as an error.

Any help is greatly appreciated.

答:
As mentioned by @Olian04, you can put //@ts-check at the top of your file, what you can also do is add "javascript.implicitProjectConfig.checkJs": true in your settings.json file to automatically do this for every file, without having to add this comment at the top of every file and cluttering code (albeit in a very minor way).

To find the settings.json file, hit cmd + , and click on the braces in the top right corner.


问:
How to make an if statement to disable select option?
I have three select menus where the user selects a subject, year and season. However, I want it so that if the user selects the year '2019', the 'Fall' option will get disabled.

<select name="Subject">
    <option value="Math">Math</option>
    <option value="Physics">Physics</option>
    <option value="Chemistry">Chemistry</option>
    <option value="Biology">Biology</option>
</select>

<select name="Year">
    <option value="2019">2019</option>
    <option value="2018">2018</option>
    <option value="2017">2017</option>
    <option value="2016">2016</option>
</select>

<select name="Season">
    <option value="Spring">Spring</option>
    <option value="Fall">Fall</option>
</select>```

答:
Create and event handler for the Year's change event and disable the season based on what Year's new value is.

https://jsfiddle.net/075fnm4a/

HTML

```<code><select name="Subject">
    <option value="Math">Math</option>
    <option value="Physics">Physics</option>
    <option value="Chemistry">Chemistry</option>
    <option value="Biology">Biology</option>
</select>

<select name="Year">
    <option value="2019">2019</option>
    <option value="2018">2018</option>
    <option value="2017">2017</option>
    <option value="2016">2016</option>
</select>

<select name="Season">
    <option value="Spring">Spring</option>
    <option value="Fall">Fall</option>
</select>
</code>```

Jquery

```<code>$(document).ready(function(){

  $('select[name="Year"]').on('change',function(){
    var $this = $(this);
    $('select[name="Season"]').find('option[value="Fall"]').prop('disabled', ($this.val() == '2019') ); // disabled or enabled
  });

  $('select[name="Year"]').trigger('change');

});
</code>```

Body:
Create and event handler for the Year's change event and disable the season based on what Year's new value is.

https://jsfiddle.net/075fnm4a/

HTML

<select name="Subject">
    <option value="Math">Math</option>
    <option value="Physics">Physics</option>
    <option value="Chemistry">Chemistry</option>
    <option value="Biology">Biology</option>
</select>

<select name="Year">
    <option value="2019">2019</option>
    <option value="2018">2018</option>
    <option value="2017">2017</option>
    <option value="2016">2016</option>
</select>

<select name="Season">
    <option value="Spring">Spring</option>
    <option value="Fall">Fall</option>
</select>

Jquery

$(document).ready(function(){

  $('select[name="Year"]').on('change',function(){
    var $this = $(this);
    $('select[name="Season"]').find('option[value="Fall"]').prop('disabled', ($this.val() == '2019') ); // disabled or enabled
  });

  $('select[name="Year"]').trigger('change');

});


问:
PHP Date - How to add a string to separate date and time
I want to display date and time format something like this "May 23 at 12:30pm".
I saw in PHP manual and found:

```<code>// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
</code>```

After modification I manage to get

```<code> echo date('M j \of h:i a');
</code>```

it is giving me "May 23 of 12:30pm"

but when i replacing of with at it is giving me "May 23 a23 08:26 pm".

I don't what is going wrong.

答:
You need to try this in php:</p>

```<code>$t = now(); //This will give you current time
echo date_format($t,"dS M,y \a\\t h:i a"); //14th May,19 at 05:39am
</code>```

Body:
I want to display date and time format something like this "May 23 at 12:30pm".
I saw in PHP manual and found:

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

After modification I manage to get

 echo date('M j \of h:i a');

it is giving me "May 23 of 12:30pm"

but when i replacing of with at it is giving me "May 23 a23 08:26 pm".

I don't what is going wrong.

Body:
You need to try this in php:

$t = now(); //This will give you current time
echo date_format($t,"dS M,y \a\\t h:i a"); //14th May,19 at 05:39am


问:
str' object has no attribute 'load_img'
I wanted to load all the images from a folder and make predictions on those images

this is what i tried

```<code>    images = []
    folder_path="C:/Users/Harsh/Desktop/Ornithopter/anv/train/images/"
    for img in os.listdir(folder_path):
     img = image.load_img(img, target_size=(img_width, img_height))
     img = img.img_to_array(img)
     img = np.expand_dims(img, axis=0)
     images.append(img)
</code>```

The above mentioned error arises on the line
img = image.load_img(img, target_size=(img_width, img_height))

答:
You have overwritten the image variable with a string instead of keeping it to the keras.preprocessing.image module. This would happen if you do:

```<code>from keras.preprocessing import image
</code>```

And then set image to anything. Be careful with naming variables the same as a package or a module.

Title: str' object has no attribute 'load_img'

Body:
I wanted to load all the images from a folder and make predictions on those images

this is what i tried

    images = []
    folder_path="C:/Users/Harsh/Desktop/Ornithopter/anv/train/images/"
    for img in os.listdir(folder_path):
     img = image.load_img(img, target_size=(img_width, img_height))
     img = img.img_to_array(img)
     img = np.expand_dims(img, axis=0)
     images.append(img)

The above mentioned error arises on the line
img = image.load_img(img, target_size=(img_width, img_height))

Body:
You have overwritten the image variable with a string instead of keeping it to the keras.preprocessing.image module. This would happen if you do:

from keras.preprocessing import image

And then set image to anything. Be careful with naming variables the same as a package or a module.


问:
Move terminal back to bottom
I accidentally clicked the button that moves the terminal from the bottom to the right. How do I get it back to the bottom? Clicking the split button again just splits the terminal.</p>

答:
Had the same issue.
Solved. MAC_BOOK_PRO 2018

Moving the cursor to the terminal.

Title: Move terminal back to bottom


问:
Is there a way to define "% of column total" measure in DAX which would work dynamically for any dimension?
I need my measure % of column total to work with any dimension that is currently selected in the pivot columns.

I have this formula which works for dimension called Gender, but I need the formula to be general and work for any dimension currently selected. I am using this measure to calculate other measures.

```<code>Weighted Gender % :=
DIVIDE (
    'Dimensions'[Weigthed Base];
    CALCULATE ( 'Dimensions'[Weigthed Base]; ALLSELECTED ( 'Dimensions'[Gender] ) )
)
</code>```

Is it possible?

答:
You can use a general version of ALLSELECTED():

```<code>Weighted % :=
DIVIDE (
    'Dimensions'[Weigthed Base];
    CALCULATE ( 'Dimensions'[Weigthed Base]; ALLSELECTED () )
)
</code>```

Be careful though, ALLSELECTED is a complex function, and you might get unexpected results depending on your data model:

https://www.sqlbi.com/articles/the-definitive-guide-to-allselected/

Body:
I need my measure % of column total to work with any dimension that is currently selected in the pivot columns.

I have this formula which works for dimension called Gender, but I need the formula to be general and work for any dimension currently selected. I am using this measure to calculate other measures.

Weighted Gender % :=
DIVIDE (
    'Dimensions'[Weigthed Base];
    CALCULATE ( 'Dimensions'[Weigthed Base]; ALLSELECTED ( 'Dimensions'[Gender] ) )
)

Is it possible?

Body:
You can use a general version of ALLSELECTED():

Weighted % :=
DIVIDE (
    'Dimensions'[Weigthed Base];
    CALCULATE ( 'Dimensions'[Weigthed Base]; ALLSELECTED () )
)

Be careful though, ALLSELECTED is a complex function, and you might get unexpected results depending on your data model:

https://www.sqlbi.com/articles/the-definitive-guide-to-allselected/


问:
Grouping elements close together
I'm trying to figure out a solid way of grouping elements together that a value is next in the list.

The data I have is this

let values = [
    ChartDataEntry(x: 0.0, y: -13.0),
    ChartDataEntry(x: 1.0, y: -13.0),
    ChartDataEntry(x: 2.0, y: 0.68),
    ChartDataEntry(x: 3.0, y: -13.0),
    ChartDataEntry(x: 4.0, y: 1.7),
    ChartDataEntry(x: 5.0, y: 0.5),
    ChartDataEntry(x: 6.0, y: 10.0)
]
```

<p>I'm trying to group it so it's more like this</p>

<pre class="lang-swift prettyprint-override"><code>let values = [
    [
        ChartDataEntry(x: 0.0, y: -13.0),
        ChartDataEntry(x: 1.0, y: -13.0),
        ChartDataEntry(x: 3.0, y: -13.0)
    ],
    [
        ChartDataEntry(x: 2.0, y: 0.68)
    ],
    [
        ChartDataEntry(x: 4.0, y: 1.7),
        ChartDataEntry(x: 5.0, y: 0.5),
        ChartDataEntry(x: 6.0, y: -10.0)
    ]
]
</code>```

Essentially the grouping I am trying to achieve is elements that x elements that have a value above -13.0 go together and elements below -13 go together. The tricky part is grouping by the x value.

The goal is to group values by the x value that are next to each other.

x: 2.0 is next to 3.0, but it's -13, so it doesnt belong in the same group, but if you look at 4.0, 5.0, & 6.0, they would all get grouped together as they have a value greater than -13 consecutively

I hope this makes sense.

答:
Use reduce(into:_:) method and enumerate the array elements. If ChartDataEntry y value is less than -13.0, get the array index where its elements are less than or equal to -13.0 and append the ChartDataEntry object to that sub array. If not find the sub array which contains a ChartDataEntry object with x value adjacent to current ChartDataEntry object, and append to the sub array. If both condition fails append a new sub array with the ChartDataEntry object.

```<code>let result = values.reduce(into: [[ChartDataEntry]]()) { (result, chart) in
    if chart.y <= -13.0, let index = result.firstIndex(where: { $0.contains(where: { $0.y <= -13.0 }) }) {
        result[index].append(chart)
    } else if let index = result.firstIndex(where: { $0.contains(where: { $0.y > -13.0 && $0.x.advanced(by: 1) == chart.x }) }) {
        result[index].append(chart)
    } else {
        result.append([chart])
    }
}
print(result)

//[[ChartDataEntry(x: 0.0, y: -13.0), ChartDataEntry(x: 1.0, y: -13.0), ChartDataEntry(x: 3.0, y: -13.0)],
//[ChartDataEntry(x: 2.0, y: 0.68)],
//[ChartDataEntry(x: 4.0, y: 1.7), ChartDataEntry(x: 5.0, y: 0.5), ChartDataEntry(x: 6.0, y: 10.0)]]
</code>```

Title: Grouping elements close together

Body:
I'm trying to figure out a solid way of grouping elements together that a value is next in the list.

The data I have is this

let values = [
    ChartDataEntry(x: 0.0, y: -13.0),
    ChartDataEntry(x: 1.0, y: -13.0),
    ChartDataEntry(x: 2.0, y: 0.68),
    ChartDataEntry(x: 3.0, y: -13.0),
    ChartDataEntry(x: 4.0, y: 1.7),
    ChartDataEntry(x: 5.0, y: 0.5),
    ChartDataEntry(x: 6.0, y: 10.0)
]

I'm trying to group it so it's more like this

let values = [
    [
        ChartDataEntry(x: 0.0, y: -13.0),
        ChartDataEntry(x: 1.0, y: -13.0),
        ChartDataEntry(x: 3.0, y: -13.0)
    ],
    [
        ChartDataEntry(x: 2.0, y: 0.68)
    ],
    [
        ChartDataEntry(x: 4.0, y: 1.7),
        ChartDataEntry(x: 5.0, y: 0.5),
        ChartDataEntry(x: 6.0, y: -10.0)
    ]
]

Essentially the grouping I am trying to achieve is elements that x elements that have a value above -13.0 go together and elements below -13 go together. The tricky part is grouping by the x value.

The goal is to group values by the x value that are next to each other.

x: 2.0 is next to 3.0, but it's -13, so it doesnt belong in the same group, but if you look at 4.0, 5.0, & 6.0, they would all get grouped together as they have a value greater than -13 consecutively

I hope this makes sense.

Body:
Use reduce(into:_:) method and enumerate the array elements. If ChartDataEntry y value is less than -13.0, get the array index where its elements are less than or equal to -13.0 and append the ChartDataEntry object to that sub array. If not find the sub array which contains a ChartDataEntry object with x value adjacent to current ChartDataEntry object, and append to the sub array. If both condition fails append a new sub array with the ChartDataEntry object.

let result = values.reduce(into: [[ChartDataEntry]]()) { (result, chart) in
    if chart.y <= -13.0, let index = result.firstIndex(where: { $0.contains(where: { $0.y <= -13.0 }) }) {
        result[index].append(chart)
    } else if let index = result.firstIndex(where: { $0.contains(where: { $0.y > -13.0 && $0.x.advanced(by: 1) == chart.x }) }) {
        result[index].append(chart)
    } else {
        result.append([chart])
    }
}
print(result)

//[[ChartDataEntry(x: 0.0, y: -13.0), ChartDataEntry(x: 1.0, y: -13.0), ChartDataEntry(x: 3.0, y: -13.0)],
//[ChartDataEntry(x: 2.0, y: 0.68)],
//[ChartDataEntry(x: 4.0, y: 1.7), ChartDataEntry(x: 5.0, y: 0.5), ChartDataEntry(x: 6.0, y: 10.0)]]


问:
How to read files from a network drive in php?
I am working on php code as shown below in which I want  to read a network drives as shown below :

```<code>$src_dir = is_dir("\\\\ADMPC02-02\\music\\incoming_folder\\");    // Line#A

var_dump($src_dir);  // bool(false)

$mp4_files = preg_grep('~\.(mp4)$~', scandir($src_dir));

$xml_files = preg_grep('~\.(xml)$~', scandir($src_dir));

print_r($mp4_files);  // it doesn't print anything

print_r($xml_files);  // it doesnt print anything
</code>```

Problem Statement:

I am wondering what changes I need to make at Line#A so that I am successfully able network directory. On doing
var_dump($src_dir); it prints bool(false).

答:
This works for me:

```<code><?php

$src_dir = '\\\ADMPC02-02\test';
$is_dir = is_dir($src_dir); // returns true
$mp4_files = preg_grep('~\.(mp4)$~', scandir($src_dir));
$xml_files = preg_grep('~\.(xml)$~', scandir($src_dir));

echo '```';
print_r($mp4_files); // lists all the mp4 files in my 'test' folder
print_r($xml_files); // lists all the xml files in my 'test' folder
```

You should also make sure that:

Network discovery is On

Files and printers sharing is On

Your music folder is publicly shared will all required permissions for the current Windows user running PHP

I hope this helps!

Body:
I am working on php code as shown below in which I want  to read a network drives as shown below :

$src_dir = is_dir("\\\\ADMPC02-02\\music\\incoming_folder\\");    // Line#A

var_dump($src_dir);  // bool(false)

$mp4_files = preg_grep('~\.(mp4)$~', scandir($src_dir));

$xml_files = preg_grep('~\.(xml)$~', scandir($src_dir));

print_r($mp4_files);  // it doesn't print anything

print_r($xml_files);  // it doesnt print anything

Problem Statement:

I am wondering what changes I need to make at Line#A so that I am successfully able network directory. On doing
var_dump($src_dir); it prints bool(false).

Body:
This works for me:

<?php

$src_dir = '\\\ADMPC02-02\test';
$is_dir = is_dir($src_dir); // returns true
$mp4_files = preg_grep('~\.(mp4)$~', scandir($src_dir));
$xml_files = preg_grep('~\.(xml)$~', scandir($src_dir));

echo '<pre>';
print_r($mp4_files); // lists all the mp4 files in my 'test' folder
print_r($xml_files); // lists all the xml files in my 'test' folder

You should also make sure that:

Network discovery is On

Files and printers sharing is On

Your music folder is publicly shared will all required permissions for the current Windows user running PHP

I hope this helps!


答:
Like this.

document.querySelector('#year').onchange = ev => {
  const value = ev.target.value;
  if (value === '2019') {
    document.querySelector('#fall').disabled = true;
  } else {
    document.querySelector('#fall').disabled = false;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="Subject">
    <option value="Math">Math</option>
    <option value="Physics">Physics</option>
    <option value="Chemistry">Chemistry</option>
    <option value="Biology">Biology</option>
</select>

<select name="Year" id="year">
    <option value="2019">2019</option>
    <option value="2018">2018</option>
    <option value="2017">2017</option>
    <option value="2016">2016</option>
</select>

<select name="Season">
    <option value="Spring">Spring</option>
    <option value="Fall" id="fall" disabled>Fall</option>
</select></code>```

Title: How to make an if statement to disable select option?

Body:
I have three select menus where the user selects a subject, year and season. However, I want it so that if the user selects the year '2019', the 'Fall' option will get disabled.

<select name="Subject">
    <option value="Math">Math</option>
    <option value="Physics">Physics</option>
    <option value="Chemistry">Chemistry</option>
    <option value="Biology">Biology</option>
</select>

<select name="Year">
    <option value="2019">2019</option>
    <option value="2018">2018</option>
    <option value="2017">2017</option>
    <option value="2016">2016</option>
</select>

<select name="Season">
    <option value="Spring">Spring</option>
    <option value="Fall">Fall</option>
</select>

Body:
Like this.

document.querySelector('#year').onchange = ev => {
  const value = ev.target.value;
  if (value === '2019') {
    document.querySelector('#fall').disabled = true;
  } else {
    document.querySelector('#fall').disabled = false;
  }
}

<select name="Subject">
    <option value="Math">Math</option>
    <option value="Physics">Physics</option>
    <option value="Chemistry">Chemistry</option>
    <option value="Biology">Biology</option>
</select>

<select name="Year" id="year">
    <option value="2019">2019</option>
    <option value="2018">2018</option>
    <option value="2017">2017</option>
    <option value="2016">2016</option>
</select>

<select name="Season">
    <option value="Spring">Spring</option>
    <option value="Fall" id="fall" disabled>Fall</option>
</select>