问:
which storage type is good for large data when using dcc.Store()
when using dcc.Store() for large data, which storage type is good, memory, local or session?

I got an error of

```<code>IOPub data rate exceeded.
The notebook server will temporarily stop sending output
to the client in order to avoid crashing it.
To change this limit, set the config variable
`--NotebookApp.iopub_data_rate_limit`.

Current values:
NotebookApp.iopub_data_rate_limit=1000000.0 (bytes/sec)
NotebookApp.rate_limit_window=3.0 (secs)

</code>```

The webpage also crashes showing below figure:

答:
this component is not for storing large datasets... It's a good component to store some data that will be used through the application;

Also, Dash is not a good framework for big data projects like the one you did mention.

If you need some extra help feel free to message me pvt.

Body:
when using dcc.Store() for large data, which storage type is good, memory, local or session?

I got an error of

IOPub data rate exceeded.
The notebook server will temporarily stop sending output
to the client in order to avoid crashing it.
To change this limit, set the config variable
`--NotebookApp.iopub_data_rate_limit`.

Current values:
NotebookApp.iopub_data_rate_limit=1000000.0 (bytes/sec)
NotebookApp.rate_limit_window=3.0 (secs)

The webpage also crashes showing below figure:


来源: stackexchange

问:
How to keep escape keys from a json?
I´m making an application with dart / flutter and I need to keep the escape keys from the json server api response, how can I do that?

Example:

JSON reponse:

```<code>{"\"\"example\"\"": "value\'"}
</code>```

Goal (after .fromJson and json.decode):

Class.example = "\"\"example\"\"";

Class.value = "value\'";

答:
If you do jsonDecode(r'{"\"\"example\"\"": "value\'"}'), then you get a map with the key ""example"" and the value value' (the quotes are part of the string content here, not delimiters).
The backslashes are removed, which is to be expected because that's what the JSON specification says should happen. The escaped quotes are retained. The key does not become just example.

If you want to retain the backslashes too, then you don't actually want JSON decoding, because JSON decoding treats \" inside a string literal as introducing the character ".

If you wanted a string containing \"\"example\"\" from JSON decoding, then the original source needed to be "\\\"\\\"example\\\"\\\"".
So, if the sender of the JSON wanted you to see backslashes, they should have included and escaped those backslashes too.

If you JSON encode the string back, you get the backslashes again (at least for "), since jsonEncode('""example""') is "\"\"example\"\"".

If you really want access to the source code of the JSON input, I'd use a non-standard JSON parser, one which allows you to access the source instead of only the parsed value.

Example:

import "package:jsontool/jsontool.dart";

/// Parses [source] as JSON, but retains source escapes in strings.
Object? readJsonSourceStrings(String source) {
  return _readJson(JsonReader.fromString(source));
}

Object? _readJson(JsonReader<StringSlice> reader) {
  if (reader.tryObject()) {
    var map = <String, Object?>{};
    while (reader.hasNextKey()) {
      var keySlice = reader.nextKeySource()!;
      var key = keySlice.substring(1, keySlice.length - 1);
      map[key] = _readJson(reader);
    }
    return map;
  }
  if (reader.tryArray()) {
    var list = <Object?>[];
    while (reader.hasNext()) {
      list.add(_readJson(reader));
    }
    return list;
  }
  if (reader.checkString()) {
    var slice = reader.expectAnyValueSource();
    return slice.substring(1, slice.length - 1);
  }
  return reader.tryNum() ?? reader.tryBool() ??
      (reader.tryNull() ? null : (throw "Unreachable"));
}

void main() {
  var m = readJsonSourceStrings(r'''{"\"\"example\"\"":"value\'"}''');
  print(m); // {\"\"example\"\": value\'}
}
```

(Disclaimer: I wrote the jsontool package.)

ContentLicense: CC BY-SA 4.0

Title: How to keep escape keys from a json?

Body:
I´m making an application with dart / flutter and I need to keep the escape keys from the json server api response, how can I do that?

Example:

JSON reponse:

{"\"\"example\"\"": "value\'"}

Goal (after .fromJson and json.decode):

Class.example = "\"\"example\"\"";

Class.value = "value\'";

Body:
If you do jsonDecode(r'{"\"\"example\"\"": "value\'"}'), then you get a map with the key ""example"" and the value value' (the quotes are part of the string content here, not delimiters).
The backslashes are removed, which is to be expected because that's what the JSON specification says should happen. The escaped quotes are retained. The key does not become just example.

If you want to retain the backslashes too, then you don't actually want JSON decoding, because JSON decoding treats \" inside a string literal as introducing the character ".

If you wanted a string containing \"\"example\"\" from JSON decoding, then the original source needed to be "\\\"\\\"example\\\"\\\"".
So, if the sender of the JSON wanted you to see backslashes, they should have included and escaped those backslashes too.

If you JSON encode the string back, you get the backslashes again (at least for "), since jsonEncode('""example""') is "\"\"example\"\"".

If you really want access to the source code of the JSON input, I'd use a non-standard JSON parser, one which allows you to access the source instead of only the parsed value.

Example:

import "package:jsontool/jsontool.dart";

/// Parses [source] as JSON, but retains source escapes in strings.
Object? readJsonSourceStrings(String source) {
  return _readJson(JsonReader.fromString(source));
}

Object? _readJson(JsonReader<StringSlice> reader) {
  if (reader.tryObject()) {
    var map = <String, Object?>{};
    while (reader.hasNextKey()) {
      var keySlice = reader.nextKeySource()!;
      var key = keySlice.substring(1, keySlice.length - 1);
      map[key] = _readJson(reader);
    }
    return map;
  }
  if (reader.tryArray()) {
    var list = <Object?>[];
    while (reader.hasNext()) {
      list.add(_readJson(reader));
    }
    return list;
  }
  if (reader.checkString()) {
    var slice = reader.expectAnyValueSource();
    return slice.substring(1, slice.length - 1);
  }
  return reader.tryNum() ?? reader.tryBool() ??
      (reader.tryNull() ? null : (throw "Unreachable"));
}

void main() {
  var m = readJsonSourceStrings(r'''{"\"\"example\"\"":"value\'"}''');
  print(m); // {\"\"example\"\": value\'}
}

(Disclaimer: I wrote the jsontool package.)


问:
print binary tree level by level in python
I want to print my binary tree in the following manner:

```<code>                   10

               6        12

             5   7    11  13
</code>```

I have written code for insertion of nodes but can't able to write for printing the tree. so please help on this . My code is :

```<code>class Node:
    def __init__(self,data):
       self.data=data
       self.left=None
       self.right=None
       self.parent=None

class binarytree:
   def __init__(self):
     self.root=None
     self.size=0

   def insert(self,data):
     if self.root==None:
        self.root=Node(data)

    else:
        current=self.root
        while 1:
            if data < current.data:
                if current.left:
                    current=current.left
                else:
                    new=Node(data)
                    current.left=new
                    break;
            elif data > current.data:
                if current.right:
                    current=current.right
                else:
                    new=Node(data)
                    current.right=new
                    break;
            else:
                break

 b=binarytree()
</code>```

答:
This is part of my own implementation of BST. The ugly part of this problem is that you have to know the space that your children occupies before you can print out yourself. Because you can have very big numbers like 217348746327642386478832541267836128736..., but also small numbers like 10, so if you have a parent-children relationship between these two, then it can potentially overlap with your other child. Therefore, we need to first go through the children, make sure we get how much space they are having, then we use that information to construct ourself.

```<code>def __str__(self):
    h = self.getHeight()
    rowsStrs = ["" for i in range(2 * h - 1)]

    # return of helper is [leftLen, curLen, rightLen] where
    #   leftLen = children length of left side
    #   curLen = length of keyStr + length of "_" from both left side and right side
    #   rightLen = children length of right side.
    # But the point of helper is to construct rowsStrs so we get the representation
    # of this BST.
    def helper(node, curRow, curCol):
        if(not node): return [0, 0, 0]
        keyStr = str(node.key)
        keyStrLen = len(keyStr)
        l = helper(node.l, curRow + 2, curCol)
        rowsStrs[curRow] += (curCol -len(rowsStrs[curRow]) + l[0] + l[1] + 1) * " " + keyStr
        if(keyStrLen < l[2] and (node.r or (node.p and node.p.l == node))):
            rowsStrs[curRow] += (l[2] - keyStrLen) * "_"
        if(l[1]):
            rowsStrs[curRow + 1] += (len(rowsStrs[curRow + 2]) - len(rowsStrs[curRow + 1])) * " " + "/"
        r = helper(node.r, curRow + 2, len(rowsStrs[curRow]) + 1)
        rowsStrs[curRow] += r[0] * "_"
        if(r[1]):
            rowsStrs[curRow + 1] += (len(rowsStrs[curRow]) - len(rowsStrs[curRow + 1])) * " " + "\\"
        return [l[0] + l[1] + 1, max(l[2] - keyStrLen, 0) + keyStrLen + r[0], r[1] + r[2] + 1]

    helper(self.head, 0, 0)
    res = "\n".join(rowsStrs)
    #print("\n\n\nStart of BST:****************************************")
    #print(res)
    #print("End of BST:****************************************")
    #print("BST height: ", h, ", BST size: ", self.size)

    return res
</code>```

Here's some examples of running this:

```<code>[26883404633, 10850198033, 89739221773, 65799970852, 6118714998, 31883432186, 84275473611, 25958013736, 92141734773, 91725885198, 131191476, 81453208197, 41559969292, 90704113213, 6886252839]
                                     26883404633___________________________________________
                                    /                                                      \
                       10850198033__                                                        89739221773___________________________
                      /             \                                                      /                                      \
           6118714998_               25958013736                 65799970852_______________                                        92141734773
          /           \                                         /                          \                                      /
 131191476             6886252839                   31883432186_                            84275473611                91725885198
                                                                \                          /                          /
                                                                 41559969292    81453208197                90704113213
</code>```

Another example:

```<code>['rtqejfxpwmggfro', 'viwmdmpedzwvvxalr', 'mvvjmkdcdpcfb', 'ykqehfqbpcjfd', 'iuuujkmdcle', 'nzjbyuvlodahlpozxsc', 'wdjtqoygcgbt', 'aejduciizj', 'gzcllygjekujzcovv', 'naeivrsrfhzzfuirq', 'lwhcjbmcfmrsnwflezxx', 'gjdxphkpfmr', 'nartcxpqqongr', 'pzstcbohbrb', 'ykcvidwmouiuz']
                                                                                rtqejfxpwmggfro____________________
                                                                                /                                   \
                                              mvvjmkdcdpcfb_____________________________                                     viwmdmpedzwvvxalr_______________
                                             /                                          \                                                                    \
                         iuuujkmdcle_________                                            nzjbyuvlodahlpozxsc_                                                 ykqehfqbpcjfd
                        /                    \                                          /                    \                                               /
 aejduciizj_____________                      lwhcjbmcfmrsnwflezxx    naeivrsrfhzzfuirq_                      pzstcbohbrb                       wdjtqoygcgbt_
                        \                                                               \                                                                    \
                         gzcllygjekujzcovv                                               nartcxpqqongr                                                        ykcvidwmouiuz
                        /
             gjdxphkpfmr
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to print my binary tree in the following manner:

                   10

               6        12

             5   7    11  13

I have written code for insertion of nodes but can't able to write for printing the tree. so please help on this . My code is :

class Node:
    def __init__(self,data):
       self.data=data
       self.left=None
       self.right=None
       self.parent=None

class binarytree:
   def __init__(self):
     self.root=None
     self.size=0

   def insert(self,data):
     if self.root==None:
        self.root=Node(data)

    else:
        current=self.root
        while 1:
            if data < current.data:
                if current.left:
                    current=current.left
                else:
                    new=Node(data)
                    current.left=new
                    break;
            elif data > current.data:
                if current.right:
                    current=current.right
                else:
                    new=Node(data)
                    current.right=new
                    break;
            else:
                break

 b=binarytree()

Body:
This is part of my own implementation of BST. The ugly part of this problem is that you have to know the space that your children occupies before you can print out yourself. Because you can have very big numbers like 217348746327642386478832541267836128736..., but also small numbers like 10, so if you have a parent-children relationship between these two, then it can potentially overlap with your other child. Therefore, we need to first go through the children, make sure we get how much space they are having, then we use that information to construct ourself.

def __str__(self):
    h = self.getHeight()
    rowsStrs = ["" for i in range(2 * h - 1)]

    # return of helper is [leftLen, curLen, rightLen] where
    #   leftLen = children length of left side
    #   curLen = length of keyStr + length of "_" from both left side and right side
    #   rightLen = children length of right side.
    # But the point of helper is to construct rowsStrs so we get the representation
    # of this BST.
    def helper(node, curRow, curCol):
        if(not node): return [0, 0, 0]
        keyStr = str(node.key)
        keyStrLen = len(keyStr)
        l = helper(node.l, curRow + 2, curCol)
        rowsStrs[curRow] += (curCol -len(rowsStrs[curRow]) + l[0] + l[1] + 1) * " " + keyStr
        if(keyStrLen < l[2] and (node.r or (node.p and node.p.l == node))):
            rowsStrs[curRow] += (l[2] - keyStrLen) * "_"
        if(l[1]):
            rowsStrs[curRow + 1] += (len(rowsStrs[curRow + 2]) - len(rowsStrs[curRow + 1])) * " " + "/"
        r = helper(node.r, curRow + 2, len(rowsStrs[curRow]) + 1)
        rowsStrs[curRow] += r[0] * "_"
        if(r[1]):
            rowsStrs[curRow + 1] += (len(rowsStrs[curRow]) - len(rowsStrs[curRow + 1])) * " " + "\\"
        return [l[0] + l[1] + 1, max(l[2] - keyStrLen, 0) + keyStrLen + r[0], r[1] + r[2] + 1]

    helper(self.head, 0, 0)
    res = "\n".join(rowsStrs)
    #print("\n\n\nStart of BST:****************************************")
    #print(res)
    #print("End of BST:****************************************")
    #print("BST height: ", h, ", BST size: ", self.size)

    return res

Here's some examples of running this:

[26883404633, 10850198033, 89739221773, 65799970852, 6118714998, 31883432186, 84275473611, 25958013736, 92141734773, 91725885198, 131191476, 81453208197, 41559969292, 90704113213, 6886252839]
                                     26883404633___________________________________________
                                    /                                                      \
                       10850198033__                                                        89739221773___________________________
                      /             \                                                      /                                      \
           6118714998_               25958013736                 65799970852_______________                                        92141734773
          /           \                                         /                          \                                      /
 131191476             6886252839                   31883432186_                            84275473611                91725885198
                                                                \                          /                          /
                                                                 41559969292    81453208197                90704113213

Another example:

['rtqejfxpwmggfro', 'viwmdmpedzwvvxalr', 'mvvjmkdcdpcfb', 'ykqehfqbpcjfd', 'iuuujkmdcle', 'nzjbyuvlodahlpozxsc', 'wdjtqoygcgbt', 'aejduciizj', 'gzcllygjekujzcovv', 'naeivrsrfhzzfuirq', 'lwhcjbmcfmrsnwflezxx', 'gjdxphkpfmr', 'nartcxpqqongr', 'pzstcbohbrb', 'ykcvidwmouiuz']
                                                                                rtqejfxpwmggfro____________________
                                                                                /                                   \
                                              mvvjmkdcdpcfb_____________________________                                     viwmdmpedzwvvxalr_______________
                                             /                                          \                                                                    \
                         iuuujkmdcle_________                                            nzjbyuvlodahlpozxsc_                                                 ykqehfqbpcjfd
                        /                    \                                          /                    \                                               /
 aejduciizj_____________                      lwhcjbmcfmrsnwflezxx    naeivrsrfhzzfuirq_                      pzstcbohbrb                       wdjtqoygcgbt_
                        \                                                               \                                                                    \
                         gzcllygjekujzcovv                                               nartcxpqqongr                                                        ykcvidwmouiuz
                        /
             gjdxphkpfmr


问:
Why does my RandomForestClassifier train much more slowly when placed in a pipeline?
I am working with a large data set (1.7 million samples) and am trying to train a classifier. I've had good results with scikit-learn's RandomForestClassifier, and now I want to perform permutation feature analysis on my classifier with scikit-learn's permutation_importance method. To do so I've put my preprocessing into a ColumnTransformer, and placed it into a Pipeline along with my classifier.

I have been doing my preprocessing and training my classifier as separate steps, and it takes about 6 seconds to train an individual tree. However, when set up in a pipeline, the same classifier takes about 5 minutes to train a tree. I'm using a very large number of trees (and please, I'm not looking for feedback on that), and this is not really practical for me to work with.

I've dug around on the web extensively, but apparently can't find the right combination of search terms. Here is the relevant code:

```<code>preprocessing = ColumnTransformer(
    [
        ('binary', OneHotEncoder(drop='if_binary'),
         binary_category_cols),
        ('complete', OneHotEncoder(),
         complete_category_cols),
        ('inc_cat', OneHotEncoder(drop=[-9]*len(incomplete_category_cols)),
         incomplete_category_cols),
        ('inc_ord', OneHotEncoder(drop=[-9]*len(incomplete_ordinal_cols)),
         incomplete_ordinal_cols),
        ('cmp_ord', OrdinalEncoder(),
         complete_ordinal_cols)
    ], verbose=True, n_jobs=10
)

rf_clf = RandomForestClassifier(
    n_jobs=10, verbose=3,
    n_estimators=1000, criterion='entropy',
    max_depth=None, max_features='sqrt',
    max_samples=None, class_weight='balanced_subsample'
)

clf = Pipeline(
    [
        ('preprocess', preprocessing),
        ('classifier', rf_clf)
    ]
)

X_train, X_test, y_train, y_test = \
    train_test_split(features, targets, test_size=0.1)

clf.fit(X_train, y_train)
</code>```

'features' is a pandas DataFrame, and targets is a pandas Series. I can comment out the pipeline, fit and transform X_train with the ColumnTransformer, and then fit the RandomForestClassifier, and trees are built at about 50 times the speed.

I've tried feeding both configurations much smaller chunks of my data, and the difference is far less, so maybe there are limitations to Pipeline with respect to large data sets? If I set max_samples to 100,000, performance is manageable, but performance goes down substantially.

Any help would be much appreciated. I've been banging my head on my desk for about four hours on a stumbling block I had in no way anticipated.

答:
Given that you are setting n_jobs to 10, my guess is that you are trying to do multiprocessing. In that case, you might want to consider running your script within a __name__ == "__main__" block.

See: https://scikit-learn.org/stable/auto_examples/model_selection/grid_search_text_feature_extraction.html#sphx-glr-auto-examples-model-selection-grid-search-text-feature-extraction-py
For an example pipeline that does hyperparameter search, but that uses the Pipeline object you are using, and explicitly sets n_jobs.

Also: Python scikit learn n_jobs

At least in my case, it has allowed me to decrease runtime when doing hyperparameter search for RandomForestClassifier.

Body:
I am working with a large data set (1.7 million samples) and am trying to train a classifier. I've had good results with scikit-learn's RandomForestClassifier, and now I want to perform permutation feature analysis on my classifier with scikit-learn's permutation_importance method. To do so I've put my preprocessing into a ColumnTransformer, and placed it into a Pipeline along with my classifier.

I have been doing my preprocessing and training my classifier as separate steps, and it takes about 6 seconds to train an individual tree. However, when set up in a pipeline, the same classifier takes about 5 minutes to train a tree. I'm using a very large number of trees (and please, I'm not looking for feedback on that), and this is not really practical for me to work with.

I've dug around on the web extensively, but apparently can't find the right combination of search terms. Here is the relevant code:

preprocessing = ColumnTransformer(
    [
        ('binary', OneHotEncoder(drop='if_binary'),
         binary_category_cols),
        ('complete', OneHotEncoder(),
         complete_category_cols),
        ('inc_cat', OneHotEncoder(drop=[-9]*len(incomplete_category_cols)),
         incomplete_category_cols),
        ('inc_ord', OneHotEncoder(drop=[-9]*len(incomplete_ordinal_cols)),
         incomplete_ordinal_cols),
        ('cmp_ord', OrdinalEncoder(),
         complete_ordinal_cols)
    ], verbose=True, n_jobs=10
)

rf_clf = RandomForestClassifier(
    n_jobs=10, verbose=3,
    n_estimators=1000, criterion='entropy',
    max_depth=None, max_features='sqrt',
    max_samples=None, class_weight='balanced_subsample'
)

clf = Pipeline(
    [
        ('preprocess', preprocessing),
        ('classifier', rf_clf)
    ]
)

X_train, X_test, y_train, y_test = \
    train_test_split(features, targets, test_size=0.1)

clf.fit(X_train, y_train)

'features' is a pandas DataFrame, and targets is a pandas Series. I can comment out the pipeline, fit and transform X_train with the ColumnTransformer, and then fit the RandomForestClassifier, and trees are built at about 50 times the speed.

I've tried feeding both configurations much smaller chunks of my data, and the difference is far less, so maybe there are limitations to Pipeline with respect to large data sets? If I set max_samples to 100,000, performance is manageable, but performance goes down substantially.

Any help would be much appreciated. I've been banging my head on my desk for about four hours on a stumbling block I had in no way anticipated.


问:
Finding the combination of strings that occurs the most in given string
I have a combination of values that occur the most in given list of strings.

```<code>combination of values == value-value-value-value-value
</code>```

So combination needs to have 5 values, and values can repeat.

```<code>all_values = ["CONJ", "NUM", "ADV", "PRT", "ADP", "PRON", "VERB", "DET", "ADJ", "NOUN"]

all_strings = ["DET-VERB-PRON-PRON-VERB-VERB-ADP",
"DET-NOUN-DET-NOUN-CONJ-PRON-NOUN-NOUN-VERB-NOUN-NOUN",
"PRON-VERB-VERB-DET-NOUN-ADP-NUM-ADP-NOUN",
"NOUN-VERB-NOUN-VERB-ADV-ADJ-ADP-PRON-NOUN-VERB-ADV-ADV-VERB-ADV-VERB",
"ADJ-NOUN-NOUN-PRT-VERB-VERB-DET-NOUN-VERB-ADP-DET-NOUN-NOUN",
"NOUN-VERB-PRT-ADP-PRON-NOUN-DET-VERB-NUM-NOUN-ADP-ADV-VERB",
"NOUN-NOUN-ADP-DET-NOUN-ADP-NOUN-NOUN",
"NOU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ERB-DET-NOUN-ADP-DET-NOUN",
"ADV-ADP-VERB-ADV-PRON-VERB-VERB",
"NOUN-DET-NOUN-NOUN-NOUN-NOUN-VERB-ADJ-NOUN-ADP-DET-NOUN",
"PRON-VERB-NOUN-ADP-NOUN-ADP-NUM-NOUN-NOUN-PRT-VERB-NOUN",
"ADJ-NOUN-ADV-VERB-DET-VERB-VERB-ADJ-NOUN-ADP-PRON",
"NOUN-ADV-ADJ-ADV-ADJ-ADP-DET",
"NOUN-PRON-VERB-ADJ-VERB-ADV",
"VERB-PRT-DET-NOUN-VERB-ADP-DET-NOUN-VERB-ADV-NOUN-VERB-VERB-ADP-PRON",
"PRON-VERB-ADV-ADJ-NOUN-NOUN-NOUN-NOUN-NOUN-PRT-VERB-DET-NOUN",
"PRON-VERB-DET-VERB-VERB-DET-NOUN-NOUN-ADP-NOUN",
"NOUN-NOUN-NOUN-NOUN-NOUN-VERB-NUM-NUM",
"PRON-ADV-VERB-NUM-NOUN-ADV-ADJ-ADP-PRON-NOUN",
"NOUN-VERB-DET-NOUN-ADP-NOUN-ADV-NOUN-VERB-VERB-PRON-NOUN",
"NOUN-VERB-VERB-VERB-ADP-PRON",
"NOUN-VERB-DET-ADV-ADJ-NOUN",
"NOUN-ADV-VERB-PRON-DET-NOUN-NOUN-ADV",
"ADV-VERB-PRT-NUM-NOUN-NOUN-PRON-VERB-DET-NOUN-ADP-DET-NOUN",
"NOUN-VERB-ADV-NOUN-VERB-ADP-DET-NOUN-NOUN",
"PRON-VERB-ADJ-NOUN-DET-ADJ-NOUN",
"VERB-PRON-VERB-DET-ADJ-ADP-PRON",
"PRON-VERB-ADJ-NOUN-ADP-NOUN",
"NOUN-NOUN-NOUN-ADJ-VERB-NOUN-VERB-NOUN-ADP-PRON-ADV",
"NOUN-NOUN-VERB-NOUN-VERB-ADV-ADP-DET-ADJ-NOUN",
"NOUN-VERB-VERB-NOUN-NOUN-NOUN-ADV-VERB-PRON-PRT-VERB-NOUN"]
</code>```

So I need to find if the best combination is for example VERB-VERB-DET-NOUN-ADP or VERB-PRON-NOUN-ADV-VERB or any other.

I was thinking of finding all possible combinations of values from all_values list, but I'm sure that there is a faster way.
Ofc, full all_strings has more than 50k values.

答:
Here's a quick script that seems to do the job fairly quickly.

```<code>from collections import defaultdict as dd
import time

all_values = ["CONJ", "NUM", "ADV", "PRT", "ADP", "PRON", "VERB", "DET", "ADJ", "NOUN"]

all_strings = ["DET-VERB-PRON-PRON-VERB-VERB-ADP",
"DET-NOUN-DET-NOUN-CONJ-PRON-NOUN-NOUN-VERB-NOUN-NOUN",
"PRON-VERB-VERB-DET-NOUN-ADP-NUM-ADP-NOUN",
"NOUN-VERB-NOUN-VERB-ADV-ADJ-ADP-PRON-NOUN-VERB-ADV-ADV-VERB-ADV-VERB",
"ADJ-NOUN-NOUN-PRT-VERB-VERB-DET-NOUN-VERB-ADP-DET-NOUN-NOUN",
"NOUN-VERB-PRT-ADP-PRON-NOUN-DET-VERB-NUM-NOUN-ADP-ADV-VERB",
"NOUN-NOUN-ADP-DET-NOUN-ADP-NOUN-NOUN",
"NOUN-ADV-VERB-ADP-DET-NOUN-VERB-VERB-ADP-NUM-ADJ-NOUN",
"PRON-ADV-VERB-DET-NOUN-PRON-VERB-VERB-NOUN-ADP-DET-NOUN",
"PRON-VERB-ADP-PRON-ADP-PRON-ADJ-ADJ-NOUN",
"PRON-VERB-DET-NOUN-NOUN-VERB-NOUN-VERB-PRT-VERB-ADP-DET-NOUN",
"PRON-VERB-ADP-PRON-ADP-DET-NOUN-DET-VERB-PRON-VERB-VERB-NOUN-ADP-PRON",
"NOUN-VERB-ADP-DET-NOUN-ADJ-VERB-ADV-VERB-ADJ-ADP-PRON-VERB-NOUN",
"ADJ-NOUN-NOUN-ADV-ADJ-NOUN-VERB",
"NOUN-ADV-VERB-ADJ-PRON-ADJ-NOUN-VERB-VERB-NUM",
"NOUN-DET-NOUN-ADV-VERB-NOUN-VERB-ADV-DET-ADJ-NOUN",
"ADV-PRON-VERB-AD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-PRON-PRON-VERB-ADV-ADV",
"NOUN-VERB-VERB-PRT-VERB-NOUN-ADP-NOUN-NOUN-ADP-DET-NOUN-NOUN",
"PRON-PRON-VERB-VERB-DET-NOUN-CONJ-PRON-VERB-VERB-ADP-DET",
"PRON-VERB-NOUN-ADP-DET-NOUN-CONJ-NOUN-CONJ-NOUN-PRON-VERB-ADP-VERB-PRON",
"NOUN-ADJ-NOUN-VERB-ADV-ADP-DET",
"DET-NOUN-VERB-ADP-ADP-NUM-ADJ-NOUN",
"PRON-VERB-VERB-PRT-VERB-VERB-PRT-ADP-DET-NOUN-ADP-DET-NOUN",
"CONJ-DET-VERB-DET-NOUN-NOUN-ADP-NOUN-NOUN",
"PRON-VERB-ADJ-NOUN-VERB-NOUN-ADP-ADJ-NOUN-ADP-NOUN",
"ADV-PRON-VERB-VERB-DET-ADJ-NOUN-ADP-NOUN-PRT-VERB-PRON-NOUN",
"VERB-PRON-VERB-DET-NOUN-ADP-DET-NOUN-PRT-VERB-VERB",
"PRON-VERB-ADP-DET-NOUN-NOUN-VERB-ADJ",
"ADV-VERB-DET-NOUN-ADP-DET-NOUN",
"ADV-ADP-VERB-ADV-PRON-VERB-VERB",
"NOUN-DET-NOUN-NOUN-NOUN-NOUN-VERB-ADJ-NOUN-ADP-DET-NOUN",
"PRON-VERB-NOUN-ADP-NOUN-ADP-NUM-NOUN-NOUN-PRT-VERB-NOUN",
"ADJ-NOUN-ADV-VERB-DET-VERB-VERB-ADJ-NOUN-ADP-PRON",
"NOUN-ADV-ADJ-ADV-ADJ-ADP-DET",
"NOUN-PRON-VERB-ADJ-VERB-ADV",
"VERB-PRT-DET-NOUN-VERB-ADP-DET-NOUN-VERB-ADV-NOUN-VERB-VERB-ADP-PRON",
"PRON-VERB-ADV-ADJ-NOUN-NOUN-NOUN-NOUN-NOUN-PRT-VERB-DET-NOUN",
"PRON-VERB-DET-VERB-VERB-DET-NOUN-NOUN-ADP-NOUN",
"NOUN-NOUN-NOUN-NOUN-NOUN-VERB-NUM-NUM",
"PRON-ADV-VERB-NUM-NOUN-ADV-ADJ-ADP-PRON-NOUN",
"NOUN-VERB-DET-NOUN-ADP-NOUN-ADV-NOUN-VERB-VERB-PRON-NOUN",
"NOUN-VERB-VERB-VERB-ADP-PRON",
"NOUN-VERB-DET-ADV-ADJ-NOUN",
"NOUN-ADV-VERB-PRON-DET-NOUN-NOUN-ADV",
"ADV-VERB-PRT-NUM-NOUN-NOUN-PRON-VERB-DET-NOUN-ADP-DET-NOUN",
"NOUN-VERB-ADV-NOUN-VERB-ADP-DET-NOUN-NOUN",
"PRON-VERB-ADJ-NOUN-DET-ADJ-NOUN",
"VERB-PRON-VERB-DET-ADJ-ADP-PRON",
"PRON-VERB-ADJ-NOUN-ADP-NOUN",
"NOUN-NOUN-NOUN-ADJ-VERB-NOUN-VERB-NOUN-ADP-PRON-ADV",
"NOUN-NOUN-VERB-NOUN-VERB-ADV-ADP-DET-ADJ-NOUN",
"NOUN-VERB-VERB-NOUN-NOUN-NOUN-ADV-VERB-PRON-PRT-VERB-NOUN"]

start = time.time()

string_mat = [s.split('-') for s in all_strings]
freq = dd(int)
for row in string_mat:
    for i in range(len(row) - 4):
        freq[tuple(row[i:i+5])]+=1
max_freq,pattern = max((f,p) for p,f in freq.items())

print("Best pattern:",'-'.join(pattern))
print("frequency:",max_freq)
print("Computation time: {:.3} seconds".format(time.time()-start))
</code>```

Result:

```<code>Best pattern: VERB-ADP-DET-NOUN-NOUN
frequency: 4
Computation time: 0.00149 seconds
</code>```

Bonus: to get a list of all patterns and their frequency in descending order, do the following (after the above script).

```<code>for f,p in sorted([(f,p) for (p,f) in freq.items()],reverse = True):
        print('-'.join(p),f': {f} time(s)')
</code>```

Here are the top 5:

```<code>VERB-ADP-DET-NOUN-NOUN : 4 time(s)
PRON-VERB-DET-NOUN-ADP : 4 time(s)
NOUN-VERB-ADP-DET-NOUN : 4 time(s)
DET-NOUN-ADP-DET-NOUN : 4 time(s)
VERB-DET-NOUN-ADP-NOUN : 3 time(s)
</code>```

Implementation using the collections.Counter object:

```<code>start = time.time()
string_mat = [s.split('-') for s in all_strings]
freq = Counter([tuple(row[i:i+5]) for row in string_mat for i in range(len(row)-4)])

print('5 most common:')
for p,f in freq.most_common(5):
    print('{}: {}'.format('-'.join(p),f))
print("Computation time: {:.3} seconds".format(time.time()-start))
</code>```

Result:

```<code>5 most common:
NOUN-VERB-ADP-DET-NOUN: 4
VERB-ADP-DET-NOUN-NOUN: 4
PRON-VERB-DET-NOUN-ADP: 4
DET-NOUN-ADP-DET-NOUN: 4
VERB-DET-NOUN-ADP-NOUN: 3
Computation time: 0.00294 seconds
</code>```

Body:
I have a combination of values that occur the most in given list of strings.

combination of values == value-value-value-value-value

So combination needs to have 5 values, and values can repeat.

all_values = ["CONJ", "NUM", "ADV", "PRT", "ADP", "PRON", "VERB", "DET", "ADJ", "NOUN"]

all_strings = ["DET-VERB-PRON-PRON-VERB-VERB-ADP",
"DET-NOUN-DET-NOUN-CONJ-PRON-NOUN-NOUN-VERB-NOUN-NOUN",
"PRON-VERB-VERB-DET-NOUN-ADP-NUM-ADP-NOUN",
"NOUN-VERB-NOUN-VERB-ADV-ADJ-ADP-PRON-NOUN-VERB-ADV-ADV-VERB-ADV-VERB",
"ADJ-NOUN-NOUN-PRT-VERB-VERB-DET-NOUN-VERB-ADP-DET-NOUN-NOUN",
"NOUN-VERB-PRT-ADP-PRON-NOUN-DET-VERB-NUM-NOUN-ADP-ADV-VERB",
"NOUN-NOUN-ADP-DET-NOUN-ADP-NOUN-NOUN",
"NOUN-ADV-VERB-ADP-DET-NOUN-VERB-VERB-ADP-NUM-ADJ-NOUN",
"PRON-ADV-VERB-DET-NOUN-PRON-VERB-VERB-NOUN-ADP-DET-NOUN",
"PRON-VERB-ADP-PRON-ADP-PRON-ADJ-ADJ-NOUN",
"PRON-VERB-DET-NOUN-NOUN-VERB-NOUN-VERB-PRT-VERB-ADP-DET-NOUN",
"PRON-VERB-ADP-PRON-ADP-DET-NOUN-D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-ADV-ADJ-ADP-DET",
"NOUN-PRON-VERB-ADJ-VERB-ADV",
"VERB-PRT-DET-NOUN-VERB-ADP-DET-NOUN-VERB-ADV-NOUN-VERB-VERB-ADP-PRON",
"PRON-VERB-ADV-ADJ-NOUN-NOUN-NOUN-NOUN-NOUN-PRT-VERB-DET-NOUN",
"PRON-VERB-DET-VERB-VERB-DET-NOUN-NOUN-ADP-NOUN",
"NOUN-NOUN-NOUN-NOUN-NOUN-VERB-NUM-NUM",
"PRON-ADV-VERB-NUM-NOUN-ADV-ADJ-ADP-PRON-NOUN",
"NOUN-VERB-DET-NOUN-ADP-NOUN-ADV-NOUN-VERB-VERB-PRON-NOUN",
"NOUN-VERB-VERB-VERB-ADP-PRON",
"NOUN-VERB-DET-ADV-ADJ-NOUN",
"NOUN-ADV-VERB-PRON-DET-NOUN-NOUN-ADV",
"ADV-VERB-PRT-NUM-NOUN-NOUN-PRON-VERB-DET-NOUN-ADP-DET-NOUN",
"NOUN-VERB-ADV-NOUN-VERB-ADP-DET-NOUN-NOUN",
"PRON-VERB-ADJ-NOUN-DET-ADJ-NOUN",
"VERB-PRON-VERB-DET-ADJ-ADP-PRON",
"PRON-VERB-ADJ-NOUN-ADP-NOUN",
"NOUN-NOUN-NOUN-ADJ-VERB-NOUN-VERB-NOUN-ADP-PRON-ADV",
"NOUN-NOUN-VERB-NOUN-VERB-ADV-ADP-DET-ADJ-NOUN",
"NOUN-VERB-VERB-NOUN-NOUN-NOUN-ADV-VERB-PRON-PRT-VERB-NOUN"]

So I need to find if the best combination is for example VERB-VERB-DET-NOUN-ADP or VERB-PRON-NOUN-ADV-VERB or any other.

I was thinking of finding all possible combinations of values from all_values list, but I'm sure that there is a faster way.
Ofc, full all_strings has more than 50k values.

Body:
Here's a quick script that seems to do the job fairly quickly.

from collections import defaultdict as dd
import time

all_values = ["CONJ", "NUM", "ADV", "PRT", "ADP", "PRON", "VERB", "DET", "ADJ", "NOUN"]

all_strings = ["DET-VERB-PRON-PRON-VER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ERB-DET-NOUN-ADP-DET-NOUN",
"NOUN-VERB-ADV-NOUN-VERB-ADP-DET-NOUN-NOUN",
"PRON-VERB-ADJ-NOUN-DET-ADJ-NOUN",
"VERB-PRON-VERB-DET-ADJ-ADP-PRON",
"PRON-VERB-ADJ-NOUN-ADP-NOUN",
"NOUN-NOUN-NOUN-ADJ-VERB-NOUN-VERB-NOUN-ADP-PRON-ADV",
"NOUN-NOUN-VERB-NOUN-VERB-ADV-ADP-DET-ADJ-NOUN",
"NOUN-VERB-VERB-NOUN-NOUN-NOUN-ADV-VERB-PRON-PRT-VERB-NOUN"]

start = time.time()

string_mat = [s.split('-') for s in all_strings]
freq = dd(int)
for row in string_mat:
    for i in range(len(row) - 4):
        freq[tuple(row[i:i+5])]+=1
max_freq,pattern = max((f,p) for p,f in freq.items())

print("Best pattern:",'-'.join(pattern))
print("frequency:",max_freq)
print("Computation time: {:.3} seconds".format(time.time()-start))

Result:

Best pattern: VERB-ADP-DET-NOUN-NOUN
frequency: 4
Computation time: 0.00149 seconds

Bonus: to get a list of all patterns and their frequency in descending order, do the following (after the above script).

for f,p in sorted([(f,p) for (p,f) in freq.items()],reverse = True):
        print('-'.join(p),f': {f} time(s)')

Here are the top 5:

VERB-ADP-DET-NOUN-NOUN : 4 time(s)
PRON-VERB-DET-NOUN-ADP : 4 time(s)
NOUN-VERB-ADP-DET-NOUN : 4 time(s)
DET-NOUN-ADP-DET-NOUN : 4 time(s)
VERB-DET-NOUN-ADP-NOUN : 3 time(s)

Implementation using the collections.Counter object:

start = time.time()
string_mat = [s.split('-') for s in all_strings]
freq = Counter([tuple(row[i:i+5]) for row in string_mat for i in range(len(row)-4)])

print('5 most common:')
for p,f in freq.most_common(5):
    print('{}: {}'.format('-'.join(p),f))
print("Computation time: {:.3} seconds".format(time.time()-start))

Result:

5 most common:
NOUN-VERB-ADP-DET-NOUN: 4
VERB-ADP-DET-NOUN-NOUN: 4
PRON-VERB-DET-NOUN-ADP: 4
DET-NOUN-ADP-DET-NOUN: 4
VERB-DET-NOUN-ADP-NOUN: 3
Computation time: 0.00294 seconds


问:
Constraints run successfully in simulator but get errors on device
I have an app that runs without any build error or warnings.  The app runs successfully on simulator (no console error) but when I run on my real device I get the following console error:

```<code>2022-02-07 15:40:30.507950-0400 SalesTax[11923:142076] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x6000037618b0 UITableView:0x15c871c00.width == 186   (active)>",
    "<NSLayoutConstraint:0x600003762850 H:|-(0)-[UITableView:0x15c871c00]   (active, names: '|':UIStackView:0x15b62cc90 )>",
    "<NSLayoutConstraint:0x6000037637a0 H:|-(20)-[UITextField:0x15c839600]   (active, names: '|':UIView:0x15b6138a0 )>",
    "<NSLayoutConstraint:0x6000037637f0 UITextField:0x15c839600.leading == UIButton:0x15b6245f0'Country California'.leading   (active)>",
    "<NSLayoutConstraint:0x600003763ac0 UIStackView:0x15b62cc90.leading == UIButton:0x15b6245f0'Country California'.leading   (active)>",
    "<NSLayoutConstraint:0x600003763b10 H:[UIStackView:0x15b62cc90]-(18)-|   (active, names: '|':UIView:0x15b6138a0 )>",
    "<NSLayoutConstraint:0x60000376c0a0 UIView:0x15b6138a0.width == UIScrollView:0x15c85d200.width   (active)>",
    "<NSLayoutConstraint:0x60000376c410 UILayoutGuide:0x600002d13b80'UIViewSafeAreaLayoutGuide'.trailing == UIScrollView:0x15c85d200.trailing   (active)>",
    "<NSLayoutConstraint:0x60000376c460 UIScrollView:0x15c85d200.leading == UILayoutGuide:0x600002d13b80'UIViewSafeAreaLayoutGuide'.leading   (active)>",
    "<NSLayoutConstraint:0x600003715680 'UISV-canvas-connection' H:[UITableView:0x15c871c00]-(0)-|   (active, names: '|':UIStackView:0x15b62cc90 )>",
    "<NSLayoutConstraint:0x600003768c30 'UIView-Encapsulated-Layout-Width' UIView:0x15b613dd0.width == 428   (active)>",
    "<NSLayoutConstraint:0x60000376c320 'UIViewSafeAreaLayoutGuide-left' H:|-(0)-[UILayoutGuide:0x600002d13b80'UIViewSafeAreaLayoutGuide'](LTR)   (active, names: '|':UIView:0x15b613dd0 )>",
    "<NSLayoutConstraint:0x60000376c3c0 'UIViewSafeAreaLayoutGuide-right' H:[UILayoutGuide:0x600002d13b80'UIViewSafeAreaLayoutGuide']-(0)-|(LTR)   (active, names: '|':UIView:0x15b613dd0 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x6000037618b0 UITableView:0x15c871c00.width == 186   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
Optional(18.0)
Message from debugger: Terminated due to signal 9
</code>```

Layout is the same on simulator and device, but a dropdown menu title doesn't show its title on my iPhone device.  I know that is a constraint problem, but I can't identify the view object constraints that cause the problem.  Please consider that it's my first time using Xcode and Swift.

答:
Solution:

On size inspector, horizontal width of some of my labels constraints, I changed the priority from 1000 to 750.  That removed the error messages.

Body:
I have an app that runs without any build error or warnings.  The app runs successfully on simulator (no console error) but when I run on my real device I get the following console error:

2022-02-07 15:40:30.507950-0400 SalesTax[11923:142076] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x6000037618b0 UITableView:0x15c871c00.width == 186   (active)>",
    "<NSLayoutConstraint:0x600003762850 H:|-(0)-[UITableView:0x15c871c00]   (active, names: '|':UIStackView:0x15b62cc90 )>",
    "<NSLayoutConstraint:0x6000037637a0 H:|-(20)-[UITextField:0x15c839600]   (active, names: '|':UIView:0x15b6138a0 )>",
    "<NSLayoutConstraint:0x6000037637f0 UITextField:0x15c839600.leading == UIButton:0x15b6245f0'Country California'.leading   (active)>",
    "<NSLayoutConstraint:0x600003763ac0 UIStackView:0x15b62cc90.leading == UIButton:0x15b6245f0'Country California'.leading   (active)>",
    "<NSLayoutConstraint:0x600003763b10 H:[UIStackView:0x15b62cc90]-(18)-|   (active, names: '|':UIView:0x15b6138a0 )>",
    "<NSLayoutConstraint:0x60000376c0a0 UIView:0x15b6138a0.width == UIScrollView:0x15c85d200.width   (active)>",
    "<NSLayoutConstraint:0x60000376c410 UILayoutGuide:0x600002d13b80'UIViewSafeAreaLayoutGuide'.trailing == UIScrollView:0x15c85d200.trailing   (active)>",
    "<NSLayoutConstraint:0x60000376c460 UIScrollView:0x15c85d200.leading == UILayoutGuide:0x600002d13b80'UIViewSafeAreaLayoutGuide'.leading   (active)>",
    "<NSLayoutConstraint:0x600003715680 'UISV-canvas-connection' H:[UITableView:0x15c871c00]-(0)-|   (active, names: '|':UIStackView:0x15b62cc90 )>",
    "<NSLayoutConstraint:0x600003768c30 'UIView-Encapsulated-Layout-Width' UIView:0x15b613dd0.width == 428   (active)>",
    "<NSLayoutConstraint:0x60000376c320 'UIViewSafeAreaLayoutGuide-left' H:|-(0)-[UILayoutGuide:0x600002d13b80'UIViewSafeAreaLayoutGuide'](LTR)   (active, names: '|':UIView:0x15b613dd0 )>",
    "<NSLayoutConstraint:0x60000376c3c0 'UIViewSafeAreaLayoutGuide-right' H:[UILayoutGuide:0x600002d13b80'UIViewSafeAreaLayoutGuide']-(0)-|(LTR)   (active, names: '|':UIView:0x15b613dd0 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x6000037618b0 UITableView:0x15c871c00.width == 186   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
Optional(18.0)
Message from debugger: Terminated due to signal 9

Layout is the same on simulator and device, but a dropdown menu title doesn't show its title on my iPhone device.  I know that is a constraint problem, but I can't identify the view object constraints that cause the problem.  Please consider that it's my first time using Xcode and Swift.


问:
from ggplotly, open all new hyperlinks in the same new window/tab
I am using the following example code where click on the point opens a link:

```<code>data(mtcars)
mtcars$urlD <- paste0("http://google.com/search?q=", gsub(" ", "+", rownames(mtcars)))

p <- ggplot(data=mtcars, aes(x=wt, y=mpg, color=factor(carb), customdata=urlD)) + geom_point()
pp <- ggplotly(p)
ppp <- htmlwidgets::onRender(pp, "
     function(el, x) {
       el.on('plotly_click', function(d) {
         var url = d.points[0].customdata;
         window.open(url);
       });
     }
  ")
</code>```

It works fine but every new click opens new window/tab. Is there any way to make it use the same window? (I mean not the window with the plot but the window where the first link was opened) In usual javascript, I would use the name parameter of window.open(), like this: window.open(url, 'MyTargetWindow'); - but it doesn't help here. Any workarounds?

答: You must be using Rstudio. window.open(url, 'MyTargetWindow') works in browser but not in Rstudio. If you click the "show in new window" button and open the plot in your browser, it works. The reason is window name is recognized in the same browser, but when you open a new browser (from Rstudio Viewer to the actual browser in this case), the name info is not passed. I am not aware of a solution to solve this cross-browser issue.

Body:
I am using the following example code where click on the point opens a link:

data(mtcars)
mtcars$urlD <- paste0("http://google.com/search?q=", gsub(" ", "+", rownames(mtcars)))

p <- ggplot(data=mtcars, aes(x=wt, y=mpg, color=factor(carb), customdata=urlD)) + geom_point()
pp <- ggplotly(p)
ppp <- htmlwidgets::onRender(pp, "
     function(el, x) {
       el.on('plotly_click', function(d) {
         var url = d.points[0].customdata;
         window.open(url);
       });
     }
  ")

It works fine but every new click opens new window/tab. Is there any way to make it use the same window? (I mean not the window with the plot but the window where the first link was opened) In usual javascript, I would use the name parameter of window.open(), like this: window.open(url, 'MyTargetWindow'); - but it doesn't help here. Any workarounds?


问:
SSL certificate configuration on a NameVirtualHost based webhost
We use a linux based host to host several webshops. All use HTTP to deliver the shops. Now, one customer asked to get a certificate. I have the certificate at hand. I created a second IP address for the first ethernet device. I have created a second section in the Apache configuration that listens on the new IP address on port 443. And then it hit me.

How the heck does the browser know where to go to fetch the website via HTTPS?

There's only one A record in the DNS entry, which points to IP address A. But the webserver listens (and needs to listen) on IP address B on port 443 for connections to this shop.

How and where is the split between IP A:80 and IP B:443 configured, so that the host can know that he needs to talk to IP B when using HTTPS? Or is this some mechanism that is transparent for the host, like IP forwarding?

答:
How and where is the split between IP A:80 and IP B:443 configured, so that the host can know that he needs to talk to IP B when using HTTPS? Or is this some mechanism that is transparent for the host, like IP forwarding?

It isn't. You have to use the same IP for both ports.


问:
How can I find the MAC address of a client on the same network, using Python-Flask?
I am looking for a python way grab the client's MAC address. All requests are over the same network. I am looking for something similar to perform arp -n <Client_IP> on the router.

答:
You can get the IP address of a client using flask's request.remote_add, then you can search for its MAC address in the ARP table of your network interface. The code below worked for me:

```<code>from flask import Flask, request
from python_arptable import get_arp_table

app = Flask(__name__)

def mac_from_ip(ip):
    arp_table = get_arp_table()

    for entry in arp_table:
        if entry['IP address'] == ip:
            return entry['HW address']
    return None

@app.route('/')
def get_client_mac():
    client_ip = request.remote_addr
    client_mac = mac_for_ip(client_ip)
    return client_mac
</code>```

Body:
You can get the IP address of a client using flask's request.remote_add, then you can search for its MAC address in the ARP table of your network interface. The code below worked for me:

from flask import Flask, request
from python_arptable import get_arp_table

app = Flask(__name__)

def mac_from_ip(ip):
    arp_table = get_arp_table()

    for entry in arp_table:
        if entry['IP address'] == ip:
            return entry['HW address']
    return None

@app.route('/')
def get_client_mac():
    client_ip = request.remote_addr
    client_mac = mac_for_ip(client_ip)
    return client_mac


问:
Replace NULL with "N/A"
I'm trying to use the Oracle NVL() function to replace NULL with "N/A":

```<code>SELECT ID AS "Record ID",
    ( SELECT NVL( COMMENT , "N/A") FROM CHECKBOX WHERE ( B1_CHECKBOX_DESC = 'Solar KW' ) AND ( RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 ) ) AS "Solar",
    ( SELECT NVL( COMMENT, "N/A" ) FROM CHECKBOX WHERE ( B1_CHECKBOX_DESC = 'Code Edition' ) AND ( RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 ) ) AS "Coder"
FROM RECORDS
</code>```

Note: I'm trying to replace NULL with "N/A," not an empty string, so it should work. However, in the result set, I'm still getting NULL values instead of "N/A". What am I doing wrong?

答:
Just wrong place for NVL(), not that your subqueries may not return rows, so use NVL on subquery:

```<code>SELECT ID AS "Record ID",
   NVL(
    ( SELECT "COMMENT" FROM CHECKBOX WHERE B1_CHECKBOX_DESC = 'Solar KW'
      AND RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 )
    , 'N/A')  AS "Solar",
   NVL(
    ( SELECT "COMMENT" FROM CHECKBOX WHERE B1_CHECKBOX_DESC = 'Code Edition'
      AND RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 )
    , 'N/A' ) AS "Coder"
FROM RECORDS
</code>```

But probably it would be better to use lateral or outer apply here:

```<code>SELECT
   ID AS "Record ID",
   c.*
FROM RECORDS
     outer apply(
        SELECT
           nvl(solar,'N/A') as solar,
           nvl(coder,'N/A') as coder
        FROM (select *
              from CHECKBOX
              WHERE B1_CHECKBOX_DESC in ('Solar KW' , 'Code Edition')
               AND RECORDS.ID1 = CHECKBOX.ID1
               AND RECORDS.ID3 = CHECKBOX.ID3
             )
        pivot(
          max("COMMENT")
          for B1_CHECKBOX_DESC in (
               'Solar KW' as Solar,
               'Code Edition' as Coder
              )
        )
     ) c
</code>```

Full example with test data:

DBFiddle

```<code>with
 records(id,id1,id3) as (
    select 1,1,1 from dual union all
    select 2,2,2 from dual
)
,CHECKBOX("COMMENT",id1,id3,B1_CHECKBOX_DESC) as (
    select 'comment1-1',1,1, 'Solar KW' from dual union all
    select 'comment1-2',1,1, 'Code Edition' from dual union all
    select 'comment2-1',2,2, 'Solar KW' from dual
)
SELECT
   ID AS "Record ID",
   c.*
FROM RECORDS
     outer apply(
        SELECT
           nvl(solar,'N/A') as solar,
           nvl(coder,'N/A') as coder
        FROM (select *
              from CHECKBOX
              WHERE B1_CHECKBOX_DESC in ('Solar KW' , 'Code Edition')
               AND RECORDS.ID1 = CHECKBOX.ID1
               AND RECORDS.ID3 = CHECKBOX.ID3
             )
        pivot(
          max("COMMENT")
          for B1_CHECKBOX_DESC in (
               'Solar KW' as Solar,
               'Code Edition' as Coder
              )
        )
     ) c;
</code>```

Results:

```<code> Record ID SOLAR      CODER
---------- ---------- ----------
         1 comment1-1 comment1-2
         2 comment2-1 N/A
</code>```

Title: Replace NULL with "N/A"

Body:
I'm trying to use the Oracle NVL() function to replace NULL with "N/A":

SELECT ID AS "Record ID",
    ( SELECT NVL( COMMENT , "N/A") FROM CHECKBOX WHERE ( B1_CHECKBOX_DESC = 'Solar KW' ) AND ( RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 ) ) AS "Solar",
    ( SELECT NVL( COMMENT, "N/A" ) FROM CHECKBOX WHERE ( B1_CHECKBOX_DESC = 'Code Edition' ) AND ( RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 ) ) AS "Coder"
FROM RECORDS

Note: I'm trying to replace NULL with "N/A," not an empty string, so it should work. However, in the result set, I'm still getting NULL values instead of "N/A". What am I doing wrong?

Body:
Just wrong place for NVL(), not that your subqueries may not return rows, so use NVL on subquery:

SELECT ID AS "Record ID",
   NVL(
    ( SELECT "COMMENT" FROM CHECKBOX WHERE B1_CHECKBOX_DESC = 'Solar KW'
      AND RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 )
    , 'N/A')  AS "Solar",
   NVL(
    ( SELECT "COMMENT" FROM CHECKBOX WHERE B1_CHECKBOX_DESC = 'Code Edition'
      AND RECORDS.ID1 = CHECKBOX.ID1 AND RECORDS.ID3 = CHECKBOX.ID3 )
    , 'N/A' ) AS "Coder"
FROM RECORDS

But probably it would be better to use lateral or outer apply here:

SELECT
   ID AS "Record ID",
   c.*
FROM RECORDS
     outer apply(
        SELECT
           nvl(solar,'N/A') as solar,
           nvl(coder,'N/A') as coder
        FROM (select *
              from CHECKBOX
              WHERE B1_CHECKBOX_DESC in ('Solar KW' , 'Code Edition')
               AND RECORDS.ID1 = CHECKBOX.ID1
               AND RECORDS.ID3 = CHECKBOX.ID3
             )
        pivot(
          max("COMMENT")
          for B1_CHECKBOX_DESC in (
               'Solar KW' as Solar,
               'Code Edition' as Coder
              )
        )
     ) c

Full example with test data:

DBFiddle

with
 records(id,id1,id3) as (
    select 1,1,1 from dual union all
    select 2,2,2 from dual
)
,CHECKBOX("COMMENT",id1,id3,B1_CHECKBOX_DESC) as (
    select 'comment1-1',1,1, 'Solar KW' from dual union all
    select 'comment1-2',1,1, 'Code Edition' from dual union all
    select 'comment2-1',2,2, 'Solar KW' from dual
)
SELECT
   ID AS "Record ID",
   c.*
FROM RECORDS
     outer apply(
        SELECT
           nvl(solar,'N/A') as solar,
           nvl(coder,'N/A') as coder
        FROM (select *
              from CHECKBOX
              WHERE B1_CHECKBOX_DESC in ('Solar KW' , 'Code Edition')
               AND RECORDS.ID1 = CHECKBOX.ID1
               AND RECORDS.ID3 = CHECKBOX.ID3
             )
        pivot(
          max("COMMENT")
          for B1_CHECKBOX_DESC in (
               'Solar KW' as Solar,
               'Code Edition' as Coder
              )
        )
     ) c;

Results:

 Record ID SOLAR      CODER
---------- ---------- ----------
         1 comment1-1 comment1-2
         2 comment2-1 N/A


问:
how to set json with comment in vscode?
I often use Vs code to open json files. sometimes there're some comments in my json files. in this case,there will be a lot of warnings.

So I click below button to change the format to "json with comment (jsonc)"

but when I open a JSON file next time, it will by default switch to JSON format (without comment)

How can I make 'jsonc' the default format of json file? so that I do not need to change it every time.

Thanks

答:
You can set a file association between json files and jsonc language formatting.

In VS Code open Settings in JSON view by using the Command Pallet (Cmd + Shift + P) and enter Preferences: Open Settings (JSON). Next, add the following (or append to the existing files.associations object if it already exists):

```<code>"files.associations": {
    "*.json": "jsonc"
}
</code>```

Title: how to set json with comment in vscode?

Body:
You can set a file association between json files and jsonc language formatting.

In VS Code open Settings in JSON view by using the Command Pallet (Cmd + Shift + P) and enter Preferences: Open Settings (JSON). Next, add the following (or append to the existing files.associations object if it already exists):

"files.associations": {
    "*.json": "jsonc"
}


问:
Is there a way to import images from a Wiki table into a spreadsheet?
I'm trying to import a MediaWiki table from here: https://hotwheels.fandom.com/wiki/List_of_2021_Hot_Wheels

I want to be able to also pull the images, but when I use ImportHtml in sheets (like so: =ImportHtml("https://hotwheels.fandom.com/wiki/List_of_2021_Hot_Wheels", "table", 1)), the "photos" column is just blank:

Is there anything I can do here? I would be alright if, at the very least, I could pull the link to the photo to put there if I can't pull the photos themselves.

答:
use:

```<code>=INDEX(IMAGE(QUERY(IMPORTXML(A1, "//a/@href"),
 "where Col1 contains 'images'")))
</code>```

to get whole table use:

```<code>=INDEX({SUBSTITUTE(ARRAY_CONSTRAIN(
 IMPORTHTML(A1, "table", 1),  9^9, 4), "*", ),
 ARRAY_CONSTRAIN({"Photo"; IMAGE(QUERY(
 IMPORTXML(A1, "//a/@href"),
 "where Col1 contains 'images'"))}, 448, 1)})
</code>```

Body:
use:

=INDEX(IMAGE(QUERY(IMPORTXML(A1, "//a/@href"),
 "where Col1 contains 'images'")))

to get whole table use:

=INDEX({SUBSTITUTE(ARRAY_CONSTRAIN(
 IMPORTHTML(A1, "table", 1),  9^9, 4), "*", ),
 ARRAY_CONSTRAIN({"Photo"; IMAGE(QUERY(
 IMPORTXML(A1, "//a/@href"),
 "where Col1 contains 'images'"))}, 448, 1)})


问:
Problem with a C# csproj log file
I wish to write to output file like txt a log of done C# instruction during debuging my csproj. Is there any buildin function in VS2010 or any idea how to do this.</p>

答:
To write info to your output window while debugging just use Debug

```<code>Debug.WriteLine("Message Here");
</code>```

You might also want to look at TraceListener. You can implement a custom one if needed. There are also several popular logging frameworks available for .NET, for example NLog and log4net

Here's a quick sample of writing trace info to a text file

```<code>using (var myFile = File.Create("TestFile.txt"))
{
    var myTextListener = new TextWriterTraceListener(myFile);
    Trace.Listeners.Add(myTextListener);
    Trace.Write("Test output ");
}
</code>```

Title: Problem with a C# csproj log file

Body:
To write info to your output window while debugging just use Debug

Debug.WriteLine("Message Here");

You might also want to look at TraceListener. You can implement a custom one if needed. There are also several popular logging frameworks available for .NET, for example NLog and log4net

Here's a quick sample of writing trace info to a text file

using (var myFile = File.Create("TestFile.txt"))
{
    var myTextListener = new TextWriterTraceListener(myFile);
    Trace.Listeners.Add(myTextListener);
    Trace.Write("Test output ");
}


问:
Using Parallel loop to give each datarow a score in C#
I have a method which iterates through each DataRow of a DataTable then sets the final "Score" column to be a result.  I am trying to figure out how to do this quicker than simply evaluating in serial.  I am new to trying parallel loops and don't know if I am taking the wrong approach.

Simplified existing code:

```<code>foreach (DataRow dr in DateOptions.Rows)
{
double score = evalRow(dr);
 dr["score"] = score;
}
</code>```

Using the following seems to result in error- as I am trying to modify the DataTable.

```<code>Parallel.ForEach(DateOptions.AsEnumerable(), dr =>
{
    double score = evalRow(dr);
     dr["score"] = score;
});
</code>```

Is there some way I am not thinking of to extract the result then apply the value to the appropriate column?

答:
It probably depends largely on whether evalRow does anything that's not thread-safe. If the only problem is coming from modifying the DataTable, then you can likely fix it by applying Command-Query Separation: use parallel processing to figure out what to do, then drop back to serial processing to actually do it.

```<code>var rowsWithScores = DateOptions.AsEnumerable().AsParallel()
    .Select(dr => new {dr, score = evalRow(dr)})
    .ToList();
foreach(var rowWithScore in rowsWithScores)
{
    rowWithScore.dr["score"] = rowWithScore.score;
}
</code>```

That said, in my experience problems like this are better solved with algorithmic fixes rather than just trying to throw parallel processing at it. If you're only dealing with thousands of items, and this is taking hours to complete, that tells me you're probably either using an algorithm with high complexity (which can probably be fixed using data structures), or doing a lot of I/O (which might lend itself to concurrent asynchronous operations). In other words, there's probably another approach that will get you orders of magnitude better performance.

Body:
I have a method which iterates through each DataRow of a DataTable then sets the final "Score" column to be a result.  I am trying to figure out how to do this quicker than simply evaluating in serial.  I am new to trying parallel loops and don't know if I am taking the wrong approach.

Simplified existing code:

foreach (DataRow dr in DateOptions.Rows)
{
double score = evalRow(dr);
 dr["score"] = score;
}

Using the following seems to result in error- as I am trying to modify the DataTable.

Parallel.ForEach(DateOptions.AsEnumerable(), dr =>
{
    double score = evalRow(dr);
     dr["score"] = score;
});

Is there some way I am not thinking of to extract the result then apply the value to the appropriate column?

Body:
It probably depends largely on whether evalRow does anything that's not thread-safe. If the only problem is coming from modifying the DataTable, then you can likely fix it by applying Command-Query Separation: use parallel processing to figure out what to do, then drop back to serial processing to actually do it.

var rowsWithScores = DateOptions.AsEnumerable().AsParallel()
    .Select(dr => new {dr, score = evalRow(dr)})
    .ToList();
foreach(var rowWithScore in rowsWithScores)
{
    rowWithScore.dr["score"] = rowWithScore.score;
}

That said, in my experience problems like this are better solved with algorithmic fixes rather than just trying to throw parallel processing at it. If you're only dealing with thousands of items, and this is taking hours to complete, that tells me you're probably either using an algorithm with high complexity (which can probably be fixed using data structures), or doing a lot of I/O (which might lend itself to concurrent asynchronous operations). In other words, there's probably another approach that will get you orders of magnitude better performance.


问:
Searching a string
OK Ive been able to get the following to partially work

```<code>var Global_Wound_array =[{"WoundNumber":1,"BodySide":"Front","BodyPart":"Nose"},{"WoundNumber":2,"BodySide":"Left","BodyPart":"Head"},{"WoundNumber":3,"BodySide":"Back","BodyPart":"Ear"}]
var Global_Wound_Counter = 1
</code>```

I can get the page to loop through and display the individual wounds but I need a way to say at a particular page one of the values eg on WoundNumber 2 BodyPart has changed and updated the string without affecting the rest of it.

```<code>page9200.setEventHandler("pageFinishing", function () {
//getSelectedButtonLabel this is ok - specific on the system
let Q1 = Q3_WoundNumber.getValue();
let Q2 = Q1_BodySide.getSelectedButtonLabel();
let Q3 = Q2_BodyPart.getSelectedButtonLabel();
for (var i = 0; i < Global_Wound_array.length; i++) {
if (i+1 == Q1){
//create new temp variable array
var Temp_Wound_obj2 = {"WoundNumber": Q1,"BodySide": Q2,"BodyPart":Q3}
Global_Wound_array.push(Temp_Wound_obj2)
}
}
});
</code>```

As well as being able to reach the end of the string to present a blank set of values to have the option to add a new wound.
Every time I think Ive got something that looks like it would work I go around in circles, when I try to update the system at the end I get and error that the - invaid parameters for RPC call: variable is bad

答:
It seems you are pasting JSON onto JSON, with no separator. This creates a messy and non-standard data structure. If you wrote your JSON with a newline at the end, you would end up with a JSONL file, which is very simple to process.

const jsonl = `
[{"WCount":1,"Side":"Centre","Part":"Ocipit","Type":"Other","SurroundingSkin":"Dermatitis","Height":"","Width":"","Depth":""}]
[{"WCount":2,"Side":"Front","Part":"Neck","Type":"Diabetic foot wound","SurroundingSkin":"Healthy/intact","Height":"3","Width":"4","Depth":"5"}]
`;

const jsonItems = jsonl.trim().split("\n");
const lastJsonItem = jsonItems[jsonItems.length - 1];
const lastItem = JSON.parse(lastJsonItem);
const lastWCount = lastItem[0].WCount;
console.log(lastWCount);```

If you already have a file without newlines... it would be best to insert them, and correct your data to JSONL. This is simple in your case just by replacing ][ with ]\n[ (and making sure the file ends with a newline too, so the next write would not be messed up), since you have no nesting and (hopefully) no ][ in your text, but in general it is not easy - I don't know of a JSON parser that will return unconsumed text, so it would probably involve writing a JSON parser. Much easier to write data correctly in the first place.

Title: Searching a string

Body:
OK Ive been able to get the following to partially work

var Global_Wound_array =[{"WoundNumber":1,"BodySide":"Front","BodyPart":"Nose"},{"WoundNumber":2,"BodySide":"Left","BodyPart":"Head"},{"WoundNumber":3,"BodySide":"Back","BodyPart":"Ear"}]
var Global_Wound_Counter = 1

I can get the page to loop through and display the individual wounds but I need a way to say at a particular page one of the values eg on WoundNumber 2 BodyPart has changed and updated the string without affecting the rest of it.

page9200.setEventHandler("pageFinishing", function () {
//getSelectedButtonLabel this is ok - specific on the system
let Q1 = Q3_WoundNumber.getValue();
let Q2 = Q1_BodySide.getSelectedButtonLabel();
let Q3 = Q2_BodyPart.getSelectedButtonLabel();
for (var i = 0; i < Global_Wound_array.length; i++) {
if (i+1 == Q1){
//create new temp variable array
var Temp_Wound_obj2 = {"WoundNumber": Q1,"BodySide": Q2,"BodyPart":Q3}
Global_Wound_array.push(Temp_Wound_obj2)
}
}
});

As well as being able to reach the end of the string to present a blank set of values to have the option to add a new wound.
Every time I think Ive got something that looks like it would work I go around in circles, when I try to update the system at the end I get and error that the - invaid parameters for RPC call: variable is bad

Body:
It seems you are pasting JSON onto JSON, with no separator. This creates a messy and non-standard data structure. If you wrote your JSON with a newline at the end, you would end up with a JSONL file, which is very simple to process.

const jsonl = `
[{"WCount":1,"Side":"Centre","Part":"Ocipit","Type":"Other","SurroundingSkin":"Dermatitis","Height":"","Width":"","Depth":""}]
[{"WCount":2,"Side":"Front","Part":"Neck","Type":"Diabetic foot wound","SurroundingSkin":"Healthy/intact","Height":"3","Width":"4","Depth":"5"}]
`;

const jsonItems = jsonl.trim().split("\n");
const lastJsonItem = jsonItems[jsonItems.length - 1];
const lastItem = JSON.parse(lastJsonItem);
const lastWCount = lastItem[0].WCount;
console.log(lastWCount);

If you already have a file without newlines... it would be best to insert them, and correct your data to JSONL. This is simple in your case just by replacing ][ with ]\n[ (and making sure the file ends with a newline too, so the next write would not be messed up), since you have no nesting and (hopefully) no ][ in your text, but in general it is not easy - I don't know of a JSON parser that will return unconsumed text, so it would probably involve writing a JSON parser. Much easier to write data correctly in the first place.


问:
React is taking way more time for execution than expected
I have tried to implement drench game. I have attached my code below. The logic is correct and it shouldn't also take so much time for execution given it is a 14x14 board. But after some clicks when the state.covered covers about quarter of the board the execution is taking way long to complete.

```<code>import './App.css';
import { useState } from 'react'

function App() {
  const colors = ['aliceblue', 'tomato', 'darksalmon', 'thistle', 'olivedrab', 'steelblue']

  var dp = [];

  for(let i=0;i<14;i++){
    let temp = []
    for(let j=0;j<14;j++){
      temp[j] = colors[Math.floor(Math.random() * 6)]
    }
    dp.push(temp)
  }

  var [state, setState] = useState({
    boardColors: dp,
    covered : [{x:0,y:0}],
  })

  var changeState = (color) => {

    var prevcolor = state.boardColors[0][0]
    var q = [...state.covered]
    var append_arr = [...state.covered]
    function isnotcovered(l,m,xt){
      for(let i=0;i<xt.length;i++){
        if(xt[i].x===l && xt[i].y===m){
          return false;
        }
      }
      return true;
    }

    var temp2D = [...state.boardColors];
      while(q.length){
        let top = q.shift()
        let l = top.x;
        let m = top.y;
        if( m-1>0 && temp2D[l][m-1]===prevcolor && isnotcovered(l,m-1,append_arr)){
          q.push({x:l,y:m-1})
          append_arr.push({x:l,y:m-1})
        }
        if(l+1<14  && temp2D[l+1][m]===prevcolor && isnotcovered(l+1,m,append_arr)){
          q.push({x:l+1,y:m})
          append_arr.push({x:l+1,y:m})
        }
        if(m+1<14 && temp2D[l][m+1]===prevcolor && isnotcovered(l,m+1,append_arr)){
          q.push({x:l,y:m+1})
          append_arr.push({x:l,y:m+1})
        }
        if(l-1>0 && temp2D[l-1][m]===prevcolor && isnotcovered(l-1,m,append_arr)){
          q.push({x:l-1,y:m})
          append_arr.push({x:l-1,y:m})
        }
      }

    setState((state) => ({boardColors : temp2D, covered : [...state.covered, ...append_arr]}) )

    setState((state) => updateState(state))

    function updateState(state){

      function isnotcovered(l,m,xt){
        for(let i=0;i<xt.length;i++){
          if(xt[i].x===l && xt[i].y===m){
            return false;
          }
        }
        return true;
      }

      var temp2D = [...state.boardColors];
      for(let i=0; i<state.covered.length; i++){
        temp2D[state.covered[i].x][state.covered[i].y]=color
      }
      var q = [...state.covered]
      var append_arr = [...state.covered]
      while(q.length){
        let top = q.shift()
        let l = top.x;
        let m = top.y;
        if( m-1>0 && temp2D[l][m-1]===color && isnotcovered(l,m-1,append_arr)){
          q.push({x:l,y:m-1})
          append_arr.push({x:l,y:m-1})
        }
        if(l+1<14  && temp2D[l+1][m]===color && isnotcovered(l+1,m,append_arr)){
          q.push({x:l+1,y:m})
          append_arr.push({x:l+1,y:m})
        }
        if(m+1<14 && temp2D[l][m+1]===color && isnotcovered(l,m+1,append_arr)){
          q.push({x:l,y:m+1})
          append_arr.push({x:l,y:m+1})
        }
        if(l-1>0 && temp2D[l-1][m]===color && isnotcovered(l-1,m,append_arr)){
          q.push({x:l-1,y:m})
          append_arr.push({x:l-1,y:m})
        }
      }
      return {
        boardColors : temp2D,
        covered : [...state.covered, ...append_arr],
      }
    }
  }

  return (
    <>
      <Board colors2D={state.boardColors} />
      <Controls boardColors={state.boardColors} colors2D={state.boardColors} colors={colors} color='green' changeState={changeState}/>
    </>
  );
}

function Board(props){
  var boardStyle = {
    height: '280px',
    aspectRatio: '1',
    backgroundColor: 'lightgreen'
  }
  var display = props.colors2D.map((color1D, index1) => (color1D.map((color,index2) => <div key={14*index1 + index2} style={{width:'20px', aspectRatio: '1', backgroundColor: color, float: 'left'}}></div>)))
  return(
    <div style={boardStyle}>
      {display}
    </div>
  )
}

function Controls(props){
  var controlStyle = {
    height: '200px',
    width: '300px',
    backgroundColor: props.color
  }

  var handleClick = (color) => {
    props.changeState(color)
  }
  var buttons = props.colors.map((color, index) => <button key={index} onClick={() => handleClick(color)}>{color}</button>)

  return(
    <>
      <div style={controlStyle}>
        {buttons}
      </div>
    </>
  )
}
export default App;
</code>```

replace this code in App.js and it should work fine

答:
I think I've found the problem by doing a console.log of your state everytime it changes:

```<code>  useEffect(() => {
    console.log(state);
  }, [state]);
</code>```

Everytime you click on a color button (even if it's the same), the displayed state shows an array as value of the covered key that gets its size multiplied by 4.

This is because you are copying the content of covered boxes in append_arr variable:

```<code>var append_arr = [...state.covered]
</code>```

And when the computing is done you append the content of state.covered and the content of append_arr into state.covered:

```<code>covered : [...state.covered, ...append_arr],
</code>```

This makes it at least double at every click.

You should assign only the result of append_arr as the new covered state:

```<code>covered : [...append_arr],
</code>```

And the reason it actually quadruples is because you are doing this twice, with 2 functions changeState and updateState doing more or less the same thing and called each time.

You are callign setState twice. This can't be useful because the result of the first call will be applied only when the whole function finishes. You should remove one of the occurrences:

```<code>    /* removing this one
    setState((state) => ({boardColors : temp2D, covered : [...state.covered, ...append_arr]}) ) */

    setState((state) => updateState(state))
</code>```

Body:
I have tried to implement drench game. I have attached my code below. The logic is correct and it shouldn't also take so much time for execution given it is a 14x14 board. But after some clicks when the state.covered covers about quarter of the board the execution is taking way long to complete.

import './App.css';
import { useState } from 'react'

function App() {
  const colors = ['aliceblue', 'tomato', 'darksalmon', 'thistle', 'olivedrab', 'steelblue']

  var dp = [];

  for(let i=0;i<14;i++){
    let temp = []
    for(let j=0;j<14;j++){
      temp[j] = colors[Math.floor(Math.random() * 6)]
    }
    dp.push(temp)
  }

  var [state, setState] = useState({
    boardColors: dp,
    covered : [{x:0,y:0}],
  })

  var changeState = (color) => {

    var prevcolor = state.boardColors[0][0]
    var q = [...state.covered]
    var append_arr = [...state.covered]
    function isnotcovered(l,m,xt){
      for(let i=0;i<xt.length;i++){
        if(xt[i].x===l && xt[i].y===m){
          return false;
        }
      }
      return true;
    }

    var temp2D = [...state.boardColors];
      while(q.length){
        let top = q.shift()
        let l = top.x;
        let m = top.y;
        if( m-1>0 && temp2D[l][m-1]===prevcolor && isnotcovered(l,m-1,append_arr)){
          q.push({x:l,y:m-1})
          append_arr.push({x:l,y:m-1})
        }
        if(l+1<14  && temp2D[l+1][m]===prevcolor && isnotcovered(l+1,m,append_arr)){
          q.push({x:l+1,y:m})
          append_arr.push({x:l+1,y:m})
        }
        if(m+1<14 && temp2D[l][m+1]===prevcolor && isnotcovered(l,m+1,append_arr)){
          q.push({x:l,y:m+1})
          append_arr.push({x:l,y:m+1})
        }
        if(l-1>0 && temp2D[l-1][m]===prevcolor && isnotcovered(l-1,m,append_arr)){
          q.push({x:l-1,y:m})
          append_arr.push({x:l-1,y:m})
        }
      }

    setState((state) => ({boardColors : temp2D, covered : [...state.covered, ...append_arr]}) )

    setState((state) => updateState(state))

    function updateState(state){

      function isnotcovered(l,m,xt){
        for(let i=0;i<xt.length;i++){
          if(xt[i].x===l && xt[i].y===m){
            return false;
          }
        }
        return true;
      }

      var temp2D = [...state.boardColors];
      for(let i=0; i<state.covered.length; i++){
        temp2D[state.covered[i].x][state.covered[i].y]=color
      }
      var q = [...state.covered]
      var append_arr = [...state.covered]
      while(q.length){
        let top = q.shift()
        let l = top.x;
        let m = top.y;
        if( m-1>0 && temp2D[l][m-1]===color && isnotcovered(l,m-1,append_arr)){
          q.push({x:l,y:m-1})
          append_arr.push({x:l,y:m-1})
        }
        if(l+1<14  && temp2D[l+1][m]===color && isnotcovered(l+1,m,append_arr)){
          q.push({x:l+1,y:m})
          append_arr.push({x:l+1,y:m})
        }
        if(m+1<14 && temp2D[l][m+1]===color && isnotcovered(l,m+1,append_arr)){
          q.push({x:l,y:m+1})
          append_arr.push({x:l,y:m+1})
        }
        if(l-1>0 && temp2D[l-1][m]===color && isnotcovered(l-1,m,append_arr)){
          q.push({x:l-1,y:m})
          append_arr.push({x:l-1,y:m})
        }
      }
      return {
        boardColors : temp2D,
        covered : [...state.covered, ...append_arr],
      }
    }
  }

  return (
    <>
      <Board colors2D={state.boardColors} />
      <Controls boardColors={state.boardColors} colors2D={state.boardColors} colors={colors} color='green' changeState={changeState}/>
    </>
  );
}

function Board(props){
  var boardStyle = {
    height: '280px',
    aspectRatio: '1',
    backgroundColor: 'lightgreen'
  }
  var display = props.colors2D.map((color1D, index1) => (color1D.map((color,index2) =>

)))
  return(

      {display}

  )
}

function Controls(props){
  var controlStyle = {
    height: '200px',
    width: '300px',
    backgroundColor: props.color
  }

  var handleClick = (color) => {
    props.changeState(color)
  }
  var buttons = props.colors.map((color, index) => <button key={index} onClick={() => handleClick(color)}>{color}</button>)

  return(
    <>

        {buttons}

    </>
  )
}
export default App;

replace this code in App.js and it should work fine

Body:
I think I've found the problem by doing a console.log of your state everytime it changes:

  useEffect(() => {
    console.log(state);
  }, [state]);

Everytime you click on a color button (even if it's the same), the displayed state shows an array as value of the covered key that gets its size multiplied by 4.

This is because you are copying the content of covered boxes in append_arr variable:

var append_arr = [...state.covered]

And when the computing is done you append the content of state.covered and the content of append_arr into state.covered:

covered : [...state.covered, ...append_arr],

This makes it at least double at every click.

You should assign only the result of append_arr as the new covered state:

covered : [...append_arr],

And the reason it actually quadruples is because you are doing this twice, with 2 functions changeState and updateState doing more or less the same thing and called each time.

You are callign setState twice. This can't be useful because the result of the first call will be applied only when the whole function finishes. You should remove one of the occurrences:

    /* removing this one
    setState((state) => ({boardColors : temp2D, covered : [...state.covered, ...append_arr]}) ) */

    setState((state) => updateState(state))


问:
Visual Studio keeps saying "error CS1002: ; expected"
I am new to coding with C# in unity and am trying to animate an object in unity, but its saying that I need a semicolon but I can't find where I need one. This is my code:

```<code>{
  public GameObject arm;
  public float time = 0f;
  public bool timedone = false;
  void Update()
  {
     if(time == 1f)
     {
         timedone = true;
     }
     if (Input.GetButtonDown("Fire1"))
     {
         arm.GetComponent<Animator>().Play("New Animation");
     }
     else
     {
         if(!timedone)
         {
             time += Time.deltaTime;
         }
         if (timedone)
         {
            arm.GetComponent<Animator>().Play("New State");
            Timereset()
         }
      }
  }
  void Timereset()
  {
    time == 0f;
  }
}
</code>```

If you can help me I would be very grateful.

答:
In else condition ,

Timereset() doesn't have ; there should be Timereset();

Body:
I am new to coding with C# in unity and am trying to animate an object in unity, but its saying that I need a semicolon but I can't find where I need one. This is my code:

{
  public GameObject arm;
  public float time = 0f;
  public bool timedone = false;
  void Update()
  {
     if(time == 1f)
     {
         timedone = true;
     }
     if (Input.GetButtonDown("Fire1"))
     {
         arm.GetComponent<Animator>().Play("New Animation");
     }
     else
     {
         if(!timedone)
         {
             time += Time.deltaTime;
         }
         if (timedone)
         {
            arm.GetComponent<Animator>().Play("New State");
            Timereset()
         }
      }
  }
  void Timereset()
  {
    time == 0f;
  }
}

If you can help me I would be very grateful.


问:
Python MySQL connector returns bytearray instead of regular string value
I am loading data from one table into pandas and then inserting that data into new table. However, instead of normal string value I am seeing bytearray.

bytearray(b'TM16B0I8') it should be TM16B0I8

What am I doing wrong here?

My code:

```<code>engine_str = 'mysql+mysqlconnector://user:pass@localhost/db'
engine = sqlalchemy.create_engine(engine_str, echo=False, encoding='utf-8')
connection = engine.connect()

th_df = pd.read_sql('select ticket_id, history_date', con=connection)

for row in th_df.to_dict(orient="records"):
    var_ticket_id = row['ticket_id']
    var_history_date = row['history_date']

    query = 'INSERT INTO new_table(ticket_id, history_date)....'
</code>```

答:
Producing a bytearray is now the expected behaviour.

It changed with mysql-connector-python 8.0.24 (2021-04-20). According to the v8.0.24 release notes, "Binary columns were returned as strings instead of 'bytes' or 'bytearray'" behaviour was a bug that was fixed in that release.

So producing a Python binaryarray is the correct behaviour, if the database column is a binary type (e.g. binary or varbinary). Previously, it produced a Python string, but now it produces a binaryarray.

So either change the data type in the database to a non-binary data type, or convert the binaryarray to a string in your code. If the column is nullable, you'll have to check for that first; since attempting to invoke decode() method on None would produce an error. You'll also have to be sure the bytes represent a valid string, in the character encoding being used for the decoding/conversion.

Body:
I am loading data from one table into pandas and then inserting that data into new table. However, instead of normal string value I am seeing bytearray.

bytearray(b'TM16B0I8') it should be TM16B0I8

What am I doing wrong here?

My code:

engine_str = 'mysql+mysqlconnector://user:pass@localhost/db'
engine = sqlalchemy.create_engine(engine_str, echo=False, encoding='utf-8')
connection = engine.connect()

th_df = pd.read_sql('select ticket_id, history_date', con=connection)

for row in th_df.to_dict(orient="records"):
    var_ticket_id = row['ticket_id']
    var_history_date = row['history_date']

    query = 'INSERT INTO new_table(ticket_id, history_date)....'


问:
How to convert two vectors into dataframe (wide format)
I want to convert two vectors into a wide format dataframe. The fist vector represent the column names and the second vector the values.
Here is my reproduceable example:

```<code>vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)
</code>```

Now I want to convert these two vector into a wide format dataframe:

```<code># A tibble: 1 x 5
   Reply Reshare  Like Share Search
   <dbl>   <dbl> <dbl> <dbl>  <dbl>
1     2       1     0     4      3
</code>```

I have found some examples for the long format, but none simple solution for the wide format. Can anyone help me?

答:
Another possible solution:</p>
```<code>library(dplyr)

data.frame(rbind(vector1, vector2)) %>%
  `colnames<-`(.[1, ]) %>%
  .[-1, ] %>%
  `rownames<-`(NULL)

  Reply Reshare Like Share Search
1     2       1    0     4      3
</code>```

Body:
I want to convert two vectors into a wide format dataframe. The fist vector represent the column names and the second vector the values.
Here is my reproduceable example:

vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)

Now I want to convert these two vector into a wide format dataframe:

# A tibble: 1 x 5
   Reply Reshare  Like Share Search
   <dbl>   <dbl> <dbl> <dbl>  <dbl>
1     2       1     0     4      3

I have found some examples for the long format, but none simple solution for the wide format. Can anyone help me?

Body:
Another possible solution:

library(dplyr)

data.frame(rbind(vector1, vector2)) %>%
  `colnames<-`(.[1, ]) %>%
  .[-1, ] %>%
  `rownames<-`(NULL)

  Reply Reshare Like Share Search
1     2       1    0     4      3


问:
Buttons are not spaced with css present
I'm having a problem with buttons in CSS.

Between the first two I get the right distance, but between the second and the third I get two buttons joined (attached) (as in the picture).

How can I solve this problem?

.buttons {
  display: flex;
}

.buttons form {
  margin: 0 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="buttons">
  <form action="createArt.html">
    <input type="submit" value="ADD" />
  </form>
  <input type="button" value="EDIT" onclick="confirmation_edit()" />
  <input type="button" value="DELETE" onclick="confirmation_delete()" />
</div></code>```

答:
You would probably be better served with a specific class on the button but here I added the selector the the input based on type (probably not the way to do this; classes should be used to style)

.buttons {
  display: flex;
}

.buttons form ,
.buttons input[type="button"] {
  margin: 0 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="buttons">
  <form action="createArt.html">
    <input type="submit" value="ADD" />
  </form>
  <input type="button" value="EDIT" onclick="confirmation_edit()" />
  <input type="button" value="DELETE" onclick="confirmation_delete()" />
</div></code>```

Title: Buttons are not spaced with css present

Body:
I'm having a problem with buttons in CSS.

Between the first two I get the right distance, but between the second and the third I get two buttons joined (attached) (as in the picture).

How can I solve this problem?

.buttons {
  display: flex;
}

.buttons form {
  margin: 0 10px;
}

  <form action="createArt.html">
    <input type="submit" value="ADD" />
  </form>
  <input type="button" value="EDIT" onclick="confirmation_edit()" />
  <input type="button" value="DELETE" onclick="confirmation_delete()" />

Body:
You would probably be better served with a specific class on the button but here I added the selector the the input based on type (probably not the way to do this; classes should be used to style)

.buttons {
  display: flex;
}

.buttons form ,
.buttons input[type="button"] {
  margin: 0 10px;
}

<div class="buttons">
  <form action="createArt.html">
    <input type="submit" value="ADD" />
  </form>
  <input type="button" value="EDIT" onclick="confirmation_edit()" />
  <input type="button" value="DELETE" onclick="confirmation_delete()" />
</div>


问:
Split a single data frame into multiple data frames based on a columns value in pandas
I have a data frame that has thousands of rows in a Jupyter Notebook using Pandas. I am attempting to use a particular column in this data frame to split the df into multiple dfs based on the columns values. If there is a way to do this without specifying the different values in the column explicitly, that would be great.

Col1
Col2
Col3
Col4

dat1
Val1
etc1
set1

dat2
Val2
etc2
set2

dat3
Val3
etc3
set2

dat4
Val4
etc4
set3

An example of one of the variations of my code:

```<code>NAM_df2 = NAM_df1.loc[NAM_df1["Col4"] == 'set2']
</code>```

答:
Try this:</p>
```<code>dfs = [d for _, d in df.groupby('Col4')]
</code>```

Body:
I have a data frame that has thousands of rows in a Jupyter Notebook using Pandas. I am attempting to use a particular column in this data frame to split the df into multiple dfs based on the columns values. If there is a way to do this without specifying the different values in the column explicitly, that would be great.

Col1
Col2
Col3
Col4

dat1
Val1
etc1
set1

dat2
Val2
etc2
set2

dat3
Val3
etc3
set2

dat4
Val4
etc4
set3

An example of one of the variations of my code:

NAM_df2 = NAM_df1.loc[NAM_df1["Col4"] == 'set2']

Body:
Try this:

dfs = [d for _, d in df.groupby('Col4')]


问:
Not Able to Iterate in Each loop to change Opacity of Set of Elements
Can you please take a look at this demo and let me know why I am not able to make an infinity loop to change opacity of each
 (like fadeIn fadeOut functions ).
I am trying to mix the fadeIn and fadeOut function with display none utility.

$(function() {

  $("p").each(function() {
    $('p').animate({
      opacity: 0
    }, 500, function() {
      $('p').css('display', 'none');
      $(this).css('display', 'block');
      $(this).animate({
        opacity: 1
      }, 500);
    });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  color: #008080;
  background-size: 40px;
  padding: 10px;
  font-size: 30px;
    display: none;
    opacity: 0;
}</code>```

This is the fiest step

This is the second step

This is the third step

This is the forth step
```

答:
Each callback of .each( runs synchronously - each one will run immediately without waiting for the prior one to finish. You should use .promise() to have a callback wait for the animation to complete before proceeding - but since you also want to loop endlessly, and not just once, you'll also need a completely different strategy. Consider having a persistent index variable that you reassign using modulo, and whose associated element's animation you await inside a loop.

(async() => {
  const ps = $('p');
  let i = 0;
  while (true) {
    await ps.eq(i).animate({
      opacity: 0
    }, 500, function() {
      $('p').css('display', 'none');
      $(this).css('display', 'block');
      $(this).animate({
        opacity: 1
      }, 500);
    }).promise();
    i = (i + 1) % ps.length;
  }
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  color: #008080;
  background-size: 40px;
  padding: 10px;
  font-size: 30px;
  display: none;
  opacity: 0;
}</code>```

This is the fiest step

This is the second step

This is the third step

This is the forth step
```

Body:
Can you please take a look at this demo and let me know why I am not able to make an infinity loop to change opacity of each
 (like fadeIn fadeOut functions ).
I am trying to mix the fadeIn and fadeOut function with display none utility.

$(function() {

  $("p").each(function() {
    $('p').animate({
      opacity: 0
    }, 500, function() {
      $('p').css('display', 'none');
      $(this).css('display', 'block');
      $(this).animate({
        opacity: 1
      }, 500);
    });
  });
});

p {
  color: #008080;
  background-size: 40px;
  padding: 10px;
  font-size: 30px;
    display: none;
    opacity: 0;
}

This is the fiest step

This is the second step

This is the third step

This is the forth step

Body:
Each callback of .each( runs synchronously - each one will run immediately without waiting for the prior one to finish. You should use .promise() to have a callback wait for the animation to complete before proceeding - but since you also want to loop endlessly, and not just once, you'll also need a completely different strategy. Consider having a persistent index variable that you reassign using modulo, and whose associated element's animation you await inside a loop.

(async() => {
  const ps = $('p');
  let i = 0;
  while (true) {
    await ps.eq(i).animate({
      opacity: 0
    }, 500, function() {
      $('p').css('display', 'none');
      $(this).css('display', 'block');
      $(this).animate({
        opacity: 1
      }, 500);
    }).promise();
    i = (i + 1) % ps.length;
  }
})();

p {
  color: #008080;
  background-size: 40px;
  padding: 10px;
  font-size: 30px;
  display: none;
  opacity: 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>This is the fiest step</p>
<p>This is the second step</p>
<p>This is the third step</p>
<p>This is the forth step</p>