问:
RichFaces FileUpload and Flash Support ending in 2020
Well, in my company we have a legacy web system that uses JSF 1.2, Seam 2.2 and RichFaces 3.3

Well, there's one part of the system that uses rich:fileUpload with FlashSupport, but as we know Flash won't be supported anymore by the end of 2020.

The question is: is there some way to change this rather than migrate the system to new techonologies? (This will be done, for sure, but problably only in 2021).

Thanks in advance.
Raphael

答:
my company went through the same problem and we developed a way to use the component without flash with several uploads. Follow the code.
Basically the javascript takes the multiple files in the input and sends it in a queue to the rich component simulating multipload.

arquivo.js

var files = []

function FileListItem(a) {
 a = [].slice.call(Array.isArray(a) ? a : arguments)
 for (var c, b = c = a.length, d = !0; b-- && d;)
  d = a[b] instanceof File
 if (!d)
  throw new TypeError(
    "expected argument to FileList is File or array of File objects")
 for (b = (new ClipboardEvent("")).clipboardData || new DataTransfer; c--;)
  b.items.add(a[c])
 return b.files
}

function docUpload(f) {

 // Popula files
 for (var i = 0; i < jQuery("#fUpload")[0].files.length; i++) {
  files[i] = jQuery("#fUpload")[0].files[i]
 }

 if (files.length > 0) {
        //just a loading modal not nedded
  document.getElementById('loading_mp').component.show();

  file = files[0]
  files.splice(0, 1)

  upload(file);
 } else {
        //just a loading modal not nedded
  document.getElementById('loading_mp').component.hide();
 }
}

function upload(file) {
 console.log('Starting Upload  ')
 jQuery(".rich-fileupload-hidden")[0].files = FileListItem([ file ])
 jQuery(".rich-fileupload-hidden").change();
 console.log('End  ')
}

function uploadMult() {
 if (files.length > 0) {
  file = files[0]
  files.splice(0, 1)
  upload(file);
 } else {
  jQuery("#fUpload")[0].files = null
  document.getElementById('loading_mp').component.hide();
 }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style type="text/css">
  #fileUploadSingle {
   float: left;
   border: none;
  }
  .rich-fileupload-list-decor {
   display: none;
  }

  #fileUploadSingle table.rich-fileupload-toolbar-decor {
   border: none;
   !
   important
  }
  /* Esconde o input */
  #fUpload {
    display: none
  }

  /* Aparência que terá o seletor de arquivo */
  .labelInputFile {
      background-color: #3498db;
      border-radius: 5px;
      color: #fff;
      cursor: pointer;
      margin: 10px;
      padding-left: 20px;
      padding-right: 20px !important;
      padding-top: 6px;
      padding-bottom: 6px;
  }
 </style></code>```

<a4j:jsFunction name="doOnUpload" action="#{documentoBean.onUpload}" />

Select File »
<input id="fUpload" type="file" onchange="docUpload(this)" multiple="multiple" />

<rich:fileUpload fileUploadListener="#{documentoBean.listener}"
    id="upload" autoclear="true" immediateUpload="true"
    clearAllControlLabel="Limpar" addControlLabel="Adicionar"
    maxFilesQuantity="30" allowFlash="false" ajaxSingle="true"
    listHeight="60" listWidth="700" onupload="doOnUpload(event)" >
    <a4j:support event="onfileuploadcomplete" reRender="list" ignoreDupResponses="true"
     oncomplete="uploadMult()" />
</rich:fileUpload>

PS:
doOnUpload not required

On Bean:
 public void listener(UploadEvent event) throws Exception {
     event.getUploadItem().getFile();
     event.getUploadItem().getFileName();
    }

     public void onUpload() {
        this.msgList.clear();
    }```

Body:
my company went through the same problem and we developed a way to use the component without flash with several uploads. Follow the code.
Basically the javascript takes the multiple files in the input and sends it in a queue to the rich component simulating multipload.

arquivo.js

var files = []

function FileListItem(a) {
 a = [].slice.call(Array.isArray(a) ? a : arguments)
 for (var c, b = c = a.length, d = !0; b-- && d;)
  d = a[b] instanceof File
 if (!d)
  throw new TypeError(
    "expected argument to FileList is File or array of File objects")
 for (b = (new ClipboardEvent("")).clipboardData || new DataTransfer; c--;)
  b.items.add(a[c])
 return b.files
}

function docUpload(f) {

 // Popula files
 for (var i = 0; i < jQuery("#fUpload")[0].files.length; i++) {
  files[i] = jQuery("#fUpload")[0].files[i]
 }

 if (files.length > 0) {
        //just a loading modal not nedded
  document.getElementById('loading_mp').component.show();

  file = files[0]
  files.splice(0, 1)

  upload(file);
 } else {
        //just a loading modal not nedded
  document.getElementById('loading_mp').component.hide();
 }
}

function upload(file) {
 console.log('Starting Upload  ')
 jQuery(".rich-fileupload-hidden")[0].files = FileListItem([ file ])
 jQuery(".rich-fileupload-hidden").change();
 console.log('End  ')
}

function uploadMult() {
 if (files.length > 0) {
  file = files[0]
  files.splice(0, 1)
  upload(file);
 } else {
  jQuery("#fUpload")[0].files = null
  document.getElementById('loading_mp').component.hide();
 }

}

<style type="text/css">
  #fileUploadSingle {
   float: left;
   border: none;
  }
  .rich-fileupload-list-decor {
   display: none;
  }

  #fileUploadSingle table.rich-fileupload-toolbar-decor {
   border: none;
   !
   important
  }
  /* Esconde o input */
  #fUpload {
    display: none
  }

  /* Aparência que terá o seletor de arquivo */
  .labelInputFile {
      background-color: #3498db;
      border-radius: 5px;
      color: #fff;
      cursor: pointer;
      margin: 10px;
      padding-left: 20px;
      padding-right: 20px !important;
      padding-top: 6px;
      padding-bottom: 6px;
  }
 </style>

<a4j:jsFunction name="doOnUpload" action="#{documentoBean.onUpload}" />

<label class="labelInputFile" for='fUpload'>Select File &#187;</label>
<input id="fUpload" type="file" onchange="docUpload(this)" multiple="multiple" />

<br/><br/>

<rich:fileUpload fileUploadListener="#{documentoBean.listener}"
    id="upload" autoclear="true" immediateUpload="true"
    clearAllControlLabel="Limpar" addControlLabel="Adicionar"
    maxFilesQuantity="30" allowFlash="false" ajaxSingle="true"
    listHeight="60" listWidth="700" onupload="doOnUpload(event)" >
    <a4j:support event="onfileuploadcomplete" reRender="list" ignoreDupResponses="true"
     oncomplete="uploadMult()" />
</rich:fileUpload>

PS:
doOnUpload not required

On Bean:
 public void listener(UploadEvent event) throws Exception {
     event.getUploadItem().getFile();
     event.getUploadItem().getFileName();
    }

     public void onUpload() {
        this.msgList.clear();
    }


来源: stackexchange

问:
Is there a way I can create infinite closures in JavaScript
I was presented with question and I had no idea how to do it

add() - > returns 0

add(1)() -> returns 1

add(1)(2)() -> returns 3

add(1)(2)(3)(4)() -> 10

Basically it can go on

答:
You can access the arguments through the variable arguments. Read more about it here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

I'm using a basic for loop, mostly for clarity, to show case it below.

function add() {
  var sum = 0;

  for (let i = 0; i < arguments.length; i++) {
     sum += arguments[i];
  }

  /* Alternative loop
  for (let number of arguments) {
    sum += number;
  } */

  return sum;
}

console.log( add(1) );

console.log( add(1, 2) );        // returns 3

console.log( add(1, 2, 3, 4) );  // returns 10```

ContentLicense: CC BY-SA 4.0


问:
Including 5.8.13 version of Javers causes weird `9730` error message at build time
I'm encountering strange behavior when trying to include latest version of Javers (5.8.13 atm)

adding

```<code>implementation("org.javers:javers-spring-boot-starter-mongo:5.8.13")
</code>```

into my gradle.build.kts file and then launching a build with

```<code>gradlew build
</code>```

produces this error message

Execution failed for task ':compileKotlin'.
  9730

If I downgrade to the previous version (5.8.12), then build completes sucessfully.

Running the build with --stacktrace produces this (excerpt of the stacktrace):

```<code>2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Caused by: java.lang.ArrayIndexOutOfBoundsException: 9730
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.codehaus.plexus.util.xml.pull.MXParser.parsePI(MXParser.java:2470)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.codehaus.plexus.util.xml.pull.MXParser.nextImpl(MXParser.java:1257)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.codehaus.plexus.util.xml.pull.MXParser.next(MXParser.java:1105)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.codehaus.plexus.util.xml.pull.MXParser.nextTag(MXParser.java:1090)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.apache.maven.model.io.xpp3.MavenXpp3Reader.parsePlugin(MavenXpp3Reader.java:2892)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.apache.maven.model.io.xpp3.MavenXpp3Reader.parsePluginManagement(MavenXpp3Reader.java:3186)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.apache.maven.model.io.xpp3.MavenXpp3Reader.parseBuild(MavenXpp3Reader.java:1157)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.apache.maven.model.io.xpp3.MavenXpp3Reader.parseModel(MavenXpp3Reader.java:2456)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.apache.mav
</code>```

PS : the issue happens for other Javers dependencies of the same version (javers-core, ...) too

答: Updating Javers to v5.9.1 or later should resolve the issue (see v5.9.1 release notes)

Body:
I'm encountering strange behavior when trying to include latest version of Javers (5.8.13 atm)

adding

implementation("org.javers:javers-spring-boot-starter-mongo:5.8.13")

into my gradle.build.kts file and then launching a build with

gradlew build

produces this error message

Execution failed for task ':compileKotlin'.
  9730

If I downgrade to the previous version (5.8.12), then build completes sucessfully.

Running the build with --stacktrace produces this (excerpt of the stacktrace):

2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Caused by: java.lang.ArrayIndexOutOfBoundsException: 9730
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.codehaus.plexus.util.xml.pull.MXParser.parsePI(MXParser.java:2470)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.codehaus.plexus.util.xml.pull.MXParser.nextImpl(MXParser.java:1257)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.codehaus.plexus.util.xml.pull.MXParser.next(MXParser.java:1105)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.codehaus.plexus.util.xml.pull.MXParser.nextTag(MXParser.java:1090)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.apache.maven.model.io.xpp3.MavenXpp3Reader.parsePlugin(MavenXpp3Reader.java:2892)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.apache.maven.model.io.xpp3.MavenXpp3Reader.parsePluginManagement(MavenXpp3Reader.java:3186)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.apache.maven.model.io.xpp3.MavenXpp3Reader.parseBuild(MavenXpp3Reader.java:1157)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.apache.maven.model.io.xpp3.MavenXpp3Reader.parseModel(MavenXpp3Reader.java:2456)
2020-04-17T10:50:37.154+0200 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at io.spring.gradle.dependencymanagement.org.apache.mav

PS : the issue happens for other Javers dependencies of the same version (javers-core, ...) too


问:
Tensorflow One Hot Encoding - Could not find valid device for node
During my feature engingeering the following error occurred. My featurelist has 21 sublists with each 8537 values being either 0 or 1. When trying to run the One Hot Encoding via tensorflow it shows the error Could not find valid device for node
Does anyone have a quick fix for the error?

```<code>for feature in featurelist[1:]:
    df = tensorflow.convert_to_tensor(feature, dtype=tensorflow.float32)
    print(df)
    df_enc = tensorflow.one_hot(df, 2, on_value=None, off_value=None, axis=None, dtype=None, name=None)
    print(df_enc)
</code>```

```<code>2020-05-29 15:08:41.969878: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x7fdefbc23d50 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-05-29 15:08:41.969919: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
tf.Tensor([0. 0. 0. ... 0. 0. 0.], shape=(8537,), dtype=float32)
Traceback (most recent call last):
  File "/Users/marius/Desktop/Masterarbeit/Github/virtual7/tempCodeRunnerFile.python", line 1234, in <module>
    df_enc = tensorflow.one_hot(df, 2, on_value=None, off_value=None, axis=None, dtype=None, name=None)
  File "/Users/marius/.pyenv/versions/3.7.3/lib/python3.7/site-packages/tensorflow_core/python/util/dispatch.py", line 180, in wrapper
    return target(*args, **kwargs)
  File "/Users/marius/.pyenv/versions/3.7.3/lib/python3.7/site-packages/tensorflow_core/python/ops/array_ops.py", line 3645, in one_hot
    name)
  File "/Users/marius/.pyenv/versions/3.7.3/lib/python3.7/site-packages/tensorflow_core/python/ops/gen_array_ops.py", line 5549, in one_hot
    _ops.raise_from_not_ok_status(e, name)
  File "/Users/marius/.pyenv/versions/3.7.3/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py", line 6606, in raise_from_not_ok_status
    six.raise_from(core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.NotFoundError: Could not find valid device for node.
Node:{{node OneHot}}
All kernels registered for op OneHot :
  device='XLA_CPU_JIT'; TI in [DT_INT32, DT_UINT8, DT_INT64]; T in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_UINT8, DT_INT16, ..., DT_UINT16, DT_COMPLEX128, DT_HALF, DT_UINT32, DT_UINT64]
  device='XLA_CPU'; TI in [DT_INT32, DT_UINT8, DT_INT64]; T in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_UINT8, DT_INT16, ..., DT_UINT16, DT_COMPLEX128, DT_HALF, DT_UINT32, DT_UINT64]
  device='CPU'; TI in [DT_UINT8]; T in [DT_INT64]
  device='CPU'; TI in [DT_INT32]; T in [DT_INT64]
  device='CPU'; TI in [DT_INT64]; T in [DT_INT64]
  device='CPU'; TI in [DT_UINT8]; T in [DT_INT32]
  .....
  device='CPU'; TI in [DT_INT32]; T in [DT_INT32]
  device='CPU'; TI in [DT_INT64]; T in [DT_INT32]
  device='CPU'; TI in [DT_UINT8]; T in [DT_UINT16]

 [Op:OneHot] name: one_hot/```
```

答:
You casted your target to tf.float32, which is incompatible with tf.one_hot when using a list. You need to convert your target to an integer dtype before one-hot encoding. Try:

```<code>x = tf.cast(x, tf.int32)
</code>```

Or, convert your tensor to a NumPy array:

```<code>tensor = np.array([0., 1., 2., 3.])

tf.one_hot(tensor, depth=4)
</code>```
```<code><tf.Tensor: shape=(4, 4), dtype=float32, numpy=
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]], dtype=float32)>
</code>```

Body:
During my feature engingeering the following error occurred. My featurelist has 21 sublists with each 8537 values being either 0 or 1. When trying to run the One Hot Encoding via tensorflow it shows the error Could not find valid device for node
Does anyone have a quick fix for the error?

for feature in featurelist[1:]:
    df = tensorflow.convert_to_tensor(feature, dtype=tensorflow.float32)
    print(df)
    df_enc = tensorflow.one_hot(df, 2, on_value=None, off_value=None, axis=None, dtype=None, name=None)
    print(df_enc)

2020-05-29 15:08:41.969878: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x7fdefbc23d50 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-05-29 15:08:41.969919: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
tf.Tensor([0. 0. 0. ... 0. 0. 0.], shape=(8537,), dtype=float32)
Traceback (most recent call last):
  File "/Users/marius/Desktop/Masterarbeit/Github/virtual7/tempCodeRunnerFile.python", line 1234, in <module>
    df_enc = tensorflow.one_hot(df, 2, on_value=None, off_value=None, axis=None, dtype=None, name=None)
  File "/Users/marius/.pyenv/versions/3.7.3/lib/python3.7/site-packages/tensorflow_core/python/util/dispatch.py", line 180, in wrapper
    return target(*args, **kwargs)
  File "/Users/marius/.pyenv/versions/3.7.3/lib/python3.7/site-packages/tensorflow_core/python/ops/array_ops.py", line 3645, in one_hot
    name)
  File "/Users/marius/.pyenv/versions/3.7.3/lib/python3.7/site-packages/tensorflow_core/python/ops/gen_array_ops.py", line 5549, in one_hot
    _ops.raise_from_not_ok_status(e, name)
  File "/Users/marius/.pyenv/versions/3.7.3/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py", line 6606, in raise_from_not_ok_status
    six.raise_from(core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.NotFoundError: Could not find valid device for node.
Node:{{node OneHot}}
All kernels registered for op OneHot :
  device='XLA_CPU_JIT'; TI in [DT_INT32, DT_UINT8, DT_INT64]; T in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_UINT8, DT_INT16, ..., DT_UINT16, DT_COMPLEX128, DT_HALF, DT_UINT32, DT_UINT64]
  device='XLA_CPU'; TI in [DT_INT32, DT_UINT8, DT_INT64]; T in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_UINT8, DT_INT16, ..., DT_UINT16, DT_COMPLEX128, DT_HALF, DT_UINT32, DT_UINT64]
  device='CPU'; TI in [DT_UINT8]; T in [DT_INT64]
  device='CPU'; TI in [DT_INT32]; T in [DT_INT64]
  device='CPU'; TI in [DT_INT64]; T in [DT_INT64]
  device='CPU'; TI in [DT_UINT8]; T in [DT_INT32]
  .....
  device='CPU'; TI in [DT_INT32]; T in [DT_INT32]
  device='CPU'; TI in [DT_INT64]; T in [DT_INT32]
  device='CPU'; TI in [DT_UINT8]; T in [DT_UINT16]

 [Op:OneHot] name: one_hot/```

Body:
You casted your target to tf.float32, which is incompatible with tf.one_hot when using a list. You need to convert your target to an integer dtype before one-hot encoding. Try:

x = tf.cast(x, tf.int32)

Or, convert your tensor to a NumPy array:

tensor = np.array([0., 1., 2., 3.])

tf.one_hot(tensor, depth=4)

<tf.Tensor: shape=(4, 4), dtype=float32, numpy=
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]], dtype=float32)>


问:
Remove characters from url hash
Wanting to remove characters from a hash in a url

side bar create url with anchor

e.g

html/g_later_life_lett.html#3.-what-is-important?everything!

```<code>var test = window.location.hash;
$(test).replace('?', '')
</code>```

so when page loads it looks af any ? and ! in hash and removes them.

thanks for help

Updated: thanks add this works fine now

```<code>var currentHash = window.location.hash;
var cleanHash = currentHash.replace(/[?!]/g, "");
window.location.hash = cleanHash;
</code>```

答:
I think you might be looking for this:

```<code>var test = window.location.hash;
var newTest = $(test).replace(/(\?|!)/gm, '');
</code>```

Put the two / marks in to use a regular expression instead of simply a simple string search.
You can also test your regex here: https://regex101.com/.

Title: Remove characters from url hash

Body:
Wanting to remove characters from a hash in a url

side bar create url with anchor

e.g

html/g_later_life_lett.html#3.-what-is-important?everything!

var test = window.location.hash;
$(test).replace('?', '')

so when page loads it looks af any ? and ! in hash and removes them.

thanks for help

Updated: thanks add this works fine now

var currentHash = window.location.hash;
var cleanHash = currentHash.replace(/[?!]/g, "");
window.location.hash = cleanHash;

Body:
I think you might be looking for this:

var test = window.location.hash;
var newTest = $(test).replace(/(\?|!)/gm, '');

Put the two / marks in to use a regular expression instead of simply a simple string search.
You can also test your regex here: https://regex101.com/.


问:
Angular test cannot access Service before initialization
I cannot make tests start, because they fail at the very beginning with error

```<code>Chrome 83.0.4103.61 (Linux x86_64) ERROR
  An error was thrown in afterAll
  Uncaught ReferenceError: Cannot access 'SomeService' before initialization
  ReferenceError: Cannot access 'SomeService' before initialization

... stack trace
</code>```

The thing is:

a) It's a singleton service and providedIn: 'root'

b) Stack trace points to nowhere (it even includes test files which are totally commented out so there is no single line of code.

c) Other tests don't start because of that

d) I can't start disabling tests to find the starting point due to their amount.

How do I find where an error could happen and what could cause this? Can it be connected to updating Karma, Jasmine and spec reporters to the latest versions of their packages? I'm working with Angular 9

答: It appears that it's due to project's "age". It was started with Angular 6. According to this comment emitDecoratorMetadata in the config is the cause. After deleting this everything works fine...

Body:
I cannot make tests start, because they fail at the very beginning with error

Chrome 83.0.4103.61 (Linux x86_64) ERROR
  An error was thrown in afterAll
  Uncaught ReferenceError: Cannot access 'SomeService' before initialization
  ReferenceError: Cannot access 'SomeService' before initialization

... stack trace

The thing is:

a) It's a singleton service and providedIn: 'root'

b) Stack trace points to nowhere (it even includes test files which are totally commented out so there is no single line of code.

c) Other tests don't start because of that

d) I can't start disabling tests to find the starting point due to their amount.

How do I find where an error could happen and what could cause this? Can it be connected to updating Karma, Jasmine and spec reporters to the latest versions of their packages? I'm working with Angular 9


问:
How can I find and click a button that has no text using React Testing Library?
Many React Testing Library examples show how to find and click a button using the getByText query, as in:

```<code>fireEvent.click(getByText("Create"))
</code>```

OR

```<code>userEvent.click(getByText("Create"))
</code>```

However, it's common to have buttons with no text and only SVG icons, like Material UI's icon buttons or floating action buttons. Is there a recommended way to query for and click buttons like these? For context, I'm using the higher-level events provided by the companion user-event library.

答:
There are a bunch of different ways to do it, including everyone's favorite fallback, data-tested. But if you're using Material UI, you might be looking for the most "MUI" way to do this. Two ideas:

The MUI documentation shows all its buttons wrapped with a label element with an htmlFor property. You could do this and then use getByLabelText()

Your icon buttons probably have (and should!) a tooltip, and the tooltip text is probably coming from a title property. Then you can get the button with getByTitle().

Body:
Many React Testing Library examples show how to find and click a button using the getByText query, as in:

fireEvent.click(getByText("Create"))

OR

userEvent.click(getByText("Create"))

However, it's common to have buttons with no text and only SVG icons, like Material UI's icon buttons or floating action buttons. Is there a recommended way to query for and click buttons like these? For context, I'm using the higher-level events provided by the companion user-event library.


问:
Assigning values to cross selection of MultiIndex DataFrame (ellipsis style of numpy)
In numpy we can select the last axis with ellipsis indexing, f.i. array[..., 4].

In Pandas DataFrames for structuring large amounts of data, I like to use MultiIndex (which I see as some kind of additional dimensions of the DataFrame). If I want to select a given subset of a DataFrame df, in this case all columns 'key' in the last level of the columns MultiIndex, I can do it with the cross selection method xs:

```<code># create sample multiindex dataframe
mi = pd.MultiIndex.from_product((('a', 'b', 'c'), (1, 2), ('some', 'key', 'foo')))
data = pd.DataFrame(data=np.random.rand(20, 18), columns=mi)

# make cross selection:
xs_df = data.xs('key', axis=1, level=-1)
</code>```

But if I want to assign values to the cross selection, xs won't work.

The documentation proposes to use IndexSlice to access and set values to a cross selection:

```<code>idx = pd.IndexSlice
data.loc[:, idx[:, :, 'key']] *= 10
</code>```

Which is working well as long as I explicitly enter the number of levels by inserting the correct amount of : before 'key'.

Assuming I just want to give the number of levels to a selection function or f.i. always select the last level, independent of the number of levels of the DataFrame, this won't work (afaik).

My current workaround is using None slices for n_levels to skip:

```<code>n_levels = data.columns.nlevels - 1  # assuming I want to select the last level
data.loc[:, (*n_levels*[slice(None)], 'key')] *= 100
</code>```

This is imho a quite nasty and cumbersome workaround. Is there any more pythonic/nicer/better way?

答:
In this case, you may be better off with get_level_values:

```<code>s = data.columns.get_level_values(-1) == 'key'
data.loc[:,s] *= 10
</code>```

Body:
In numpy we can select the last axis with ellipsis indexing, f.i. array[..., 4].

In Pandas DataFrames for structuring large amounts of data, I like to use MultiIndex (which I see as some kind of additional dimensions of the DataFrame). If I want to select a given subset of a DataFrame df, in this case all columns 'key' in the last level of the columns MultiIndex, I can do it with the cross selection method xs:

# create sample multiindex dataframe
mi = pd.MultiIndex.from_product((('a', 'b', 'c'), (1, 2), ('some', 'key', 'foo')))
data = pd.DataFrame(data=np.random.rand(20, 18), columns=mi)

# make cross selection:
xs_df = data.xs('key', axis=1, level=-1)

But if I want to assign values to the cross selection, xs won't work.

The documentation proposes to use IndexSlice to access and set values to a cross selection:

idx = pd.IndexSlice
data.loc[:, idx[:, :, 'key']] *= 10

Which is working well as long as I explicitly enter the number of levels by inserting the correct amount of : before 'key'.

Assuming I just want to give the number of levels to a selection function or f.i. always select the last level, independent of the number of levels of the DataFrame, this won't work (afaik).

My current workaround is using None slices for n_levels to skip:

n_levels = data.columns.nlevels - 1  # assuming I want to select the last level
data.loc[:, (*n_levels*[slice(None)], 'key')] *= 100

This is imho a quite nasty and cumbersome workaround. Is there any more pythonic/nicer/better way?

Body:
In this case, you may be better off with get_level_values:

s = data.columns.get_level_values(-1) == 'key'
data.loc[:,s] *= 10


问:
Delphi TTable.Exists fails on Paradox table even if database tables exist
When I create a table object (Table1) from scratch and assign the TableName property to an existing table on disk, the Table1.Exist function fails. I'm using Delphi2010 and it is a Paradox 7 table.

```<code>filename := ZipMaster1.DirEntry[i].FileName;
if Pos('.DB', UpperCase(filename)) > 0 then
begin
  Table1 := TTable.Create(FormArchiveFileSelector);
  Table1.TableName := IncludeTrailingPathDelimiter(ExtractDir) + ExtractFileName(filename);
  if Table1.Exists then
    Table1.DeleteTable;
  Table1.Free;
end;
</code>```

When I replace Table1.Exists with FileExists(Table1.TableName), this returns true. Does anyone have any explanantion for this?

Solution code

Followed suggestions, below is some 'correct' sample code:

```<code>filename := 'C:\Temp\tables\XXX_1.db';
Table1.DatabaseName := ExtractFilePath(filename);
Table1.Tablename := ExtractFileName(filename);
if Table1.Exists then MessageDlg('Exists', mtInformation, [mbOK], 0)
else MessageDlg('Missing', mtInformation, [mbOK], 0);
</code>```

Note: Even setting Table1.Tablename to the full path and tablename while setting DatabaseName properly cause the Exists function to fail. TableName must be without the path, always.

答:
You need to separately set the DatabaseName and FileName. </p>

```<code>Table1 := TTable.Create(whatever);
Table1.DatabaseName := ExtractDir;
Table1.TableName := ExtractFileName(filename);
</code>```

<p>(You should really get away from the BDE and Paradox files (as well as TTable). The BDE has been deprecated for more than a decade now, and may not ship in future versions of Delphi. There are serious issues with the latest versions of Windows as well.)</p>

ContentLicense: CC BY-SA 3.0

Body:
When I create a table object (Table1) from scratch and assign the TableName property to an existing table on disk, the Table1.Exist function fails. I'm using Delphi2010 and it is a Paradox 7 table.

filename := ZipMaster1.DirEntry[i].FileName;
if Pos('.DB', UpperCase(filename)) > 0 then
begin
  Table1 := TTable.Create(FormArchiveFileSelector);
  Table1.TableName := IncludeTrailingPathDelimiter(ExtractDir) + ExtractFileName(filename);
  if Table1.Exists then
    Table1.DeleteTable;
  Table1.Free;
end;

When I replace Table1.Exists with FileExists(Table1.TableName), this returns true. Does anyone have any explanantion for this?

Solution code

Followed suggestions, below is some 'correct' sample code:

filename := 'C:\Temp\tables\XXX_1.db';
Table1.DatabaseName := ExtractFilePath(filename);
Table1.Tablename := ExtractFileName(filename);
if Table1.Exists then MessageDlg('Exists', mtInformation, [mbOK], 0)
else MessageDlg('Missing', mtInformation, [mbOK], 0);

Note: Even setting Table1.Tablename to the full path and tablename while setting DatabaseName properly cause the Exists function to fail. TableName must be without the path, always.

Body:
You need to separately set the DatabaseName and FileName.

Table1 := TTable.Create(whatever);
Table1.DatabaseName := ExtractDir;
Table1.TableName := ExtractFileName(filename);

(You should really get away from the BDE and Paradox files (as well as TTable). The BDE has been deprecated for more than a decade now, and may not ship in future versions of Delphi. There are serious issues with the latest versions of Windows as well.)


问:
Contact Form 7 add line breaks in multiple checkboxes in email
I have a CF7 form where I have multiple checkboxes and the user has to select at least one option. Here is the code I'm using.

[checkbox* checkbox-380 use_label_element "option1" "option2" "option3"]

Everything is working. But when the form is submitted the result in the email display the selected checkboxes in one line separated by commas like below:

option1, option2, option3.

But I want each item to be displayed in a new line like this:

option1
option2
option3

Is it doable?

Thanks in advance.

答:
Just add is in your custom css:</p>

```<code>span.wpcf7-list-item {display: block;}
</code>```

Body:
Just add is in your custom css:

span.wpcf7-list-item {display: block;}


答:
I think you are looking for this.

   function add(a){
 func  = function(b){
  func.result+=b;
  return func;
 }
  func.result = a;
  return func;
 }
console.log(add(2)(2).result);```

Each sequential call returns the same function again. You can do it infinitely and access result as property of the returned function.

Title: Is there a way I can create infinite closures in JavaScript

Body:
I was presented with question and I had no idea how to do it

add() - > returns 0

add(1)() -> returns 1

add(1)(2)() -> returns 3

add(1)(2)(3)(4)() -> 10

Basically it can go on

Body:
I think you are looking for this.

   function add(a){
 func  = function(b){
  func.result+=b;
  return func;
 }
  func.result = a;
  return func;
 }
console.log(add(2)(2).result);

Each sequential call returns the same function again. You can do it infinitely and access result as property of the returned function.


问:
How can I make a a dialog box happen directly after my app's main form is visible?
I have been using TForm's OnActivate event to give me the opportunity to show a dialog box as soon as my app has started.  I want the main form to already be loaded & visible.  What's a good way to do this?

I have found that OnActivate works fine unless the forms WindowState is wsMaximized.

in the past I've accomplished what I want in various ways but I expect there is a better way.

Here's what worked for me:

```<code>procedure TForm1.FormCreate(Sender: TObject);
begin
  Application.OnIdle:=OnIdle;
end;

procedure TForm1.OnIdle(Sender: TObject; var Done: Boolean);
begin
  Application.OnIdle:=nil;
  form2:=TForm2.Create(Application);
  form2.ShowModal;
end;
</code>```

Is there a better way?

答:
I was shown the following method of doing this long ago and it's always worked for me.

In your main form OnCreate method, after you've done anything you might normally do in this method, add the following line:

Self.Show;

This will display the main form.

Then, after that, enter the code to display your dialog box.

When run, your main form will display followed immediately by your dialog box.

Body:
I have been using TForm's OnActivate event to give me the opportunity to show a dialog box as soon as my app has started.  I want the main form to already be loaded & visible.  What's a good way to do this?

I have found that OnActivate works fine unless the forms WindowState is wsMaximized.

in the past I've accomplished what I want in various ways but I expect there is a better way.

Here's what worked for me:

procedure TForm1.FormCreate(Sender: TObject);
begin
  Application.OnIdle:=OnIdle;
end;

procedure TForm1.OnIdle(Sender: TObject; var Done: Boolean);
begin
  Application.OnIdle:=nil;
  form2:=TForm2.Create(Application);
  form2.ShowModal;
end;

Is there a better way?


问:
Is there performance/compiler benefits when using tuple vs struct whenever possible?
Is there performance/compiler benefits when using tuple vs struct whenever possible?

For example in this case where

you don't need protocol conformance,

you don't need functions,

all variables are readonly.

.

```<code>typealias SomeModel = (
    name: String,
    id: String
)
</code>```

vs

```<code>struct SomeModel {
    let name: String
    let id: String
}
</code>```

答:
Create following function to calculate a time for operations. Put blocks of your code as its argument and try to see a difference by yourself:</p>

```<code>func duration(_ block: () -> ()) -> TimeInterval {
  let startTime = Date()
  block()
  return Date().timeIntervalSince(startTime)
}
</code>```

Body:
Is there performance/compiler benefits when using tuple vs struct whenever possible?

For example in this case where

you don't need protocol conformance,

you don't need functions,

all variables are readonly.

.

typealias SomeModel = (
    name: String,
    id: String
)

vs

struct SomeModel {
    let name: String
    let id: String
}

Body:
Create following function to calculate a time for operations. Put blocks of your code as its argument and try to see a difference by yourself:

func duration(_ block: () -> ()) -> TimeInterval {
  let startTime = Date()
  block()
  return Date().timeIntervalSince(startTime)
}


问:
Create a column to indicate the presence of a value in other columns
I have a dataset with symptoms (20+), the symptoms are categorized as Yes/No/Unknown. I would like to create a new column which indicates if the subject (ID) has no symptoms (I'm defining this as they have no symptoms with 'Yes').

I've got a sample dataset below and I can create a column as desired but it feels like there must be a better/cleaner way just using dplyr::mutate() rather than the filtering and joining that I'm doing?

library(dplyr)

test <- tibble(
  ID = c(1:10),
  col1 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE),
  col2 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE),
  col3 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE)
)

left_join(test, test %>%
  filter_at(vars(col1:col3), any_vars(. == "Yes")) %>%
  mutate(any_symptoms = "Yes") %>%
  select(ID, any_symptoms),
by = "ID"
) %>%
  mutate(any_symptoms = recode(any_symptoms, .missing = "No"))
#> # A tibble: 10 x 5
#>       ID col1    col2    col3    any_symptoms
#>    <int> <chr>   <chr>   <chr>   <chr>
#>  1     1 Unknown Unknown Unknown No
#>  2     2 Unknown No      No      No
#>  3     3 Yes     Yes     Unknown Yes
#>  4     4 No      Unknown Unknown No
#>  5     5 No      No      Unknown No
#>  6     6 Unknown Yes     Unknown Yes
#>  7     7 Yes     Unknown Unknown Yes
#>  8     8 No      No      No      No
#>  9     9 No      Unknown Unknown No
#> 10    10 No      No      No      No
```

Created on 2020-05-29 by the reprex package (v0.3.0)

答:
This should work:</p>

```<code>test %>%
  left_join(
    test %>%
      pivot_longer(-ID) %>%
      group_by(ID) %>%
      mutate(is_yes = value == "Yes") %>%
      summarise(any_symptoms = ifelse(sum(is_yes) > 0, "Yes", "No"))
  )
</code>```

Body:
I have a dataset with symptoms (20+), the symptoms are categorized as Yes/No/Unknown. I would like to create a new column which indicates if the subject (ID) has no symptoms (I'm defining this as they have no symptoms with 'Yes').

I've got a sample dataset below and I can create a column as desired but it feels like there must be a better/cleaner way just using dplyr::mutate() rather than the filtering and joining that I'm doing?

library(dplyr)

test <- tibble(
  ID = c(1:10),
  col1 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE),
  col2 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE),
  col3 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE)
)

left_join(test, test %>%
  filter_at(vars(col1:col3), any_vars(. == "Yes")) %>%
  mutate(any_symptoms = "Yes") %>%
  select(ID, any_symptoms),
by = "ID"
) %>%
  mutate(any_symptoms = recode(any_symptoms, .missing = "No"))
#> # A tibble: 10 x 5
#>       ID col1    col2    col3    any_symptoms
#>    <int> <chr>   <chr>   <chr>   <chr>
#>  1     1 Unknown Unknown Unknown No
#>  2     2 Unknown No      No      No
#>  3     3 Yes     Yes     Unknown Yes
#>  4     4 No      Unknown Unknown No
#>  5     5 No      No      Unknown No
#>  6     6 Unknown Yes     Unknown Yes
#>  7     7 Yes     Unknown Unknown Yes
#>  8     8 No      No      No      No
#>  9     9 No      Unknown Unknown No
#> 10    10 No      No      No      No

Created on 2020-05-29 by the reprex package (v0.3.0)

Body:
This should work:

test %>%
  left_join(
    test %>%
      pivot_longer(-ID) %>%
      group_by(ID) %>%
      mutate(is_yes = value == "Yes") %>%
      summarise(any_symptoms = ifelse(sum(is_yes) > 0, "Yes", "No"))
  )


问:
How to give numbers to row that reset every time the value of another column changes?
this is probably a simple question, but I want to create row numbers based on the values in the column.

It would look like this:

```<code>1 | AAA
2 | AAA
3 | AAA
1 | BBB
2 | BBB
1 | CCC
2 | CCC
3 | CCC
4 | CCC
1 | DDD
2 | DDD
</code>```

I don't really know how to word my question since my first language isn't english, but what would be the function or steps to take to achieve that?

答:
The answer that I found from @BigBen is this:

=IF(A2=A1,B1+1,1)

https://superuser.com/questions/631644/count-the-number-of-sequential-duplicates-excel

Body:
this is probably a simple question, but I want to create row numbers based on the values in the column.

It would look like this:

1 | AAA
2 | AAA
3 | AAA
1 | BBB
2 | BBB
1 | CCC
2 | CCC
3 | CCC
4 | CCC
1 | DDD
2 | DDD

I don't really know how to word my question since my first language isn't english, but what would be the function or steps to take to achieve that?


答:
I use this cheme for slove my problem:</p>

```<code>  {
    "operation": "shift",
    "spec": {
        "*": {
              "@": "",
              "cancelInfo": {
                "cancelDate": "cancelInfo_cancelDate",
                "cancelReason": "cancelInfo_cancelReason"
              }
      }
    }
  }
</code>```

Title: JOLT transform: sub-object to top object

Body:
I use Apache NIFI. I need transform JSON in JSON with JoltTransformJSON processor.
I have JSON:

[ {
  "code" : "01.11.11.111-00001",
  "version" : "1",
  "inclusionDate" : "2018-06-16T05:53:14+04:00",
  "publishDate" : "2018-06-16T05:53:14+04:00",
  "name" : "????",
  "actual" : "false",
  "applicationDateStart" : "2018-06-16T00:00:00+04:00",
  "applicationDateEnd" : "2018-06-16T00:00:00+04:00",
  "cancelInfo" : {
    "cancelDate" : "2018-06-17T00:00:00+04:00",
    "cancelReason" : "????????? ???? ????????? ?????????? ??????? ????."
  },
  "nsiDescription" : "",
  "isTemplate" : "false",
  "noNewFeatures" : "false"
}, {
  "code" : "01.11.11.111-00002",
  "version" : "1",
  "inclusionDate" : "2018-06-21T04:21:14+04:00",
  "publishDate" : "2018-06-21T04:21:14+04:00",
  "name" : "????",
  "actual" : "false",
  "applicationDateStart" : "2018-06-21T00:00:00+04:00",
  "applicationDateEnd" : "2018-06-22T00:00:00+04:00",
  "cancelInfo" : {
    "cancelDate" : "2018-06-22T00:00:00+04:00",
    "cancelReason" : "????????? ???? ????????? ?????????? ??????? ????."
  },
  "isTemplate" : "false",
  "noNewFeatures" : "false"
} ]

How I can transform this part of JSON

  "cancelInfo" : {
    "cancelDate" : "2018-06-22T00:00:00+04:00",
    "cancelReason" : "????????? ???? ????????? ?????????? ??????? ????."
  },

In this JSON. Transform with JOLT.

[ {
  "code" : "01.11.11.111-00001",
  "version" : "1",
  "inclusionDate" : "2018-06-16T05:53:14+04:00",
  "publishDate" : "2018-06-16T05:53:14+04:00",
  "name" : "????",
  "actual" : "false",
  "applicationDateStart" : "2018-06-16T00:00:00+04:00",
  "applicationDateEnd" : "2018-06-16T00:00:00+04:00",
  "cancelDate" : "2018-06-17T00:00:00+04:00",
  "cancelReason" : "????????? ???? ????????? ?????????? ??????? ????.",
  "nsiDescription" : "",
  "isTemplate" : "false",
  "noNewFeatures" : "false"
}, {
  "code" : "01.11.11.111-00002",
  "version" : "1",
  "inclusionDate" : "2018-06-21T04:21:14+04:00",
  "publishDate" : "2018-06-21T04:21:14+04:00",
  "name" : "????",
  "actual" : "false",
  "applicationDateStart" : "2018-06-21T00:00:00+04:00",
  "applicationDateEnd" : "2018-06-22T00:00:00+04:00",
  "cancelDate" : "cancelDate" : "2018-06-22T00:00:00+04:00",
  "cancelReason" : "????????? ???? ????????? ?????????? ??????? ????.",
  "isTemplate" : "false",
  "noNewFeatures" : "false"
} ]

I can't make a JOLT specification. Tell me also where you can see its full description, I can't find it.

Body:
I use this cheme for slove my problem:

  {
    "operation": "shift",
    "spec": {
        "*": {
              "@": "",
              "cancelInfo": {
                "cancelDate": "cancelInfo_cancelDate",
                "cancelReason": "cancelInfo_cancelReason"
              }
      }
    }
  }


问:
gcp datacatalog_v1beta1 create taxonomy and policy tags failed
I am trying to use Python Client for Google Cloud Data Catalog API beta 1 to create taxonomy and policy tags. here is my code:

```<code>from google.cloud.datacatalog_v1beta1 import PolicyTagManagerClient, enums, types
from google.oauth2 import service_account

key_path = "./xxxxx.json"
credentials = service_account.Credentials.from_service_account_file(
    key_path,
    scopes=["https://www.googleapis.com/auth/cloud-platform"],
)

client = PolicyTagManagerClient(credentials=credentials)
resource_name = '//bigquery.googleapis.com/projects/{}/locations/us/taxonomies/{}'.format('3xxxxxxxx58','50xxxxxxxxx14')
taxonomy = client.get_taxonomy(resource_name)
print(taxonomy)

pt_taxonomy = types.Taxonomy()
pt_taxonomy.display_name = 'PHI'
response = client.create_taxonomy(parent=<project_id>, taxonomy=pt_taxonomy)
</code>```

I get following error for get_taxonomy()

```<code>google.api_core.exceptions.MethodNotImplemented: 501 Operation is not implemented, or supported, or enabled.
</code>```

and for create_taxonomy() I got:

```<code>"Received http2 header with status: 404","grpc_status":1,"value":"404"}"
</code>```

any idea?
Thank you for your help!

BTW google api call does work, it returns 200 with following example.

So I changed my code to:

```<code>pt_taxonomy1 = types.Taxonomy()
pt_taxonomy1.display_name = 'PHI1'

response = client.create_taxonomy('projects/39xxxxx/locations/us', pt_taxonomy1)
</code>```

still same 501 error

答:
@hdu, I filed a bug describing the 501 error in the client library repository: https://github.com/googleapis/python-datacatalog/issues/33.
[EDITED] This bug has been fixed.

In spite of the 501 error, I believe there's another minor issue in your script:

resource_name = '//bigquery.googleapis.com/projects/{}/locations/us/taxonomies/{}'.format('3xxxxxxxx58','50xxxxxxxxx14')
taxonomy = client.get_taxonomy(resource_name)

GET Taxonomy expects the resource name of the requested taxonomy as an argument, formatted as projects/{project_id}/locations/{location_id}/taxonomies/{taxonomies_id} (source).

Body:
I am trying to use Python Client for Google Cloud Data Catalog API beta 1 to create taxonomy and policy tags. here is my code:

from google.cloud.datacatalog_v1beta1 import PolicyTagManagerClient, enums, types
from google.oauth2 import service_account

key_path = "./xxxxx.json"
credentials = service_account.Credentials.from_service_account_file(
    key_path,
    scopes=["https://www.googleapis.com/auth/cloud-platform"],
)

client = PolicyTagManagerClient(credentials=credentials)
resource_name = '//bigquery.googleapis.com/projects/{}/locations/us/taxonomies/{}'.format('3xxxxxxxx58','50xxxxxxxxx14')
taxonomy = client.get_taxonomy(resource_name)
print(taxonomy)

pt_taxonomy = types.Taxonomy()
pt_taxonomy.display_name = 'PHI'
response = client.create_taxonomy(parent=<project_id>, taxonomy=pt_taxonomy)

I get following error for get_taxonomy()

google.api_core.exceptions.MethodNotImplemented: 501 Operation is not implemented, or supported, or enabled.

and for create_taxonomy() I got:

"Received http2 header with status: 404","grpc_status":1,"value":"404"}"

any idea?
Thank you for your help!

BTW google api call does work, it returns 200 with following example.

So I changed my code to:

pt_taxonomy1 = types.Taxonomy()
pt_taxonomy1.display_name = 'PHI1'

response = client.create_taxonomy('projects/39xxxxx/locations/us', pt_taxonomy1)

still same 501 error


问:
Gremlin traversal queries on spark graph
I have build a property graph(60 million nodes, 40 million edges) from s3 using Apache Spark Graphx framework.
I want to fire traversal queries on this graph.

My queries will be like:-

```<code>g.V().has("name","xyz").out('parent').out().has('name','abc')
</code>```

```<code>g.V().has('proc_name','serv.exe').out('file_create').
has('file_path',containing('Tsk04.txt')).in().in('parent').values('proc_name')
</code>```

```<code>g.V().has('md5','935ca12348040410e0b2a8215180474e').values('files')
</code>```

mostly queries are of form g.V().out().out().out()

Such queries are easily possible on graph db's like neo4j,titan,aws neptune since they support gremlin.

Can we traverse spark graphs in such manner.
I tried spark pregel-api but its bit complex as compared to gremlin.

Reason I am looking for spark graph is because cloud solutions of above mentioned graphdbs is costly.

答:
Spark GraphFrames library should be most convenient for you. it provides neo4j-cypher-like traversal description and use Spark DataFrames api for filtering

https://graphframes.github.io/graphframes/docs/_site/user-guide.html#motif-finding
Here is an example:

```<code>val g2: GraphFrame = GraphFrame.fromGraphX(gx) // you can start with just V and E DataFrames here
val motifs: GraphFrame = g.find("(a)-[e]->(b); (b)-[e2]->(c)")
motifs.filter("a.name = 'xyz'  and e.label = 'parent' and c.name = 'abc'").show()
</code>```

TinkerPop it self has spark support, so you can issue spark OLAP queries from gremlin console
https://tinkerpop.apache.org/docs/current/reference/#sparkgraphcomputer

Or there are some close source solutions. Datastax Enterprise Database has a good Gremlin support for spark: https://www.datastax.com/blog/2017/05/introducing-dse-graph-frames
I'm a former author of it

Body:
I have build a property graph(60 million nodes, 40 million edges) from s3 using Apache Spark Graphx framework.
I want to fire traversal queries on this graph.

My queries will be like:-

g.V().has("name","xyz").out('parent').out().has('name','abc')

g.V().has('proc_name','serv.exe').out('file_create').
has('file_path',containing('Tsk04.txt')).in().in('parent').values('proc_name')

g.V().has('md5','935ca12348040410e0b2a8215180474e').values('files')

mostly queries are of form g.V().out().out().out()

Such queries are easily possible on graph db's like neo4j,titan,aws neptune since they support gremlin.

Can we traverse spark graphs in such manner.
I tried spark pregel-api but its bit complex as compared to gremlin.

Reason I am looking for spark graph is because cloud solutions of above mentioned graphdbs is costly.

Body:
Spark GraphFrames library should be most convenient for you. it provides neo4j-cypher-like traversal description and use Spark DataFrames api for filtering

https://graphframes.github.io/graphframes/docs/_site/user-guide.html#motif-finding
Here is an example:

val g2: GraphFrame = GraphFrame.fromGraphX(gx) // you can start with just V and E DataFrames here
val motifs: GraphFrame = g.find("(a)-[e]->(b); (b)-[e2]->(c)")
motifs.filter("a.name = 'xyz'  and e.label = 'parent' and c.name = 'abc'").show()

TinkerPop it self has spark support, so you can issue spark OLAP queries from gremlin console
https://tinkerpop.apache.org/docs/current/reference/#sparkgraphcomputer

Or there are some close source solutions. Datastax Enterprise Database has a good Gremlin support for spark: https://www.datastax.com/blog/2017/05/introducing-dse-graph-frames
I'm a former author of it


问:
Why are double-quotes urlencoded as %22?
As far as I know, URL encoding exists because URLs only support ASCII encoding. But since " is already in the ASCII table, why should it be encoded as %22 in URL encoding?

答:
URLs only support ASCII encoding

That's not true. URL's don't support spaces or / or & or ? for example even though they are valid ASCII characters because they have special meaning in URLs.

Valid characters in URLs are:

A-Z

a-z

0-9

-

_

.

~

Other characters are not supported. Some, such as spaces and tabs are not supported because they have special meaning in protocols that usually use URLs such as HTTP. Others such as ? and & are not supported because they have special meaning in URL syntax.


问:
json array return as count in a key javascript
i have a json object that has json array inside

```<code>{
  "0": [
    {
      "accountId": "2020060",
      "status": "0"
    }
  ],
  "1": [
    {
      "accountId": "2020025",
      "status": "1"
    },
    {
      "accountId": "2020027",
      "status": "1"
    },
    {
      "accountId": "2020057",
      "status": "1"
    }
  ],
}
</code>```

how can i convert the json array into count so that the response would look like this?

```<code>{
   "0" : "1",
   "1" : "3"
}
</code>```

答:
I use Object.keys and reduce.</p>

```<code>const arr ={
  "0": [
    {
      "accountId": "2020060",
      "status": "0"
    }
  ],
  "1": [
    {
      "accountId": "2020025",
      "status": "1"
    },
    {
      "accountId": "2020027",
      "status": "1"
    },
    {
      "accountId": "2020057",
      "status": "1"
    }
  ],
}

const newArr = Object.keys(arr).reduce((acc, rec) => {
  return { ...acc, [rec]: arr[rec].length }
}, [])

display.log(newArr)
</code>```

Body:
i have a json object that has json array inside

{
  "0": [
    {
      "accountId": "2020060",
      "status": "0"
    }
  ],
  "1": [
    {
      "accountId": "2020025",
      "status": "1"
    },
    {
      "accountId": "2020027",
      "status": "1"
    },
    {
      "accountId": "2020057",
      "status": "1"
    }
  ],
}

how can i convert the json array into count so that the response would look like this?

{
   "0" : "1",
   "1" : "3"
}

Body:
I use Object.keys and reduce.

const arr ={
  "0": [
    {
      "accountId": "2020060",
      "status": "0"
    }
  ],
  "1": [
    {
      "accountId": "2020025",
      "status": "1"
    },
    {
      "accountId": "2020027",
      "status": "1"
    },
    {
      "accountId": "2020057",
      "status": "1"
    }
  ],
}

const newArr = Object.keys(arr).reduce((acc, rec) => {
  return { ...acc, [rec]: arr[rec].length }
}, [])

display.log(newArr)


问:
Find Font size of an active console Window
first scripting goal I haven't been able to uncover my own solution for.

Attempts and research on how to find current font size so far:

checking wmic for a useable value:

wmic path Win32_VideoController  get * /format:value

The accepted solution for this similar question:

for /f "tokens=3" %A in ('reg query "HKEY_CURRENT_USER\Control Panel\Desktop\WindowMetrics" /v AppliedDPI') do echo %A

This solution returns the same result regardless of font size on my machines - 0x12

Searching Q&A's here on stackoverflow

Searching on Dostips

Using an external executable to force font size (BG.exe)

Not all the scripts I use this in will warrant users needing to download supporting executables

Script execution is intended for Windows 10 systems supporting ASCII escape codes

The context for needing current font size:

I've developed a routine for controlling console size and position, which remains accurate accross different resolutions, however it currently depends on values for maximum lines and columns based on an assumed font size of 16x8

With a reliable means to determine font size, I can do away with this assumption and formulate positioning using the relationship between the actual font size, maximum lines / columns and screen resolution.
I still need to determine the above relationship - if anyone already knows it, feel free to share.

::: { Subroutine to process output of wmic command into usable variables for screen dimensions (resolution)
::: - Formula based on Consolas 16x8 Font
:ChangeConsole <Lines> <Columns>  <If a 4th parameter is Defined, Aligns screen at top left>
::: - Get screen Dimensions
    For /f "delims=" %%# in  ('"wmic path Win32_VideoController  get CurrentHorizontalResolution,CurrentVerticalResolution /format:value"') do (
        Set "%%#">nul
    )
::: - Calculation of X axis relative to screen resolution and console size. Resolution scales to Max Columns ~ 165
    Set /A XresScale=CurrentHorizontalResolution / 165
    Set /A HorzCentre=CurrentHorizontalResolution / 2
    Set /A CentreX= ( HorzCentre - ( ( %~2 * XresScale ) / 2 ) ) - 8
::: - Calculation of Y axis relative to screen resolution and console size. Resolution scales to Max Lines ~ 43
    Set /A YresScale=CurrentVerticalResolution / 43
    Set /A VertCentre=CurrentVerticalResolution / 2
    Set /A CentreY=VertCentre - ( ( %~1 * YresScale ) / 2 )
::: - Optional 4th parameter can be used to align console at top left of screen instead of screen centre
    If Not "%~4"=="" (Set /A CentreY=0,CentreX=-8)
::: - Creates a batch file to reopen the main script using Call with parameters to define properties for console change and the label to resume from.
    (
    Echo.@Mode Con: lines=%~1 cols=%~2
    Echo.@Title %ProgName%
    Echo.@Call "%AlignFile%" "%~1" "%~2" "%~3" "%AlignFile%"
    )>"%temp%\ChangeConsole.bat"
::: - .Vbs script creation
    (
    Echo.Set objWMIService = GetObject^("winmgmts:\\.\root\cimv2"^)
    Echo.Set objConfig = objWMIService.Get^("Win32_ProcessStartup"^)
    Echo.objConfig.SpawnInstance_
    Echo.objConfig.X = %CentreX%
    Echo.objConfig.Y = %CentreY%
    Echo.Set objNewProcess = objWMIService.Get^("Win32_Process"^)
    Echo.intReturn = objNewProcess.Create^("%temp%\ChangeConsole.bat", Null, objConfig, intProcessID^)
    )>"%temp%\Consolepos.vbs"
::: - .Vbs Starts the companion batch script to Change Console properties, ends the parent.
    Start "" "%temp%\Consolepos.vbs" & Exit
::: }
```

A demo of the above routine

答:
I wrote this small MASM32 assembly language program to get the size of the font of the current cmd.exe window:

```<code>;   FontSize.asm: Returns the current font size of cmd.exe window - Antonio Perez Ayala

        include         \masm32\include\masm32rt.inc

    .data

CONSOLE_FONT_INFO STRUCT
  nFont                 DWORD ?
  dwFontSize            COORD <>
CONSOLE_FONT_INFO ENDS

    hConsoleOutput      DD          ?
    ConsoleCurrentFont  CONSOLE_FONT_INFO   <>

    .code

Main    PROC

        invoke  GetStdHandle, STD_OUTPUT_HANDLE                                 ;EAX = console output handle
        mov     hConsoleOutput, eax                                             ;store it
        invoke  GetCurrentConsoleFont, eax, FALSE, ADDR ConsoleCurrentFont      ;get current font info
        invoke  GetConsoleFontSize, hConsoleOutput, ConsoleCurrentFont.nFont    ;EAX = font size
        invoke  ExitProcess, eax                                                ;return it in ERRORLEVEL

Main    ENDP

        end     Main
</code>```

You may review the documentation of the WIN32 API functions used at this site.

To get the executable program copy this code into fontsize.asm source program and assembly it via MASM32 SDK package. You may also execute the following .bat Batch file and extract it from the created fontsize.zip file:

```<code>@certutil -decode "%~F0" fontsize.zip & goto :EOF

-----BEGIN CERTIFICATE-----
UEsDBBQAAAAIAMtAvVDPMRDXlAEAAAAKAAAMAAAAZm9udHNpemUuZXhl7ZI9LwRB
GMf/644cDidRUGC8JarNhaiQXOK1IDZOJYh1O3F79mZlbyTiMyjkGgWdTqVQiIoP
cIVvoJFcq1DKmtkXTgiFKMj+ss/zn+f/PDO7k+zi6hFiAOIiXBe4gk8G33MhorX3
uhWXjZW+K2Wh0reSN0tk17G3Hb1IcjpjNidblDh7jJiMTC9lSdE2qNrS0jQYnLG+
VrztmoyVwzjuT5V7hD50t5c7hS6bubz0w3dqM8CCEkMlcbcRevdoU5qV+iTq4F9E
kgqCyCLjr+ve2qF6Fw2KWLgxVauv4tFBgGH8AkSc/UVb5XSfC52XRQp4d9cAAmyq
jqFzHTgPDG+u4f1cRjyqP4akNNLBXOLD3A0i/jWFp+q4kDOkM8jHRSpAqw4Ixx2T
lTsmG1X5l2hVOe8OJYmwh+DluJcTIkf8TTYIwEUcitCI702Qt/6pXNfUtXy29wQz
+ybXHDtHSyU8Yo7yKZuVbIvO2oxnzQMKPHvunuNQVttEQRF+lhvzOjMsMbdDHUat
0RHVsKzPvyAiIuInvABQSwECFAAUAAAACADLQL1QzzEQ15QBAAAACgAADAAAAAAA
AAAAACAAAAAAAAAAZm9udHNpemUuZXhlUEsFBgAAAAABAAEAOgAAAL4BAAAAAA==
-----END CERTIFICATE-----
</code>```

fontsize.exe program returns the font size via %ERRORLEVEL% value. For example:

```<code>C:\Users\Antonio\Documents\ASMB\MASM32 Assembler for Windows
> fontsize.exe

C:\Users\Antonio\Documents\ASMB\MASM32 Assembler for Windows
> set /A "height=%errorlevel% >> 16, width=%errorlevel% & 0xFF"
8

C:\Users\Antonio\Documents\ASMB\MASM32 Assembler for Windows
> echo The font size is %width% x %height%
The font size is 8 x 16
</code>```

Body:
first scripting goal I haven't been able to uncover my own solution for.

Attempts and research on how to find current font size so far:

checking wmic for a useable value:

wmic path Win32_VideoController  get * /format:value

The accepted solution for this similar question:

for /f "tokens=3" %A in ('reg query "HKEY_CURRENT_USER\Control Panel\Desktop\WindowMetrics" /v AppliedDPI') do echo %A

This solution returns the same result regardless of font size on my machines - 0x12

Searching Q&A's here on stackoverflow

Searching on Dostips

Using an external executable to force font size (BG.exe)

Not all the scripts I use this in will warrant users needing to download supporting executables

Script execution is intended for Windows 10 systems supporting ASCII escape codes

The context for needing current font size:

I've developed a routine for controlling console size and position, which remains accurate accross different resolutions, however it currently depends on values for maximum lines and columns based on an assumed font size of 16x8

With a reliable means to determine font size, I can do away with this assumption and formulate positioning using the relationship between the actual font size, maximum lines / columns and screen resolution.
I still need to determine the above relationship - if anyone already knows it, feel free to share.

::: { Subroutine to process output of wmic command into usable variables for screen dimensions (resolution)
::: - Formula based on Consolas 16x8 Font
:ChangeConsole <Lines> <Columns>  <If a 4th parameter is Defined, Aligns screen at top left>
::: - Get screen Dimensions
    For /f "delims=" %%# in  ('"wmic path Win32_VideoController  get CurrentHorizontalResolution,CurrentVerticalResolution /format:value"') do (
        Set "%%#">nul
    )
::: - Calculation of X axis relative to screen resolution and console size. Resolution scales to Max Columns ~ 165
    Set /A XresScale=CurrentHorizontalResolution / 165
    Set /A HorzCentre=CurrentHorizontalResolution / 2
    Set /A CentreX= ( HorzCentre - ( ( %~2 * XresScale ) / 2 ) ) - 8
::: - Calculation of Y axis relative to screen resolution and console size. Resolution scales to Max Lines ~ 43
    Set /A YresScale=CurrentVerticalResolution / 43
    Set /A VertCentre=CurrentVerticalResolution / 2
    Set /A CentreY=VertCentre - ( ( %~1 * YresScale ) / 2 )
::: - Optional 4th parameter can be used to align console at top left of screen instead of screen centre
    If Not "%~4"=="" (Set /A CentreY=0,CentreX=-8)
::: - Creates a batch file to reopen the main script using Call with parameters to define properties for console change and the label to resume from.
    (
    Echo.@Mode Con: lines=%~1 cols=%~2
    Echo.@Title %ProgName%
    Echo.@Call "%AlignFile%" "%~1" "%~2" "%~3" "%AlignFile%"
    )>"%temp%\ChangeConsole.bat"
::: - .Vbs script creation
    (
    Echo.Set objWMIService = GetObject^("winmgmts:\\.\root\cimv2"^)
    Echo.Set objConfig = objWMIService.Get^("Win32_ProcessStartup"^)
    Echo.objConfig.SpawnInstance_
    Echo.objConfig.X = %CentreX%
    Echo.objConfig.Y = %CentreY%
    Echo.Set objNewProcess = objWMIService.Get^("Win32_Process"^)
    Echo.intReturn = objNewProcess.Create^("%temp%\ChangeConsole.bat", Null, objConfig, intProcessID^)
    )>"%temp%\Consolepos.vbs"
::: - .Vbs Starts the companion batch script to Change Console properties, ends the parent.
    Start "" "%temp%\Consolepos.vbs" & Exit
::: }

A demo of the above routine

Body:
I wrote this small MASM32 assembly language program to get the size of the font of the current cmd.exe window:

;   FontSize.asm: Returns the current font size of cmd.exe window - Antonio Perez Ayala

        include         \masm32\include\masm32rt.inc

    .data

CONSOLE_FONT_INFO STRUCT
  nFont                 DWORD ?
  dwFontSize            COORD <>
CONSOLE_FONT_INFO ENDS

    hConsoleOutput      DD          ?
    ConsoleCurrentFont  CONSOLE_FONT_INFO   <>

    .code

Main    PROC

        invoke  GetStdHandle, STD_OUTPUT_HANDLE                                 ;EAX = console output handle
        mov     hConsoleOutput, eax                                             ;store it
        invoke  GetCurrentConsoleFont, eax, FALSE, ADDR ConsoleCurrentFont      ;get current font info
        invoke  GetConsoleFontSize, hConsoleOutput, ConsoleCurrentFont.nFont    ;EAX = font size
        invoke  ExitProcess, eax                                                ;return it in ERRORLEVEL

Main    ENDP

        end     Main

You may review the documentation of the WIN32 API functions used at this site.

To get the executable program copy this code into fontsize.asm source program and assembly it via MASM32 SDK package. You may also execute the following .bat Batch file and extract it from the created fontsize.zip file:

@certutil -decode "%~F0" fontsize.zip & goto :EOF

-----BEGIN CERTIFICATE-----
UEsDBBQAAAAIAMtAvVDPMRDXlAEAAAAKAAAMAAAAZm9udHNpemUuZXhl7ZI9LwRB
GMf/644cDidRUGC8JarNhaiQXOK1IDZOJYh1O3F79mZlbyTiMyjkGgWdTqVQiIoP
cIVvoJFcq1DKmtkXTgiFKMj+ss/zn+f/PDO7k+zi6hFiAOIiXBe4gk8G33MhorX3
uhWXjZW+K2Wh0reSN0tk17G3Hb1IcjpjNidblDh7jJiMTC9lSdE2qNrS0jQYnLG+
VrztmoyVwzjuT5V7hD50t5c7hS6bubz0w3dqM8CCEkMlcbcRevdoU5qV+iTq4F9E
kgqCyCLjr+ve2qF6Fw2KWLgxVauv4tFBgGH8AkSc/UVb5XSfC52XRQp4d9cAAmyq
jqFzHTgPDG+u4f1cRjyqP4akNNLBXOLD3A0i/jWFp+q4kDOkM8jHRSpAqw4Ixx2T
lTsmG1X5l2hVOe8OJYmwh+DluJcTIkf8TTYIwEUcitCI702Qt/6pXNfUtXy29wQz
+ybXHDtHSyU8Yo7yKZuVbIvO2oxnzQMKPHvunuNQVttEQRF+lhvzOjMsMbdDHUat
0RHVsKzPvyAiIuInvABQSwECFAAUAAAACADLQL1QzzEQ15QBAAAACgAADAAAAAAA
AAAAACAAAAAAAAAAZm9udHNpemUuZXhlUEsFBgAAAAABAAEAOgAAAL4BAAAAAA==
-----END CERTIFICATE-----

fontsize.exe program returns the font size via %ERRORLEVEL% value. For example:

C:\Users\Antonio\Documents\ASMB\MASM32 Assembler for Windows
> fontsize.exe

C:\Users\Antonio\Documents\ASMB\MASM32 Assembler for Windows
> set /A "height=%errorlevel% >> 16, width=%errorlevel% & 0xFF"
8

C:\Users\Antonio\Documents\ASMB\MASM32 Assembler for Windows
> echo The font size is %width% x %height%
The font size is 8 x 16


问:
I am having problem with if statement in dart

child: RaisedButton(
    onPressed: () {
      if (_formKey.currentState.validate()) {
        double angle = double.parse(a.text);

        print(angle);
        if (v.text != null) {
          double velocity = double.parse(v.text);
          print(velocity);
        } else if (h.text != null) {
          double height = double.parse(h.text);
          print(height);
          print(angle);
        } else if (t.text != null) {
          double time = double.parse(t.text);
          print(time);
          print(angle);
        }
      }
    },
```

In the following code when I keep v.text empty it still reads the if statement and not jump to else if part while i validate the form. i don't know why it is doing this please help me out

答:
Instead of v.text != null

do v.text.isNotEmpty

Body:
child: RaisedButton(
    onPressed: () {
      if (_formKey.currentState.validate()) {
        double angle = double.parse(a.text);

        print(angle);
        if (v.text != null) {
          double velocity = double.parse(v.text);
          print(velocity);
        } else if (h.text != null) {
          double height = double.parse(h.text);
          print(height);
          print(angle);
        } else if (t.text != null) {
          double time = double.parse(t.text);
          print(time);
          print(angle);
        }
      }
    },

In the following code when I keep v.text empty it still reads the if statement and not jump to else if part while i validate the form. i don't know why it is doing this please help me out


问:
Can managed code perform computations as fast as unmamanged?
I've been interested in different chess engines lately. There are many open and closed sources project in this field. They are all (most of them anyway) written in C/C++. This is kind of an obvious thing - you have a computationally intensive task, you use C/C++ so you get both portability and speed. This seems like a no-brainier.

However, I would like to question that idea. When .NET first appeared, there were many people saying that .NET idea would not work because .NET programs were doomed to be super-slow. In reality this did not happen. Somebody did a good job with the VM, JIT, etc and we have decent performance for most tasks now. But not all. Microsoft never promised that .NET will be suitable for all task and admitted for some tasks you will still need C/C++.

Going back to the question of computationally heavy task - is there a way to write a .NET program so that it does not perform computations considerably worse that an unmanaged code using the same algorithms? I'd be happy with "constant" speed loss, but anything worse than that is going to be a problem.

What do you think? Can we be close in speed to unmanaged code for computations in managed code, or unmanaged code is the only viable answer? If we can, how? If we can't why?

Update:  a lot of good feedback here. I'm going to accept the most up-voted answer.

答:
Short answer yes, long answer with enough work.

There are high frequency trading applications written in managed C# .NET. Very few other applications ever approach the time criticalness as a trading engine requires. The overall concept is you develop software that is extremely efficient that your application will not need the garbage collector to ever invoke itself for non generation 0 objects. If at any point the garbage collector kicks in you have a massive (in computing terms of time) lag lasting dozens or hundreds of milliseconds which would be unacceptable.


问:
Principal Error in AD when user is in group?
I have the following code, which works fine, as long as the user isn't in defined group (groupName)

all values are defined in this function or somewhere else and are implemented correctly, the values are correct in this function:

```<code>    public void AddUserToGroup(string userId, string groupName)
    {

        string ss = Password();
        bool bSuccess = false;

        try
        {
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "lhw-nt.local", null, "lhw-nt\\administrator", ss))
            {
                GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);
                group.Members.Add(pc, IdentityType.UserPrincipalName, userId);
                group.Save();

                bSuccess = true;
            }
        } catch (DirectoryServicesCOMException e)
        {
            MessageBox.Show(e.ToString(), "Fehler");
        }

        if(bSuccess)
        {
            MessageBox.Show("Erfolgreich", "Erfolg");
        }
</code>```

When the user is in that group a principal error at

group.Members.Add(pc, IdentityType.UserPrincipalName, userId);

appears and won't go away even if the user is not in the group.

The error is:

System.DirectoryServices.AccountManagement.No Matching PrincipalException HResult=0x80131501 Message=Es wurde kein den angegebenen Parametern entsprechender Prinzipal gefunden. Source=System.DirectoryServices.AccountManagement StackTrace: at System.DirectoryServices.AccountManagement.PrincipalCollection.Add(PrincipalContext context, IdentityType identityType, String identityValue)

I already tried a try-catch block around that but the error still pops up. What is wrong?

答:
That error is not because the user is already in the group. It truly does mean that the user could not be found.

In this line:

```<code>group.Members.Add(pc, IdentityType.UserPrincipalName, userId);
</code>```

You are telling it to match the userId to the UserPrincipalName. Does the value you are passing for userId match the user's UserPrincipalName? It should look something like username@lhw-nt.local. If you are passing just username, then you can change that line to have IdentityType.SamAccountName instead.

Once it can find the user and the user is already in the group, it will throw a PrincipalExistsException, which you can catch and even ignore if you'd like.

The rest of this answer is just a side note that you can ignore if you'd like.

I prefer to use the DirectoryServices namespace directly, which is what the AccountManagement namespace uses in the background anyway. It's a bit more code, but you have much more control over what happens. This often results in code that runs faster.

For example, here is an equivalent method to find the group and user by name and add the user to the group. This will not throw an exception if the user is already a member of the group. It will just silently continue.

You should handle the cases where either the group or user is not found. I have put comments in those spots.

```<code>public void AddUserToGroup(string userId, string groupName)
{

    string ss = Password();
    bool bSuccess = false;

    try
    {
        var searchRoot = new DirectoryEntry("LDAP://lhw-nt.local", "lhw-nt\\administrator", ss);

        //Find the group
        var groupSearcher = new DirectorySearcher
        {
            SearchRoot = searchRoot,
            //match group name by either sAMAccountName or cn
            Filter = $"(&(objectClass=group)(|(sAMAccountName={groupName})(cn={groupName})))",
            PropertiesToLoad = { "cn" } //if we omit this, it will load every attribute, which we don't need
        };

        var group = groupSearcher.FindOne()?.GetDirectoryEntry();

        if (group == null)
        {
            //group wasn't found
            return;
        }

        //Find the user
        var userSearcher = new DirectorySearcher
        {
            SearchRoot = searchRoot,
            Filter = $"(userPrincipalName={userId})",
            PropertiesToLoad = { "distinguishedName" }
        };

        var userDn = userSearcher.FindOne()?.Properties["distinguishedName"][0] as string;

        if (userDn == null)
        {
            //user wasn't found
            return;
        }

        //Add the user to the group
        group.Properties["member"].Add(userDn);
        group.CommitChanges();

        bSuccess = true;
    }
    catch (DirectoryServicesCOMException e)
    {
        MessageBox.Show(e.ToString(), "Fehler");
    }

    if (bSuccess)
    {
        MessageBox.Show("Erfolgreich", "Erfolg");
    }
}
</code>```

Body:
I have the following code, which works fine, as long as the user isn't in defined group (groupName)

all values are defined in this function or somewhere else and are implemented correctly, the values are correct in this function:

    public void AddUserToGroup(string userId, string groupName)
    {

        string ss = Password();
        bool bSuccess = false;

        try
        {
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "lhw-nt.local", null, "lhw-nt\\administrator", ss))
            {
                GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);
                group.Members.Add(pc, IdentityType.UserPrincipalName, userId);
                group.Save();

                bSuccess = true;
            }
        } catch (DirectoryServicesCOMException e)
        {
            MessageBox.Show(e.ToString(), "Fehler");
        }

        if(bSuccess)
        {
            MessageBox.Show("Erfolgreich", "Erfolg");
        }

When the user is in that group a principal error at

group.Members.Add(pc, IdentityType.UserPrincipalName, userId);

appears and won't go away even if the user is not in the group.

The error is:

System.DirectoryServices.AccountManagement.No Matching PrincipalException HResult=0x80131501 Message=Es wurde kein den angegebenen Parametern entsprechender Prinzipal gefunden. Source=System.DirectoryServices.AccountManagement StackTrace: at System.DirectoryServices.AccountManagement.PrincipalCollection.Add(PrincipalContext context, IdentityType identityType, String identityValue)

I already tried a try-catch block around that but the error still pops up. What is wrong?

Body:
That error is not because the user is already in the group. It truly does mean that the user could not be found.

In this line:

group.Members.Add(pc, IdentityType.UserPrincipalName, userId);

You are telling it to match the userId to the UserPrincipalName. Does the value you are passing for userId match the user's UserPrincipalName? It should look something like username@lhw-nt.local. If you are passing just username, then you can change that line to have IdentityType.SamAccountName instead.

Once it can find the user and the user is already in the group, it will throw a PrincipalExistsException, which you can catch and even ignore if you'd like.

The rest of this answer is just a side note that you can ignore if you'd like.

I prefer to use the DirectoryServices namespace directly, which is what the AccountManagement namespace uses in the background anyway. It's a bit more code, but you have much more control over what happens. This often results in code that runs faster.

For example, here is an equivalent method to find the group and user by name and add the user to the group. This will not throw an exception if the user is already a member of the group. It will just silently continue.

You should handle the cases where either the group or user is not found. I have put comments in those spots.

public void AddUserToGroup(string userId, string groupName)
{

    string ss = Password();
    bool bSuccess = false;

    try
    {
        var searchRoot = new DirectoryEntry("LDAP://lhw-nt.local", "lhw-nt\\administrator", ss);

        //Find the group
        var groupSearcher = new DirectorySearcher
        {
            SearchRoot = searchRoot,
            //match group name by either sAMAccountName or cn
            Filter = $"(&(objectClass=group)(|(sAMAccountName={groupName})(cn={groupName})))",
            PropertiesToLoad = { "cn" } //if we omit this, it will load every attribute, which we don't need
        };

        var group = groupSearcher.FindOne()?.GetDirectoryEntry();

        if (group == null)
        {
            //group wasn't found
            return;
        }

        //Find the user
        var userSearcher = new DirectorySearcher
        {
            SearchRoot = searchRoot,
            Filter = $"(userPrincipalName={userId})",
            PropertiesToLoad = { "distinguishedName" }
        };

        var userDn = userSearcher.FindOne()?.Properties["distinguishedName"][0] as string;

        if (userDn == null)
        {
            //user wasn't found
            return;
        }

        //Add the user to the group
        group.Properties["member"].Add(userDn);
        group.CommitChanges();

        bSuccess = true;
    }
    catch (DirectoryServicesCOMException e)
    {
        MessageBox.Show(e.ToString(), "Fehler");
    }

    if (bSuccess)
    {
        MessageBox.Show("Erfolgreich", "Erfolg");
    }
}


问:
Another way to change the name of a table in Laravel using App\Models\XXX name
Simple question...
I can change the name of a table in a query like this:

```<code>$users = DB::table('users AS u')->select('name');
</code>```

Can i do it in some way like this?

```<code>$users = App\Models\Users::select('name')->get();
</code>```

答:
Can you try this:

```<code>$users = Users::from('users AS u')
               // Extra Logic
               ->where('u.//field' , '=' , $data)
               ->select('u.name')
               ->get();
</code>```

Hope It will help You!

Body:
Simple question...
I can change the name of a table in a query like this:

$users = DB::table('users AS u')->select('name');

Can i do it in some way like this?

$users = App\Models\Users::select('name')->get();

Body:
Can you try this:

$users = Users::from('users AS u')
               // Extra Logic
               ->where('u.//field' , '=' , $data)
               ->select('u.name')
               ->get();

Hope It will help You!


问:
Cannot declare List property in the JPA @Entity class. It says 'Basic' attribute type should not be a container
I have a JPA @Entity class Place, with some properties holding some information about a place, such as name of place, description, and URLs of some images.

For the URLs of images, I declare a List<Link> in my entity.

However, I am getting this error:

Basic attribute type should not be a container.

I tried to remove @Basic, but the error message is still there. Why does it shows this error?

答:
You can also use @ElementCollection:

```<code>@ElementCollection
private List<String> tags;
</code>```

Body:
You can also use @ElementCollection:

@ElementCollection
private List<String> tags;


问:
Insert image into SQL Server database tables column
so I created a Menu Table like this

```<code>create table Menu(
MenuID char(5) primary key check(menuID LIKE 'MN[0-9][0-9][0-9]'),
MenuName varchar (50) not null,
MenuPrice int not null,
MenuImage varbinary(max) not null,
CategoryID char(5) references Category(CategoryID) ON UPDATE CASCADE ON DELETE SET NULL
)
</code>```

and I wanted to insert values into Menu but it isn't working.

```<code>insert into Menu values
('MN001','Mac & Cheese',60000,(SELECT * FROM OPENROWSET(BULK 'C:\Users\Kristina\Documents\FOODS\maccheese.jpg', SINGLE_BLOB) as T1),'CA001'),
('MN002','Grilled Veggies',60000,(SELECT * FROM OPENROWSET(BULK 'C:\Users\Kristina\Documents\FOODS\grilled.jpg', SINGLE_BLOB) as T2),'CA001')
</code>```

It kept giving me: Incorrect syntax near ','. I'm using SQL Server Management Studio 18.
I'm very new to this. Please help me, thanks!

答:
TRY THIS:

```<code>Insert into tableName (ImageColumn)
SELECT BulkColumn
FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img
</code>```

Paste your image path here

Body:
so I created a Menu Table like this

create table Menu(
MenuID char(5) primary key check(menuID LIKE 'MN[0-9][0-9][0-9]'),
MenuName varchar (50) not null,
MenuPrice int not null,
MenuImage varbinary(max) not null,
CategoryID char(5) references Category(CategoryID) ON UPDATE CASCADE ON DELETE SET NULL
)

and I wanted to insert values into Menu but it isn't working.

insert into Menu values
('MN001','Mac & Cheese',60000,(SELECT * FROM OPENROWSET(BULK 'C:\Users\Kristina\Documents\FOODS\maccheese.jpg', SINGLE_BLOB) as T1),'CA001'),
('MN002','Grilled Veggies',60000,(SELECT * FROM OPENROWSET(BULK 'C:\Users\Kristina\Documents\FOODS\grilled.jpg', SINGLE_BLOB) as T2),'CA001')

It kept giving me: Incorrect syntax near ','. I'm using SQL Server Management Studio 18.
I'm very new to this. Please help me, thanks!

Body:
TRY THIS:

Insert into tableName (ImageColumn)
SELECT BulkColumn
FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img

Paste your image path here


问:
Dedicated Elasticsearch ingest (coordinate ) nodes
In Elasticsearch is it recommended to have ingest nodes as dedicated? I'm planning to run Elasticsearch on k8s cluster and allowing ingest pods to be scheduled on worker nodes which have other java service pods also running. Is this good setup for production ? Any guideline how much memory, cpu should be kept for ingest nodes ?</p>

答:
It depends on your use case if you have a write-heavy system with costly transformation, then you can use the dedicated ingest node(Note this is different from the co-ordinate node, the title of question is misleading).

Please refer different node type in elasticsearch and please refer the responsibility of coordinating node

As explained in the official doc of nodes

Ingest nodes are able to apply an ingest pipeline to a document in
  order to transform and enrich the document before indexing. With a
  heavy ingest load, it makes sense to use dedicated ingest nodes and to
  mark the master and data nodes as node.ingest: false.


问:
Wordpress Headless to reactJS with wp-api
I want to make an app with a wordpress headless server and a react app for the front end with the wp-api.

I can get my data but with html tags. I want to build my html into react, not into wordpress.

I don't know how to do this, I tried to trim the html with wpautop who makes content as plain text (https://codex.wordpress.org/Function_Reference/wpautop), but now I'm stuck because, what if I need to put a picture or a list in the middle of my content with this plaintext :D ?
I don't know if there are solutions for this, that's why I'm asking here.

Regards !

答:
Create one common function for removing HTML tags in the react side like.

```<code>removeTags = (str) => {
  if ((str===null) || (str===''))
  return false;
  else
  str = str.toString();
  return str.replace( /(<([^>]+)>)/ig, '');
}
</code>```

and call it whenever you get data from Wordpress API like:

```<code>this.removeTags(post.excerpt.rendered)
</code>```

You can check my repo for more information:

https://github.com/BRdhanani/headless-wordpress-with-react

Body:
Create one common function for removing HTML tags in the react side like.

removeTags = (str) => {
  if ((str===null) || (str===''))
  return false;
  else
  str = str.toString();
  return str.replace( /(<([^>]+)>)/ig, '');
}

and call it whenever you get data from Wordpress API like:

this.removeTags(post.excerpt.rendered)

You can check my repo for more information:

https://github.com/BRdhanani/headless-wordpress-with-react


问:
Thymeleaf - output variable without a tag
I use Thymeleaf as a templating engine and I usually output variable value like this:

in Java I set:

```<code>ctx.setVariable("tester", "hello");
</code>```

and in html template I output:

```<code><span th:text="${tester}"></span>
</code>```

This works great, but I would like to output a variable without the need of a tag. Something following would be great:

```<code>${tester}
</code>```

Unfortunately it does not work. My goal is to avoid unnecessary tag to output the variable value. Is this possible to do with Thymeleaf?

答:
My goal is to avoid unnecessary tag to output the variable value. Is this possible to do with Thymeleaf?

Yes this is possible. You can use the Thymeleaf synthetic th:block tag (see here).

Example template excerpt:

```<code><body>
    <th:block th:text="${tester}"></th:block>
</body>
</code>```

This renders the following HTML:

```<code><body>
    hello
</body>
</code>```

Only the variable is displayed.

Body:
I use Thymeleaf as a templating engine and I usually output variable value like this:

in Java I set:

ctx.setVariable("tester", "hello");

and in html template I output:

This works great, but I would like to output a variable without the need of a tag. Something following would be great:

${tester}

Unfortunately it does not work. My goal is to avoid unnecessary tag to output the variable value. Is this possible to do with Thymeleaf?

Body:
My goal is to avoid unnecessary tag to output the variable value. Is this possible to do with Thymeleaf?

Yes this is possible. You can use the Thymeleaf synthetic th:block tag (see here).

Example template excerpt:

<body>
    <th:block th:text="${tester}"></th:block>
</body>

This renders the following HTML:

<body>
    hello
</body>

Only the variable is displayed.


问:
COUNTIF Formula moves down when row at top added
I have the following COUNTIF Formula in my Google Sheet.

=COUNTIFS('Events/Incidents'!$E$3:$E,X4,'Events/Incidents'!$I$3:$I,"Accident")```
</div>
</div>
</p>

<p>This is a sample of the sheet which has the formula in the first row under the "Accidents" header:</p>

<p><img src="https://i.stack.imgur.com/ftQVE.png" alt="enter image description here"></p>

<p>It works until a user adds a row 3 to the top of the source sheet (Events/Incidents) then the formula changes to the following so that it captures row 4 down instead of the desired row 3.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>=COUNTIFS('Events/Incidents'!$E$4:$E,X4,'Events/Incidents'!$I$4:$I,"Accident")</code>```

I used the Query function for "All Events" (the first 3 columns). The Countif formula is under each of the Incidents. In my Countif example, X4 is the Employee, John White which was returned in the QUERY.

The QUERY continues to return/include row 3 but I don't know how to do this for the individual Incidents. I tried adding ArrayFormula to the Countif function but I have the same problem.

Would appreciate some help with this.

答:
I understand that you want to update your QUERY to reflect the correct row without resorting to returning the Branch in every response. If my comprehension is correct, there is a way to reach your goals with little modification.

First, you'll have to create a named range that includes the whole table (from the headers to the last row). You can then use this named range in every formula so new rows can be detected without changing the formula per se.

Finally, you can modify your QUERY to return only the values of Incidents in a Branch with something similar to =QUERY(myNamedRange,"SELECT G WHERE A = 'Auckland'"). That QUERY won't return the Branch, only the Incidents. If you keep having any doubts, please ask me for further help.

Body:
I have the following COUNTIF Formula in my Google Sheet.

=COUNTIFS('Events/Incidents'!$E$3:$E,X4,'Events/Incidents'!$I$3:$I,"Accident")

This is a sample of the sheet which has the formula in the first row under the "Accidents" header:

It works until a user adds a row 3 to the top of the source sheet (Events/Incidents) then the formula changes to the following so that it captures row 4 down instead of the desired row 3.

=COUNTIFS('Events/Incidents'!$E$4:$E,X4,'Events/Incidents'!$I$4:$I,"Accident")

I used the Query function for "All Events" (the first 3 columns). The Countif formula is under each of the Incidents. In my Countif example, X4 is the Employee, John White which was returned in the QUERY.

The QUERY continues to return/include row 3 but I don't know how to do this for the individual Incidents. I tried adding ArrayFormula to the Countif function but I have the same problem.

Would appreciate some help with this.


问:
Why does virtual box vboxheadless process using Vagrant use 100% of my cpu?
So I'm using a couple vagrant boxes and when i have them up, "sometimes/randomly" it starts to take up 100% cpu on my OS X machine and i have no idea whats causing it. I can ssh into the vmachine and check the load and it's at 0 sot its not something thats running in the box.

The only way I can fix this is if i suspend it and resume it, then it goes away until randomly it starts to happen again. Sometimes hours later, sometimes days later.

The only thing I can think of is it might be because i'm using nfs mounts within my virtual machine to access my projects, but i'm not sure yet.  Any ideas?

答:
I have disabled System Integrity Protection in order to be able to use iosnoop to diagnose high ioctl activity, which seems to cause 100% CPU usage.

The problem disappeared. So I believe it has something to do with SIP.


答:
.NET is not super-super slow- but nor is it in the same realm as a native language. The speed differential is something you could easily suck up for a business app that prefers safety and shorter development cycles. If you're not using every cycle on the CPU then it doesn't matter how many you use, and the fact is that many or even most apps simply don't need that kind of performance. However, when you do need that kind of performance, .NET won't offer it.

More importantly, it's not controllable enough. In C++ then you destroy every resource, manage every allocation. This is a big burden when you really don't want to have to do it- but when you need the added performance of fine-tuning every allocation, it's impossible to beat.

Another thing to consider is the compiler. I mean, the JIT has access to more information about both the program and the target CPU. However, it does have to re-compile from scratch every time, and do so under far, far greater time constraints than the C++ compiler, inherently limiting what it's capable of. The CLR semantics, like heap allocation for every object every time, are also fundamentally limiting of it's performance. Managed GC allocation is plenty fast, but it's no stack allocation, and more importantly, de-allocation.

Edit: Of course, the fact that .NET ships with a different memory control paradigm to (most) native languages means that for an application for which garbage collection is particularly suited, then .NET code may run faster than native code. This isn't, however, anything to do with managed code versus native code, just picking the right algorithm for the right job, and it doesn't mean that an equivalent GC algorithm used from native code wouldn't be faster.

Title: Can managed code perform computations as fast as unmamanged?

Body:
I've been interested in different chess engines lately. There are many open and closed sources project in this field. They are all (most of them anyway) written in C/C++. This is kind of an obvious thing - you have a computationally intensive task, you use C/C++ so you get both portability and speed. This seems like a no-brainier.

However, I would like to question that idea. When .NET first appeared, there were many people saying that .NET idea would not work because .NET programs were doomed to be super-slow. In reality this did not happen. Somebody did a good job with the VM, JIT, etc and we have decent performance for most tasks now. But not all. Microsoft never promised that .NET will be suitable for all task and admitted for some tasks you will still need C/C++.

Going back to the question of computationally heavy task - is there a way to write a .NET program so that it does not perform computations considerably worse that an unmanaged code using the same algorithms? I'd be happy with "constant" speed loss, but anything worse than that is going to be a problem.

What do you think? Can we be close in speed to unmanaged code for computations in managed code, or unmanaged code is the only viable answer? If we can, how? If we can't why?

Update:  a lot of good feedback here. I'm going to accept the most up-voted answer.


问:
Netscape LDAP API to get the Maxpagesize from Microsoft AD
As Microsoft AD has maxpagesize property, which is used to return the max records per page from directory to client. So if we want to fetch more records (than configured to maxpagesize) from Microsoft AD, we need to do pagination.

So to achieve this we wanted to read this value of maxpagesize at client side through Netscape API.
So could you please help us on this. is it really possible otherwise we need to configure the pagesize at UI.

Thanks,
Hrushi

答:
The MaxPageSize is part of the LDAP policy in Active Directory and since Windows Server 2008 R2 or Windows Server 2008 domain controller the hardcoded limits dictate MaxPageSize=20,000 and MaxValRange=5,000.

The value can be read from:

```<code>dn: CN=Default Query Policy,CN=Query-Policies,CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=mad,DC=example,DC=com
</code>```

But Real life is never that simple.

LDAP policies are specified using the lDAPAdminLimits attribute. The lDAPAdminLimits attribute of a queryPolicy object is a multivalued string where each string value encodes a name-value pair. In the encoding, the name and value are separated by an "=". For example, the encoding of the name "MaxActiveQueries" with value "0" is "MaxActiveQueries=0". Each name is the name of an LDAP policy, and the value is a value of that policy.

There can be multiple queryPolicy objects in a forest. A DC determines the queryPolicy object that contains its policies according to the following logic:

If the queryPolicyObject attribute is present on the DC's nTDSDSA
object, the DC uses the queryPolicy object referenced by it.

Otherwise, if the queryPolicyObject attribute is present on the
nTDSSiteSettings object for the site to which the DC belongs, the DC
uses the queryPolicy object referenced by it.

Otherwise, the DC uses the queryPolicy object whose DN is "CN=Default
Query Policy,CN=Query-Policies" relative to the nTDSService object
(for example, "CN=Default Query Policy, CN=Query-Policies,
CN=Directory Service, CN=Windows NT, CN=Services" relative to the
root of the config NC).

And Finally MaxPageSize in Windows Server 2008 and Windows Server 2008 R2 (and I assume later) has a Hardcoded limit which override LDAP policy in Active Directory setting when the policy value should be higher.

Body:
The MaxPageSize is part of the LDAP policy in Active Directory and since Windows Server 2008 R2 or Windows Server 2008 domain controller the hardcoded limits dictate MaxPageSize=20,000 and MaxValRange=5,000.

The value can be read from:

dn: CN=Default Query Policy,CN=Query-Policies,CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=mad,DC=example,DC=com

But Real life is never that simple.

LDAP policies are specified using the lDAPAdminLimits attribute. The lDAPAdminLimits attribute of a queryPolicy object is a multivalued string where each string value encodes a name-value pair. In the encoding, the name and value are separated by an "=". For example, the encoding of the name "MaxActiveQueries" with value "0" is "MaxActiveQueries=0". Each name is the name of an LDAP policy, and the value is a value of that policy.

There can be multiple queryPolicy objects in a forest. A DC determines the queryPolicy object that contains its policies according to the following logic:

If the queryPolicyObject attribute is present on the DC's nTDSDSA
object, the DC uses the queryPolicy object referenced by it.

Otherwise, if the queryPolicyObject attribute is present on the
nTDSSiteSettings object for the site to which the DC belongs, the DC
uses the queryPolicy object referenced by it.

Otherwise, the DC uses the queryPolicy object whose DN is "CN=Default
Query Policy,CN=Query-Policies" relative to the nTDSService object
(for example, "CN=Default Query Policy, CN=Query-Policies,
CN=Directory Service, CN=Windows NT, CN=Services" relative to the
root of the config NC).

And Finally MaxPageSize in Windows Server 2008 and Windows Server 2008 R2 (and I assume later) has a Hardcoded limit which override LDAP policy in Active Directory setting when the policy value should be higher.