问:
Invalid Argument Error Tensorflow Object Detection Training
I am training tensor flow object detection following the tensor flow API. I have trained many models in the past using the exact same steps. This model however keeps giving me the error message below. The error message references

InvalidArgumentError: image_size must contain 3 elements[4]

I searched the error and found

InvalidArgumentError: image_size must contain 3 elements[4] #3349

which shows the error and gives the solution of checking to make sure that all images are RGB. I used the code provided in that thread to check all images. I found about 15 images that were not RGB. I removed the images and the corresponding xml files. I recompiled the csv files and the tfrecord files and restarted the training. I received the error message again. I then tried to start the training over without resuming from the last checkpoint and I still received the error. The error does not happen on a regular basis. Sometimes the model will go for several thousand steps before a failure. I have also tried removing the random crop parameter from the pipeline.config file which had no affect.

Any help is appreciated.

Error Message:

```<code>INFO:tensorflow:global_step/sec: 2.03361
INFO:tensorflow:global step 4039: loss = 6.2836 (0.512 sec/step)
INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.InvalidArgumentError'>, image_size must contain 3 elements[4]
         [[Node: cond_2/RandomCropImage/sample_distorted_bounding_box/SampleDistortedBoundingBoxV2 = SampleDistortedBoundingBoxV2[T=DT_INT32, area_range=[0.1, 1], aspect_ratio_range=[0.5, 2],max_attempts=100, seed=0, seed2=0, use_image_if_no_bounding_boxes=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](cond_2/RandomCropImage/Shape, cond_2/RandomCropImage/ExpandDims, cond_2/RandomCropImage/PruneNonOverlappingBoxes/Const)]]
INFO:tensorflow:Recording summary at step 4039.
INFO:tensorflow:global step 4040: loss = 4.6984 (0.880 sec/step)
INFO:tensorflow:Finished training! Saving model to disk.
Traceback (most recent call last):
  File "/floyd/object_detection/legacy/train.py", line 184, in <module>
    tf.app.run()
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 125, inrun
    _sys.exit(main(argv))
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 250, in new_func
    return func(*args, **kwargs)
  File "/floyd/object_detection/legacy/train.py", line 180, in main
    graph_hook_fn=graph_rewriter_fn)
  File "/floyd/object_detection/legacy/trainer.py", line 415, in train
    saver=saver)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/contrib/slim/python/slim/learning.py", line 785, in train
    ignore_live_threads=ignore_live_threads)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/training/supervisor.py", line 833, in stop
    ignore_live_threads=ignore_live_threads)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/training/coordinator.py", line389, in join
    six.reraise(*self._exc_info_to_raise)
  File "/usr/local/lib/python3.6/site-packages/six.py", line 693, in reraise
    raise value
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/training/queue_runner_impl.py", line 252, in _run
    enqueue_callable()
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1244,in _single_operation_run
    self._call_tf_sessionrun(None, {}, [], target_list, None)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1409,in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.InvalidArgumentError: image_size must contain 3 elements[4]
         [[Node: cond_2/RandomCropImage/sample_distorted_bounding_box/SampleDistortedBoundingBoxV2 = SampleDistortedBoundingBoxV2[T=DT_INT32, area_range=[0.1, 1], aspect_ratio_range=[0.5, 2],max_attempts=100, seed=0, seed2=0, use_image_if_no_bounding_boxes=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](cond_2/RandomCropImage/Shape, cond_2/RandomCropImage/ExpandDims, cond_2/RandomCropImage/PruneNonOverlappingBoxes/Const)]]
</code>```

Thanks in advance.

答: so it was the RGB image problem. I had checked the images and removed the non RGB images and recreated the records, but the model was still pointing to the old records because the paths were very similar, I did not notice. </p>

Body:
I am training tensor flow object detection following the tensor flow API. I have trained many models in the past using the exact same steps. This model however keeps giving me the error message below. The error message references

InvalidArgumentError: image_size must contain 3 elements[4]

I searched the error and found

InvalidArgumentError: image_size must contain 3 elements[4] #3349

which shows the error and gives the solution of checking to make sure that all images are RGB. I used the code provided in that thread to check all images. I found about 15 images that were not RGB. I removed the images and the corresponding xml files. I recompiled the csv files and the tfrecord files and restarted the training. I received the error message again. I then tried to start the training over without resuming from the last checkpoint and I still received the error. The error does not happen on a regular basis. Sometimes the model will go for several thousand steps before a failure. I have also tried removing the random crop parameter from the pipeline.config file which had no affect.

Any help is appreciated.

Error Message:

INFO:tensorflow:global_step/sec: 2.03361
INFO:tensorflow:global step 4039: loss = 6.2836 (0.512 sec/step)
INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.InvalidArgumentError'>, image_size must contain 3 elements[4]
         [[Node: cond_2/RandomCropImage/sample_distorted_bounding_box/SampleDistortedBoundingBoxV2 = SampleDistortedBoundingBoxV2[T=DT_INT32, area_range=[0.1, 1], aspect_ratio_range=[0.5, 2],max_attempts=100, seed=0, seed2=0, use_image_if_no_bounding_boxes=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](cond_2/RandomCropImage/Shape, cond_2/RandomCropImage/ExpandDims, cond_2/RandomCropImage/PruneNonOverlappingBoxes/Const)]]
INFO:tensorflow:Recording summary at step 4039.
INFO:tensorflow:global step 4040: loss = 4.6984 (0.880 sec/step)
INFO:tensorflow:Finished training! Saving model to disk.
Traceback (most recent call last):
  File "/floyd/object_detection/legacy/train.py", line 184, in <module>
    tf.app.run()
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 125, inrun
    _sys.exit(main(argv))
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 250, in new_func
    return func(*args, **kwargs)
  File "/floyd/object_detection/legacy/train.py", line 180, in main
    graph_hook_fn=graph_rewriter_fn)
  File "/floyd/object_detection/legacy/trainer.py", line 415, in train
    saver=saver)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/contrib/slim/python/slim/learning.py", line 785, in train
    ignore_live_threads=ignore_live_threads)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/training/supervisor.py", line 833, in stop
    ignore_live_threads=ignore_live_threads)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/training/coordinator.py", line389, in join
    six.reraise(*self._exc_info_to_raise)
  File "/usr/local/lib/python3.6/site-packages/six.py", line 693, in reraise
    raise value
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/training/queue_runner_impl.py", line 252, in _run
    enqueue_callable()
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1244,in _single_operation_run
    self._call_tf_sessionrun(None, {}, [], target_list, None)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1409,in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.InvalidArgumentError: image_size must contain 3 elements[4]
         [[Node: cond_2/RandomCropImage/sample_distorted_bounding_box/SampleDistortedBoundingBoxV2 = SampleDistortedBoundingBoxV2[T=DT_INT32, area_range=[0.1, 1], aspect_ratio_range=[0.5, 2],max_attempts=100, seed=0, seed2=0, use_image_if_no_bounding_boxes=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](cond_2/RandomCropImage/Shape, cond_2/RandomCropImage/ExpandDims, cond_2/RandomCropImage/PruneNonOverlappingBoxes/Const)]]

Thanks in advance.


来源: stackexchange

问:
Translating Nucleotides Triplets
I am trying to split a string of nucleotides in a way that allows me to find the outlier in the center of the nucleotide sequence, and turn it into a triplet by adding "n" to fill in the gaps.

I have tried splitting by number of characters, but the problem is that it happens from left to right, and I have been trying to find a way to do it right to left. So what I have done is find the length of the sequence, which in this one example is 52. Then, I take that length number and divide it by 3, to find the number of potential triplets that there will be. Then, I divide by 2 to know (obviously rounding) how many groups of 3 there will be roughly on each side of the outlier. Ideally, I want one more triplet on the left hand side than on the right hand side. The outlier would remain in the middle (either as one nucleotide, or two). For example:

```<code>nucleobases <- 'TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC'
nucleolength <- nchar("TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC")
num1 <- round(nucleolength/6)*3

firstsplit <- gsub("(.{27})", "\\1 ", nucleobases) #This works for the first half

secondsplit <- gsub("(.{24})", "\\1 ", firstsplit, rev) #This works, but not in the ideal way that it is supposed to.
</code>```

I do not have any trouble translating the sequences into amino acids, which is my end goal. What I want is to add "n" in the places where it belongs in the sequence (on the outlier) so the ends of the sequences become the correct amino acids. This is ultimately what I would like:

```<code>#original sequence: TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC
#split up in the correct places: TGTGCCAGCAGTTTAAGGTAGATAGCG G GATTCCTACAATGAGCAGTTCTTC
#"N" fills in the outlier: TGTGCCAGCAGTTTAAGGTAGATAGCG GNN GATTCCTACAATGAGCAGTTCTTC
#Gaps are then eliminated and sequence is translated: TGTGCCAGCAGTTTAAGGTAGATAGCGGNNGATTCCTACAATGAGCAGTTCTTC
#Translated sequence: CASSLR-IAXDSYNEQFF
</code>```

If anyone has an idea of how to do this in an efficient way possible, it would be great to know! Also, something to keep in mind is that this is not the only sequence. There are other sequences with different lengths (47, 46, 35, etc.). To reiterate, the grouped sequence on the left should be longer than the right, with the outlier in the middle. Please keep in mind that the groups should be a multiple of 3 (since they are codons), all except for the outlier. Thank you!!

答:
You could write a simple function to do this - perhaps something like the following...

```<code>nucleobases <- 'TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC'

fill_outlier <- function(x){
  threes <- floor(nchar(x) / 3)                            #number of whole sets of three
  outlier <- 1 + 3 * ceiling(threes / 2)                   #number of threes to the left
  outlen <- nchar(x) %% 3                                  #length of outlier
  filled <- paste0(substr(x, 1, outlier-1),                #section before outlier
                   ifelse(outlen==0, "",                   #do nothing if multiple of 3
                      substr(paste0(substr(x, outlier, outlier + outlen - 1), #outlier
                                    "NN"),                 #pad it with Ns
                             1, 3)),                       #take first three characters
                   substr(x, outlier + outlen, nchar(x)))  #section after outlier
  return(filled)
}

fill_outlier(nucleobases)
[1] "TGTGCCAGCAGTTTAAGGTAGATAGCGGNNGATTCCTACAATGAGCAGTTCTTC"
</code>```

This will be vectorised, so you can apply it directly to a vector of strings.

ContentLicense: CC BY-SA 4.0

Title: Translating Nucleotides Triplets

Body:
I am trying to split a string of nucleotides in a way that allows me to find the outlier in the center of the nucleotide sequence, and turn it into a triplet by adding "n" to fill in the gaps.

I have tried splitting by number of characters, but the problem is that it happens from left to right, and I have been trying to find a way to do it right to left. So what I have done is find the length of the sequence, which in this one example is 52. Then, I take that length number and divide it by 3, to find the number of potential triplets that there will be. Then, I divide by 2 to know (obviously rounding) how many groups of 3 there will be roughly on each side of the outlier. Ideally, I want one more triplet on the left hand side than on the right hand side. The outlier would remain in the middle (either as one nucleotide, or two). For example:

nucleobases <- 'TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC'
nucleolength <- nchar("TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC")
num1 <- round(nucleolength/6)*3

firstsplit <- gsub("(.{27})", "\\1 ", nucleobases) #This works for the first half

secondsplit <- gsub("(.{24})", "\\1 ", firstsplit, rev) #This works, but not in the ideal way that it is supposed to.

I do not have any trouble translating the sequences into amino acids, which is my end goal. What I want is to add "n" in the places where it belongs in the sequence (on the outlier) so the ends of the sequences become the correct amino acids. This is ultimately what I would like:

#original sequence: TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC
#split up in the correct places: TGTGCCAGCAGTTTAAGGTAGATAGCG G GATTCCTACAATGAGCAGTTCTTC
#"N" fills in the outlier: TGTGCCAGCAGTTTAAGGTAGATAGCG GNN GATTCCTACAATGAGCAGTTCTTC
#Gaps are then eliminated and sequence is translated: TGTGCCAGCAGTTTAAGGTAGATAGCGGNNGATTCCTACAATGAGCAGTTCTTC
#Translated sequence: CASSLR-IAXDSYNEQFF

If anyone has an idea of how to do this in an efficient way possible, it would be great to know! Also, something to keep in mind is that this is not the only sequence. There are other sequences with different lengths (47, 46, 35, etc.). To reiterate, the grouped sequence on the left should be longer than the right, with the outlier in the middle. Please keep in mind that the groups should be a multiple of 3 (since they are codons), all except for the outlier. Thank you!!

Body:
You could write a simple function to do this - perhaps something like the following...

nucleobases <- 'TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC'

fill_outlier <- function(x){
  threes <- floor(nchar(x) / 3)                            #number of whole sets of three
  outlier <- 1 + 3 * ceiling(threes / 2)                   #number of threes to the left
  outlen <- nchar(x) %% 3                                  #length of outlier
  filled <- paste0(substr(x, 1, outlier-1),                #section before outlier
                   ifelse(outlen==0, "",                   #do nothing if multiple of 3
                      substr(paste0(substr(x, outlier, outlier + outlen - 1), #outlier
                                    "NN"),                 #pad it with Ns
                             1, 3)),                       #take first three characters
                   substr(x, outlier + outlen, nchar(x)))  #section after outlier
  return(filled)
}

fill_outlier(nucleobases)
[1] "TGTGCCAGCAGTTTAAGGTAGATAGCGGNNGATTCCTACAATGAGCAGTTCTTC"

This will be vectorised, so you can apply it directly to a vector of strings.


问:
Parse a JSON object with the value as JSON string array
I am trying to parse a JSON string which is of the following format

```<code>{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}
</code>```

I have written a code to parse it.

```<code>import groovy.json.JsonOutput
import groovy.json.JsonSlurper

def jsonSlurper = new JsonSlurper()

def object = jsonSlurper.parseText('{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}')

println(object["edgeNodeRegistrationStatus"][0])
</code>```

I expect the code to print {"CONFIRMED":"TRUE"}. But its throwing an error

```<code>Caught: groovy.json.JsonException: expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

The current character read is 'C' with an int value of 67
expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

line number 1
index number 35
{"edgeNodeRegistrationStatus": ["{"CONFIRMED":"TRUE"}"]}
...................................^
groovy.json.JsonException: expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

The current character read is 'C' with an int value of 67
expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

line number 1
index number 35
{"edgeNodeRegistrationStatus": ["{"CONFIRMED":"TRUE"}"]}
...................................^
    at jdoodle.run(jdoodle.groovy:4)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Command exited with non-zero status 1
</code>```

答:
Or, you can use a different String delimiter, thusly:</p>

```<code>def text = $/{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}/$

def object = jsonSlurper.parseText(text)

println object.edgeNodeRegistrationStatus[0]
</code>```

Body:
I am trying to parse a JSON string which is of the following format

{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}

I have written a code to parse it.

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

def jsonSlurper = new JsonSlurper()

def object = jsonSlurper.parseText('{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}')

println(object["edgeNodeRegistrationStatus"][0])

I expect the code to print {"CONFIRMED":"TRUE"}. But its throwing an error

Caught: groovy.json.JsonException: expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

The current character read is 'C' with an int value of 67
expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

line number 1
index number 35
{"edgeNodeRegistrationStatus": ["{"CONFIRMED":"TRUE"}"]}
...................................^
groovy.json.JsonException: expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

The current character read is 'C' with an int value of 67
expecting a ',' or a ']',  but got
the current character of  'C' with an int value of 67  on array index of 1

line number 1
index number 35
{"edgeNodeRegistrationStatus": ["{"CONFIRMED":"TRUE"}"]}
...................................^
    at jdoodle.run(jdoodle.groovy:4)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Command exited with non-zero status 1

Body:
Or, you can use a different String delimiter, thusly:

def text = $/{"edgeNodeRegistrationStatus": ["{\"CONFIRMED\":\"TRUE\"}"]}/$

def object = jsonSlurper.parseText(text)

println object.edgeNodeRegistrationStatus[0]


问:
Spring Boot jdbc issue. Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured
I'm just connected this DB in Intellij IDEA and it's fine, but when I launch my Spring Boot App with this configs, I see this trouble's messages

***Configs on pics

```<code>2019-05-28 20:56:53.487 ERROR 700 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

Process finished with exit code 0

</code>```

application.properties
pom

答:
We need to add a bean for DataSource in the configuration class, something like this</p>

```<code>@Bean
public DataSource dataSource(){
    DriverManagerDataSource source = new DriverManagerDataSource();
    source.setDriverClassName(driverClass);
    source.setUrl(url);
    source.setUsername(username);
    source.setPassword(password);
    return source;
}
</code>```

Body:
I'm just connected this DB in Intellij IDEA and it's fine, but when I launch my Spring Boot App with this configs, I see this trouble's messages

***Configs on pics

2019-05-28 20:56:53.487 ERROR 700 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

Process finished with exit code 0

application.properties
pom

Body:
We need to add a bean for DataSource in the configuration class, something like this

@Bean
public DataSource dataSource(){
    DriverManagerDataSource source = new DriverManagerDataSource();
    source.setDriverClassName(driverClass);
    source.setUrl(url);
    source.setUsername(username);
    source.setPassword(password);
    return source;
}


问:
Android, for JNI should System.loadLibrary be called in an InputMethodService?
When sub-classing InputMethodService where native code is used, Android will kill the service when the input method is dismissed.

Later, Android will restart the service and JNI is not present causing Java unable to find the native functions and an exception thrown.

I had previously thought that only one System.loadLibrary in MainActivity was required. Should this be added to services too?

答:
There is no extra cost in putting LoadLibrary in all relevant classes, so go for it. Use it in static constructors of each Java class, or companion object of Kotlin class </p>

<p>MainActivity is not the best choice to begin with, because every time you later add another activity or service that can be started independently, you must not forget to duplicate your LoadLibrary. </p>

Body:
There is no extra cost in putting LoadLibrary in all relevant classes, so go for it. Use it in static constructors of each Java class, or companion object of Kotlin class

MainActivity is not the best choice to begin with, because every time you later add another activity or service that can be started independently, you must not forget to duplicate your LoadLibrary.


问:
Is there any function for reading NFC-A (ISO14443A) tag with X-NUCLEO_NFC05A1?
I'm using X-NUCLEO-NFC05A1 with STM32 NUCLEO-F401RE board to read an NFC-A (ISO14443A) tag. I couldn't find any function for reading the tag. Can anyone help me?

I tried the sample given by ST, I could find write function from there. But I couldn't find any reading function from there.

答:
You can simply use rfalTransceiveBlockingTxRx() from rfal_rf.h provided by the RFAL library. That transceive mechanism applies to all RF technologies.

Since there is no generic commandset for interacting with NFC-A tags, the exact coding of the READ command will depend on your specific tag type. For instance, for a Type 2 tag, the READ command would consist of two bytes: 0x30 <BLOCK-ADDRESS-AS-SINGLE-BYTE>

For such a tag, you could, for instance, use something like this:

```<code>uint8_t bufferTx[2];
uint16_t lenTx;
uint8_t bufferRx[16];
uint16_t lenRxMax, lenRx;
ReturnCode status;

lenTx = 0;
bufferTx[lenTx++] = 0x30;
bufferTx[lenTx++] = 0;  // TODO: change this to the read offset

lenRxMax = 16;
lenRx = 0;
status = rfalTransceiveBlockingTxRx(&bufferTx[0], lenTx, &bufferRx[0], lenRxMax, &lenRx, RFAL_TXRX_FLAGS_DEFAULT, rfalConvMsTo1fc(5));

// if status does not indicate error,
// you will now find the response in bufferRx,
// the actual response length is lenRx
</code>```

Body:
You can simply use rfalTransceiveBlockingTxRx() from rfal_rf.h provided by the RFAL library. That transceive mechanism applies to all RF technologies.

Since there is no generic commandset for interacting with NFC-A tags, the exact coding of the READ command will depend on your specific tag type. For instance, for a Type 2 tag, the READ command would consist of two bytes: 0x30 <BLOCK-ADDRESS-AS-SINGLE-BYTE>

For such a tag, you could, for instance, use something like this:

uint8_t bufferTx[2];
uint16_t lenTx;
uint8_t bufferRx[16];
uint16_t lenRxMax, lenRx;
ReturnCode status;

lenTx = 0;
bufferTx[lenTx++] = 0x30;
bufferTx[lenTx++] = 0;  // TODO: change this to the read offset

lenRxMax = 16;
lenRx = 0;
status = rfalTransceiveBlockingTxRx(&bufferTx[0], lenTx, &bufferRx[0], lenRxMax, &lenRx, RFAL_TXRX_FLAGS_DEFAULT, rfalConvMsTo1fc(5));

// if status does not indicate error,
// you will now find the response in bufferRx,
// the actual response length is lenRx


问:
How to capitalize the first letter of a String in Java?
I am using Java to get a String input from the user. I am trying to make the first letter of this input capitalized.

I tried this:

```<code>String name;

BufferedReader br = new InputStreamReader(System.in);

String s1 = name.charAt(0).toUppercase());

System.out.println(s1 + name.substring(1));
</code>```

which led to these compiler errors:

Type mismatch: cannot convert from InputStreamReader to BufferedReader

Cannot invoke toUppercase() on the primitive type char

答:
Use replace method.</p>

```<code>String newWord = word.replace(String.valueOf(word.charAt(0)), String.valueOf(word.charAt(0)).toUpperCase());
</code>```

Body:
I am using Java to get a String input from the user. I am trying to make the first letter of this input capitalized.

I tried this:

String name;

BufferedReader br = new InputStreamReader(System.in);

String s1 = name.charAt(0).toUppercase());

System.out.println(s1 + name.substring(1));

which led to these compiler errors:

Type mismatch: cannot convert from InputStreamReader to BufferedReader

Cannot invoke toUppercase() on the primitive type char

Body:
Use replace method.

String newWord = word.replace(String.valueOf(word.charAt(0)), String.valueOf(word.charAt(0)).toUpperCase());


问:
Flex - How to bind (two-way) an integer to a TextInput Field
How do you two-way bind an integer to an input field in Flex/FB4?
is_admin is an integer :

```<code><s:TextInput id="textUserIsAdmin" text="@{user.is_admin}" width="5"/>
</code>```

I receive:

```<code>1067: Implicit coercion of a value of type String to an unrelated type int.
</code>```

Is there a different input type, or do I have to bind a different way?

答:
Short answer, you can't do 2 way binding when trying to change the very nature of the object you're binding.  They have to be the same or it won't work.  With that said, there is a workaround:

```<code><s:TextInput id="textUserIsAdmin" text="{user.is_admin}" restrict="0-9" change="user.is_admin = int(textUserIsAdmin.text)"/>
</code>```

As you can see here, I'm binding the original value from the model, but then when the user types something the change event is dispatched and the TextInput value is casted and saved.  I also added a 'restrict' so that only numbers can be typed in.

ContentLicense: CC BY-SA 3.0

Body:
How do you two-way bind an integer to an input field in Flex/FB4?
is_admin is an integer :

<s:TextInput id="textUserIsAdmin" text="@{user.is_admin}" width="5"/>

I receive:

1067: Implicit coercion of a value of type String to an unrelated type int.

Is there a different input type, or do I have to bind a different way?

Body:
Short answer, you can't do 2 way binding when trying to change the very nature of the object you're binding.  They have to be the same or it won't work.  With that said, there is a workaround:

<s:TextInput id="textUserIsAdmin" text="{user.is_admin}" restrict="0-9" change="user.is_admin = int(textUserIsAdmin.text)"/>

As you can see here, I'm binding the original value from the model, but then when the user types something the change event is dispatched and the TextInput value is casted and saved.  I also added a 'restrict' so that only numbers can be typed in.


问:
Remove initial part of filename
I have multiple files that I would like to edit.

They look like

```<code>20190122-233715-886_tlog.354.2019012223043
</code>```

The prefix is mainly just date and time stamps and processing ID.

I need it to be

tlog.354.20190122230435

答:
Using a regular expression with a capture group allows you to

rename in a single pipeline.

```<code>Get-ChildItem *_tlog.* |
 Where-Object Name -match '^\d{8}-\d{6}-\d+_(tlog.*)$'|
   Rename-Item -NewNAme {$Matches[1]} -WhatIF
</code>```

If the output looks OK, remove the -WhatIf

Sample run with aliases (in my German locale):

```<code>PS> gci *_tlog.*|? Name -match '^\d{8}-\d{6}-\d+_(tlog.*)$'|Ren -NewName {$Matches[1]} -WhatIF
WhatIf: Ausführen des Vorgangs "Datei umbenennen" für das Ziel
"Element: A:\Test\20190122-233715-886_tlog.354.2019012223043
    Ziel: A:\Test\tlog.354.2019012223043".
</code>```

Title: Remove initial part of filename

Body:
I have multiple files that I would like to edit.

They look like

20190122-233715-886_tlog.354.2019012223043

The prefix is mainly just date and time stamps and processing ID.

I need it to be

tlog.354.20190122230435

Body:
Using a regular expression with a capture group allows you to

rename in a single pipeline.

Get-ChildItem *_tlog.* |
 Where-Object Name -match '^\d{8}-\d{6}-\d+_(tlog.*)$'|
   Rename-Item -NewNAme {$Matches[1]} -WhatIF

If the output looks OK, remove the -WhatIf

Sample run with aliases (in my German locale):

PS> gci *_tlog.*|? Name -match '^\d{8}-\d{6}-\d+_(tlog.*)$'|Ren -NewName {$Matches[1]} -WhatIF
WhatIf: Ausführen des Vorgangs "Datei umbenennen" für das Ziel
"Element: A:\Test\20190122-233715-886_tlog.354.2019012223043
    Ziel: A:\Test\tlog.354.2019012223043".


问:
Correct way how to connect to BluetoothGatt devices sequentially
I have already implemented Bluetooth low energy device scanning logic, but I'm struggling a little bit with BluetoothGatt service usage. What I want to do is to connect to each of my ESP32 devices sequentially from my Android phone, so that I can receive the data and then continue to the next device (and disconnect from previous). So there will be only one active connection between ESP32 and Android phone. The ESP32 is already programmed so if android phone connects to it using BluetoothGatt then it sends data (max 20 bytes).

The real struggle is to understand how to manage these connections to properly close/release the resources.

What would be the correct/simplest way to manage these BluetoothGatt connections?

My implementation basically connects to a new device Gatt service when the sent data is "end". The problem is that this works if one ESP32 device is active. If more devices are active then something happens and the data is not received from Gatt service.

Here is part of my implementation (sorry, I couldn't reduce the code size more):

1) I use BLE scanner to discover new devices

```<code>private Handler _leScanHandler = new Handler();
private final BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
        final int newRSSI = rssi;
        _leScanHandler.post(new Runnable() {
            @Override
            public void run() {
                addDeviceToListOnLEScan(device, newRSSI);
            }
        });
    }
};
</code>```

2) And the called method basically manages the BluetoothGatt conenctions..

```<code>public void addDeviceToListOnLEScan(BluetoothDevice device, int rssi) {

    // Gets only user defined devices
    boolean isUserDefinedDevice = _definedDevicesHashMap.containsKey(device.getAddress());
    if (!isUserDefinedDevice) {
        return;
    }

    // Adds device and updates 'LastModifiedTime = Date(System.currentTimeMillis())'
    addOrUpdateDevice(device.getAddress(), _scannedDevices);

    // Called only once on each connect button press to enable gatt operations
    if (!_isInitialConnectionHasBeenMade) {
        _isDataSendingCompleteFromCurrentGatt = true;
        _isInitialConnectionHasBeenMade = true;
    }

    // Sequential BLE device connect/disconnect operations
    if (_isDataSendingCompleteFromCurrentGatt) {

        BluetoothGatt previousGatt = _definedDevicesHashMap(previousAddress);
        if (previousGatt != null) {
            previousGatt.disconnect(); // ?
        }

        BluetoothGatt nextGatt = _definedDevicesHashMap(nextAddress);
        if (/* Checks if 'nextAddress' is in _scannedDevices */
            /* And whether device 'IsActive()' */) {

            if (nextGatt == null) {
                nextGatt = connectToDeviceGattService(nextGatt)
            }
            else {
                // Do something here ?
            }
            _isDataSendingCompleteFromCurrentGatt = false;
        }
    }
}
</code>```

3) The following variables/classes that I'm using

```<code>private boolean _isDataSendingCompleteFromCurrentGatt = false;
private boolean _isInitialConnectionHasBeenMade = false;
private HashMap<String, BluetoothGatt> _definedDevicesHashMap;
_definedDevicesHashMap.put("ff:ff:9f:c8:c2:93", null);
_definedDevicesHashMap.put("ff:ff:9f:c8:c4:91", null);
...

private HashMap<String, MyBLEDevice> _scannedDevices;

public class MyBLEDevice
{
    private final int deviceInactivityTimeout = 10;
    private String MacAddress;
    private Date _lastModifiedDate;
    public boolean isDeviceActive() {
        // Just gets the time difference (DateNow - lastModified) / 1000 < 10s
    }
}
</code>```

4) Method which I use to connect to device

```<code>public BluetoothGatt connectToDeviceGattService(BluetoothGatt currentGatt, BluetoothDevice device, BluetoothGattCallback callback) {
    _bluetoothAdapter.cancelDiscovery();
    if (currentGatt == null) {
        currentGatt = device.connectGatt(_activity, true, callback);
    }
    else {
        // Is anything here needed ?
    }

    return currentGatt;
}
</code>```

5) The BluetoothGatt callback

```<code>private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {

            // Discover services ?

        } else if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_DISCONNECTED) {

            // Do nothing ?

        } else if (status != BluetoothGatt.GATT_SUCCESS) {

            // Disconnect from current BluetoothGatt instance?
            // Also close the connection ?

            _isDataSendingCompleteFromCurrentGatt = true;
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        enableGattConfigurationCharacteristic();
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
        _gattServiceHandler.post(new Runnable() {
            @Override
            public void run() {
                handleMessage(Message.obtain(null, MSG_CHARACTERISTIC_CHANGE, characteristic));
            }
        });
    }
};
</code>```

6) And finally, the handler which is used to receive data from Gatt callback

```<code>private static final int MSG_CHARACTERISTIC_CHANGE = 0;
private Handler _gattServiceHandler = new Handler();
private void handleMessage(Message msg) {
    BluetoothGattCharacteristic characteristic;
    switch (msg.what) {
        case MSG_CHARACTERISTIC_CHANGE: {
            characteristic = (BluetoothGattCharacteristic) msg.obj;
            if (BLELogic.PROPERTY_NOTIFY_CHAR_UUID.equals(characteristic.getUuid())) {

                String notification = BluetoothExtension.getCharacteristicValue(characteristic);
                if (notification.equals("end")) {
                    _isDataSendingCompleteFromCurrentGatt = true;
                } else {
                    UpdateViewOnGattNotificationSent(notification);
                }
            }
        }
        default:
            return;
    }
}
</code>```

At the beginning I wanted to simplify all the logic, but it looks like when using BLE/Gatt service connections, there is nothing simple about this.

答:
Here is a Question and answer that might interest you

Short from the answer:

To achieve multiple BLE connection you have to store multiple
  BluetoothGatt object and use those object for different deveice. To
  store multiple connection object of BluetoothGatt you can use Map<>

private Map connectedDeviceMap;.............

Body:
I have already implemented Bluetooth low energy device scanning logic, but I'm struggling a little bit with BluetoothGatt service usage. What I want to do is to connect to each of my ESP32 devices sequentially from my Android phone, so that I can receive the data and then continue to the next device (and disconnect from previous). So there will be only one active connection between ESP32 and Android phone. The ESP32 is already programmed so if android phone connects to it using BluetoothGatt then it sends data (max 20 bytes).

The real struggle is to understand how to manage these connections to properly close/release the resources.

What would be the correct/simplest way to manage these BluetoothGatt connections?

My implementation basically connects to a new device Gatt service when the sent data is "end". The problem is that this works if one ESP32 device is active. If more devices are active then something happens and the data is not received from Gatt service.

Here is part of my implementation (sorry, I couldn't reduce the code size more):

1) I use BLE scanner to discover new devices

private Handler _leScanHandler = new Handler();
private final BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
        final int newRSSI = rssi;
        _leScanHandler.post(new Runnable() {
            @Override
            public void run() {
                addDeviceToListOnLEScan(device, newRSSI);
            }
        });
    }
};

2) And the called method basically manages the BluetoothGatt conenctions..

public void addDeviceToListOnLEScan(BluetoothDevice device, int rssi) {

    // Gets only user defined devices
    boolean isUserDefinedDevice = _definedDevicesHashMap.containsKey(device.getAddress());
    if (!isUserDefinedDevice) {
        return;
    }

    // Adds device and updates 'LastModifiedTime = Date(System.currentTimeMillis())'
    addOrUpdateDevice(device.getAddress(), _scannedDevices);

    // Called only once on each connect button press to enable gatt operations
    if (!_isInitialConnectionHasBeenMade) {
        _isDataSendingCompleteFromCurrentGatt = true;
        _isInitialConnectionHasBeenMade = true;
    }

    // Sequential BLE device connect/disconnect operations
    if (_isDataSendingCompleteFromCurrentGatt) {

        BluetoothGatt previousGatt = _definedDevicesHashMap(previousAddress);
        if (previousGatt != null) {
            previousGatt.disconnect(); // ?
        }

        BluetoothGatt nextGatt = _definedDevicesHashMap(nextAddress);
        if (/* Checks if 'nextAddress' is in _scannedDevices */
            /* And whether device 'IsActive()' */) {

            if (nextGatt == null) {
                nextGatt = connectToDeviceGattService(nextGatt)
            }
            else {
                // Do something here ?
            }
            _isDataSendingCompleteFromCurrentGatt = false;
        }
    }
}

3) The following variables/classes that I'm using

private boolean _isDataSendingCompleteFromCurrentGatt = false;
private boolean _isInitialConnectionHasBeenMade = false;
private HashMap<String, BluetoothGatt> _definedDevicesHashMap;
_definedDevicesHashMap.put("ff:ff:9f:c8:c2:93", null);
_definedDevicesHashMap.put("ff:ff:9f:c8:c4:91", null);
...

private HashMap<String, MyBLEDevice> _scannedDevices;

public class MyBLEDevice
{
    private final int deviceInactivityTimeout = 10;
    private String MacAddress;
    private Date _lastModifiedDate;
    public boolean isDeviceActive() {
        // Just gets the time difference (DateNow - lastModified) / 1000 < 10s
    }
}

4) Method which I use to connect to device

public BluetoothGatt connectToDeviceGattService(BluetoothGatt currentGatt, BluetoothDevice device, BluetoothGattCallback callback) {
    _bluetoothAdapter.cancelDiscovery();
    if (currentGatt == null) {
        currentGatt = device.connectGatt(_activity, true, callback);
    }
    else {
        // Is anything here needed ?
    }

    return currentGatt;
}

5) The BluetoothGatt callback

private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {

            // Discover services ?

        } else if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_DISCONNECTED) {

            // Do nothing ?

        } else if (status != BluetoothGatt.GATT_SUCCESS) {

            // Disconnect from current BluetoothGatt instance?
            // Also close the connection ?

            _isDataSendingCompleteFromCurrentGatt = true;
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        enableGattConfigurationCharacteristic();
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
        _gattServiceHandler.post(new Runnable() {
            @Override
            public void run() {
                handleMessage(Message.obtain(null, MSG_CHARACTERISTIC_CHANGE, characteristic));
            }
        });
    }
};

6) And finally, the handler which is used to receive data from Gatt callback

private static final int MSG_CHARACTERISTIC_CHANGE = 0;
private Handler _gattServiceHandler = new Handler();
private void handleMessage(Message msg) {
    BluetoothGattCharacteristic characteristic;
    switch (msg.what) {
        case MSG_CHARACTERISTIC_CHANGE: {
            characteristic = (BluetoothGattCharacteristic) msg.obj;
            if (BLELogic.PROPERTY_NOTIFY_CHAR_UUID.equals(characteristic.getUuid())) {

                String notification = BluetoothExtension.getCharacteristicValue(characteristic);
                if (notification.equals("end")) {
                    _isDataSendingCompleteFromCurrentGatt = true;
                } else {
                    UpdateViewOnGattNotificationSent(notification);
                }
            }
        }
        default:
            return;
    }
}

At the beginning I wanted to simplify all the logic, but it looks like when using BLE/Gatt service connections, there is nothing simple about this.


问:
How to compile Objective-C code in Visual Studio
I have an old project which is written in Objective-C. There were some in-house compilers written to compile from Objective-C to C code. However due to some compatibility issues those compilers aren't working anymore.

In Build 2015, Microsoft demonstrated building some objective-c code (.m) projects in Visual Studio. However I can't find the steps to do them.

Looking for the steps for the same. I have Visual Studio 2015 and 2017 both.

答:
I strongly believe you are talking about the WinObjC, the Windows bridge for iOS. It is an open-source project that provides an Objective-C development environment for Visual Studio and support for iOS APIs.

You have to install To Chocolatey & winobjc-tools to get started with an existing Xcode Project. The installation details are here : WinObjC Download and Installation


问:
rvalue reference usage: needed?
I have a class

```<code>class Person {
  // some other fields for this object
  std::vector<string> relatives;
}
</code>```

then a util function which returns a list of Person

```<code>std::vector<Person> getSomePerson() {
  // implementation details...
}
</code>```

Now I want to loop through:

```<code>for (auto&& p: getSomePerson()) {  <---- do I need the rvalue reference???
  // use p
  some_other_vector.insert(
      std::make_move_iterator(p.relatives.begin()),
      std::make_move_iterator(p.relatives.end())
  )
}
</code>```

Question: do I need the rvalue reference? Does it make any difference than using simple reference here?

答:
In your case:

```<code>for (auto&& p: getSomePerson()) {
for (auto& p: getSomePerson()) {
</code>```

those two lines are completely identical.

auto&& here is a forwarding reference.  It will deduce to be an rvalue or lvalue reference depending on what it is initialized with.

The range being iterated over is an rvalue of type vector.  Its iterator's operator* returns an lvalue reference.

So p will be an lvalue reference to a Person.

auto&& can be interpreted here (and many other spots) as "I do not care what I am binding to, but don't make any extra copies".  It is a reasonable default for a for(:) loop.

If your range returned values, auto&& would become an rvalue reference, and reference lifetime extension would occur.  auto& would fail to compile.

auto const& is another reasonable option here; it is much like auto&&, but you also promise not to modify the thing you are referring to.

Title: rvalue reference usage: needed?

Body:
I have a class

class Person {
  // some other fields for this object
  std::vector<string> relatives;
}

then a util function which returns a list of Person

std::vector<Person> getSomePerson() {
  // implementation details...
}

Now I want to loop through:

for (auto&& p: getSomePerson()) {  <---- do I need the rvalue reference???
  // use p
  some_other_vector.insert(
      std::make_move_iterator(p.relatives.begin()),
      std::make_move_iterator(p.relatives.end())
  )
}

Question: do I need the rvalue reference? Does it make any difference than using simple reference here?

Body:
In your case:

for (auto&& p: getSomePerson()) {
for (auto& p: getSomePerson()) {

those two lines are completely identical.

auto&& here is a forwarding reference.  It will deduce to be an rvalue or lvalue reference depending on what it is initialized with.

The range being iterated over is an rvalue of type vector.  Its iterator's operator* returns an lvalue reference.

So p will be an lvalue reference to a Person.

auto&& can be interpreted here (and many other spots) as "I do not care what I am binding to, but don't make any extra copies".  It is a reasonable default for a for(:) loop.

If your range returned values, auto&& would become an rvalue reference, and reference lifetime extension would occur.  auto& would fail to compile.

auto const& is another reasonable option here; it is much like auto&&, but you also promise not to modify the thing you are referring to.


问:
When to register a method that will call Form.Invoke to an event?
I get the following exception in a Windows Form application

System.InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

The method where the exception occurs calls this.Invoke (System.Windows.Forms.Form.Invoke). This method is registered to the event of another class in the constructor, which seems to lead to a race condition and this exception.

```<code>public Form1()
{
    InitializeComponent();
    SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod);
}

private void MyMethod()
{
    this.Invoke((MethodInvoker)delegate
    {
        // ... some code ...
    }
}
</code>```

At which stage of the form lifecycle is the Handle created? In which event of the form would it be safe to register the method to the foreign event?

答:
Ok, I now changed it to this:

```<code>public Form1(){
    InitializeComponent();
}
protected override void OnHandleCreated(EventArgs e)
{
    base.OnHandleCreated(e);
    SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod);
}
private void MyMethod()
{
    this.Invoke((MethodInvoker)delegate
    {
        // ... some code ...
    }
}
</code>```

an alternative version would be

```<code>public Form1(){
    InitializeComponent();
    SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod);
}
private void MyMethod()
{
    if (this.IsHandleCreated)
    {
        this.Invoke((MethodInvoker)delegate
        {
            // ... some code ...
        }
    }
}
</code>```

Body:
I get the following exception in a Windows Form application

System.InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

The method where the exception occurs calls this.Invoke (System.Windows.Forms.Form.Invoke). This method is registered to the event of another class in the constructor, which seems to lead to a race condition and this exception.

public Form1()
{
    InitializeComponent();
    SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod);
}

private void MyMethod()
{
    this.Invoke((MethodInvoker)delegate
    {
        // ... some code ...
    }
}

At which stage of the form lifecycle is the Handle created? In which event of the form would it be safe to register the method to the foreign event?

Body:
Ok, I now changed it to this:

public Form1(){
    InitializeComponent();
}
protected override void OnHandleCreated(EventArgs e)
{
    base.OnHandleCreated(e);
    SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod);
}
private void MyMethod()
{
    this.Invoke((MethodInvoker)delegate
    {
        // ... some code ...
    }
}

an alternative version would be

public Form1(){
    InitializeComponent();
    SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod);
}
private void MyMethod()
{
    if (this.IsHandleCreated)
    {
        this.Invoke((MethodInvoker)delegate
        {
            // ... some code ...
        }
    }
}


问:
How to connect tables
Im stuck with my code. I want everything from my serviceticket table to be shown with CUSTID. I get an error "ambiguous column name: CUSTID"
Can anyone help me? I have tried everything</p>

```<code>create table customers(CUSTID INTEGER PRIMARY KEY AUTOINCREMENT,
    FIRSTNAME TEXT(50),
    LASTNAME TEXT (50),
    STREET TEXT(50),
    CITY TEXT(50),
    ZIP INT(4),
    PHONENUMBER INT(8),
    EMAIL VARCHAR(50)
);

create table serviceticket(SERVICETICKETID int(2) NOT NULL PRIMARY KEY,
    TICKETNUMBER INT,
    CUSTID int,
    DATE_RECIEVED text,
    EXPECTED_DELIEVERYDATe TEXT,
    COMMENTS TEXT,
    DATE_RETURNED TEXT
);

insert into customers (FIRSTNAME, LASTNAME, STREET, CITY, ZIP, PHONENUMBER, EMAIL)
  values ('Jørgen', 'Marven', 'Dræmmestad 22', 'Gjøvik', 6026,12837262, 'jørge@gmail.com');

insert into serviceticket(SERVICETICKETID, TICKETNUMBER,CUSTID, DATE_RECIEVED, EXPECTED_DELIEVERYDATE, COMMENTS, DATE_RETURNED)
  values (56, 133, NULL, NULL, '12/4/19', '22/4/19', 'Wants authenic parts', '22/4/19');

select SERVICETICKETID, TICKETNUMBER, CUSTID, DATE_RECIEVED, EXPECTED_DELIEVERYDATE, COMMENTS, DATE_RETURNED
from serviceticket, customers
where serviceticket.CUSTID = customers.CUSTID;
</code>```

答:
You wrote select SERVICETICKETID, TICKETNUMBER, CUSTID, ... without specifying whether the CUSTID is from serviceticket or customers. Write

```<code>select SERVICETICKETID, TICKETNUMBER, customers.CUSTID, ...
</code>```

and you should use the join syntax that is newer than the where syntax for joining tables. You can also use table aliases to make the query more readable

```<code>select
    S.SERVICETICKETID, S.TICKETNUMBER, C.CUSTID, S.DATE_RECIEVED, S.EXPECTED_DELIEVERYDATE,
    S.COMMENTS, S.DATE_RETURNED
from
    serviceticket S
    INNER JOIN customers C
        ON S.CUSTID = C.CUSTID
</code>```

Title: How to connect tables

Body:
Im stuck with my code. I want everything from my serviceticket table to be shown with CUSTID. I get an error "ambiguous column name: CUSTID"
Can anyone help me? I have tried everything

create table customers(CUSTID INTEGER PRIMARY KEY AUTOINCREMENT,
    FIRSTNAME TEXT(50),
    LASTNAME TEXT (50),
    STREET TEXT(50),
    CITY TEXT(50),
    ZIP INT(4),
    PHONENUMBER INT(8),
    EMAIL VARCHAR(50)
);

create table serviceticket(SERVICETICKETID int(2) NOT NULL PRIMARY KEY,
    TICKETNUMBER INT,
    CUSTID int,
    DATE_RECIEVED text,
    EXPECTED_DELIEVERYDATe TEXT,
    COMMENTS TEXT,
    DATE_RETURNED TEXT
);

insert into customers (FIRSTNAME, LASTNAME, STREET, CITY, ZIP, PHONENUMBER, EMAIL)
  values ('Jørgen', 'Marven', 'Dræmmestad 22', 'Gjøvik', 6026,12837262, 'jørge@gmail.com');

insert into serviceticket(SERVICETICKETID, TICKETNUMBER,CUSTID, DATE_RECIEVED, EXPECTED_DELIEVERYDATE, COMMENTS, DATE_RETURNED)
  values (56, 133, NULL, NULL, '12/4/19', '22/4/19', 'Wants authenic parts', '22/4/19');

select SERVICETICKETID, TICKETNUMBER, CUSTID, DATE_RECIEVED, EXPECTED_DELIEVERYDATE, COMMENTS, DATE_RETURNED
from serviceticket, customers
where serviceticket.CUSTID = customers.CUSTID;

Body:
You wrote select SERVICETICKETID, TICKETNUMBER, CUSTID, ... without specifying whether the CUSTID is from serviceticket or customers. Write

select SERVICETICKETID, TICKETNUMBER, customers.CUSTID, ...

and you should use the join syntax that is newer than the where syntax for joining tables. You can also use table aliases to make the query more readable

select
    S.SERVICETICKETID, S.TICKETNUMBER, C.CUSTID, S.DATE_RECIEVED, S.EXPECTED_DELIEVERYDATE,
    S.COMMENTS, S.DATE_RETURNED
from
    serviceticket S
    INNER JOIN customers C
        ON S.CUSTID = C.CUSTID


问:
How to increase code font size in IntelliJ?
I tried doing it via Appearances as shown, but this seems to not affect code font or size

How can this be done please?

答: The font used in menus, dialogs and tool windows can be changed in Settings > Appearance & Behavior > Use custom font.


问:
OnTriggerEnter firing too late
I'm trying to make a sticky grenade by disabling its rigidbody upon collision, using OnCollisionEnter(). However, OnCollisionEnter() fires when there is clearly no collision happening, as you can see in this image : https://imgur.com/w9KMEff. This causes my grenade to stick in the air. I suspect this is due to a lack of synchronization between physics loop & rendering loop. Also, my standard "non-sticky" grenade uses the same model & is working finely.

I already tried the following :

Verify that there are no other colliders which could cause my grenade
to "stick in the air"

Use OnTriggerEnter()  instead. The result is a little better but the problem is that it is fired too late, only once the grenade is inside an obstacle or an enemy.

Add rigidbody & continuous collision detection to all objects

Tweak PhysicsManager.DefaultContactOffset from 0.01 to 0.001, as suggested by Eliasar

Switch from "PCM" to "Legacy Contacts Generation"

None of these worked so I'm feeling a little desperate. Thanks in advance for your help !

Code I use to stick the grenade upon collision :

```<code>void OnCollisionEnter(Collision c) {
   rigidbody.isKinematic = true;
   transform.parent = c.transform;
}
</code>```

答:
PhysicsManager.DefaultContactOffset might be set too high for your object scale

According to this Unity forum post, your physics margin might be too high if your objects' scales are too small. OnCollisionEnter will fire during a Physics tick and may update your grenade's position a frame sooner than you're expecting. That would explain why it would stick outside the contact point, whereas OnTriggerEnter would process 1 frame later.

Unity post in text form

Max_van_Hell, Jun 1, 2017

oh god yeah Baby, I finally found the issue!

Appearantly the PhysicsManager.DefaultContactOffset was too high for my scale. The Default contact Offset was about 0.02 and with virtual objects which are around 10cm it yields a HUGE error margin obviously.

That never was a Problem for me, since in most graphics or game projects the scale of the objects is actually much larger so that such a contact Offset does not have a huge influence.

However, since this is a HoloLens Project and I am working with virtual objects which are around 10cm - 100cm the contact offset is more sensible.

Anyway, thank you much for your help!

cheers,

Title: OnTriggerEnter firing too late

Body:
I'm trying to make a sticky grenade by disabling its rigidbody upon collision, using OnCollisionEnter(). However, OnCollisionEnter() fires when there is clearly no collision happening, as you can see in this image : https://imgur.com/w9KMEff. This causes my grenade to stick in the air. I suspect this is due to a lack of synchronization between physics loop & rendering loop. Also, my standard "non-sticky" grenade uses the same model & is working finely.

I already tried the following :

Verify that there are no other colliders which could cause my grenade
to "stick in the air"

Use OnTriggerEnter()  instead. The result is a little better but the problem is that it is fired too late, only once the grenade is inside an obstacle or an enemy.

Add rigidbody & continuous collision detection to all objects

Tweak PhysicsManager.DefaultContactOffset from 0.01 to 0.001, as suggested by Eliasar

Switch from "PCM" to "Legacy Contacts Generation"

None of these worked so I'm feeling a little desperate. Thanks in advance for your help !

Code I use to stick the grenade upon collision :

void OnCollisionEnter(Collision c) {
   rigidbody.isKinematic = true;
   transform.parent = c.transform;
}


问:
How to display Google captcha?
My Google captcha has had the ends chopped off, particularly the right end in both mobile mobile and desktop?

Why is this?

I have the following html:

```<code>"wpcf7-form-control-wrap your-subject"><input type="text"
name="your-subject" value="" size="40" class="wpcf7-form-control
wpcf7-text" aria-invalid="false" /></span> </label></p>
<p><label> Your Message<br />
<span class="wpcf7-form-control-wrap your-message"><textarea
name="your-message" cols="40" rows="10" class="wpcf7-form-control
wpcf7-textarea" aria-invalid="false"></textarea></span> </label></p>
<p><div class="anr_captcha_field"><div id="anr_captcha_field_1"
class="anr_captcha_field_div"></div></div><span class="wpcf7-form-
control-wrap g-recaptcha-response"></span></p>
<p><input type="submit" value="Send" class="wpcf7-form-control
wpcf7-submit" /></p>
<div class="wpcf7-response-output wpcf7-display-none"></div></form>.
</div></div><!-- .entry-content -->
<footer class="entry-footer">
</footer><!-- .entry-footer -->
</code>```

And the following css:

```<code>#anr_captcha_field_1 {overflow: hidden;
border-radius: 0px;
transform: scale(0.9);
transform-origin: left top;
margin-left:35px; background-color: #fff; border: none;
}

@media (max-width: 5000px) and (min-width: 768px)
{#anr_captcha_field_1 {

overflow: hidden;
border-radius: 0px;
transform: scale(0.9);
transform-origin: left top;
margin-left:10px; background-color: #fff; border: none;
}}
</code>```

The problem arose because I wanted to centre the capture in desktop, now the right end's chopped off.

Page: https://adsler.co.uk/contact-us/

答:
Add to your CSS:

```<code>.anr_captcha_field {
  display: inline-block;
  margin-left: -10px;
}

@media (max-width: 768px) {
  .anr_captcha_field {
      margin-left: 0;
  }
}
</code>```

This should help solve your problem

Title: How to display Google captcha?

Body:
My Google captcha has had the ends chopped off, particularly the right end in both mobile mobile and desktop?

Why is this?

I have the following html:

"wpcf7-form-control-wrap your-subject"><input type="text"
name="your-subject" value="" size="40" class="wpcf7-form-control
wpcf7-text" aria-invalid="false" />

 Your Message

<textarea
name="your-message" cols="40" rows="10" class="wpcf7-form-control
wpcf7-textarea" aria-invalid="false"></textarea>

<input type="submit" value="Send" class="wpcf7-form-control
wpcf7-submit" />

</form>.

And the following css:

#anr_captcha_field_1 {overflow: hidden;
border-radius: 0px;
transform: scale(0.9);
transform-origin: left top;
margin-left:35px; background-color: #fff; border: none;
}

@media (max-width: 5000px) and (min-width: 768px)
{#anr_captcha_field_1 {

overflow: hidden;
border-radius: 0px;
transform: scale(0.9);
transform-origin: left top;
margin-left:10px; background-color: #fff; border: none;
}}

The problem arose because I wanted to centre the capture in desktop, now the right end's chopped off.

Page: https://adsler.co.uk/contact-us/

Body:
Add to your CSS:

.anr_captcha_field {
  display: inline-block;
  margin-left: -10px;
}

@media (max-width: 768px) {
  .anr_captcha_field {
      margin-left: 0;
  }
}

This should help solve your problem


问:
Travelling salesman problem for a tree graph (no hamiltonian path)
Almost broken my head while trying to find algorithm that finds fastest route in graph that pass through ALL graph vertices from start vertex (with no need to return to start edge).

I have checked all the main algorithms for graphs and similar problems on stackoverflow.

Almost all TSP examples I googled was for complete graphs.

TSPLIB not looks like can solve my problem.

Sorry if I missed something.

Input graph (check images):

• Weighted

• Undirected

• Planar

• No hamiltonian path

• No negative edges

• Size: up to 100 vertices (but usually  50-70)

Edge length almost the same in graph, so we can say that this is an unweighted graph and take 1 as a length of edge.

Should solve with "dead end" cases:

Real input graphs looks like this (start from vertex 0):

Big graph:

Expected result:

• Shortest path (a set of vertices indices) through all the edges from start edge.

• No need to return to start edge at the end

Got only one idea:

1) Check all possible combinations of path, measure the distance and find the path with smallest distance.

1a) Use Depth-First Search or Breadth-First Search

1b) If while iterating the current vertex have more than one edge - make a separate combinations for all of them (try all possible ways).

1c) In my case there are a lot of “dead end” in graph, so algorithm should find the way (the fastest ofc) from there and iterate through already passed vertices and not get stuck.

2) Reconstruct the path

Maybe I should use Minimum Spanning Trees algorithm here too…

Or maybe for faster calculation I should split my graph to multiple smallest that are linked only with single edge (like 49-52, 40-41 on screenshot)

Any help will be appreciated.

Prefer C# examples (libs) but I can port code from any language.

答:
I  my case this NP-hard problem should be solved fast as possible and not so perfectly, so I used the best solution for me (simplified version) (best case scenario should be O(n+n*m), n - nodes, m - edges):

Use Breadth-first search (BFS) to find the deepest (far) node from start (let's call it FAR_NODE)

Use Djkstra algorithm to calculate distance from FAR_NODE to all the other nodes (actually I was using BFS algorithm here too because for euclidian space it is faster and gives the same result)... so just save distance in all nodes from FAR_NODE.

Start walking through the graph from start node to nearest not passed, prefer nodes with bigger "distance from FAR_NODE"

If there is no not passed nodes linked to current node- chose the nearest not passed node (preferred with with biggest "distance" value)(can use BFS too).

Algorithm is published and documented here(with animations): https://github.com/Stridemann/TravelShortPathFinder

===================================================

Using Branch&Bound way:

As I mentioned in comment to my question I almost solved this in branch&bound way. The idea is to give a score to each permutation and process only with bigger score.

If someone interesting this is example code:

using System.Collections.Generic;
using System.Linq;
using GraphFastPath.GraphData;

namespace GraphFastPath
{
    public class BranchNBound
    {
        public static BranchNBound Instance;
        private readonly Graph _graph;
        public bool _ignoreDeadEnds;
        public SortedDictionary<float, List<BbIterationStep>> _iterations = new SortedDictionary<float, List<BbIterationStep>>();
        public List<BbIterationStep> BestPath = new List<BbIterationStep>();
        public int IdCounter;
        public int MaxNodesVisited;
        public BbIterationStep PathNode;

        public BranchNBound(Graph graph, bool ignoreDeadEnds)
        {
            _graph = graph;
            _ignoreDeadEnds = ignoreDeadEnds;
            Instance = this;

            var nodesCount = ignoreDeadEnds ? _graph.Nodes.Count(x => !x.IsDeadEnd) : _graph.Nodes.Count;

            foreach (var edge in _graph.Nodes[0].Edges)
                AddStep(new BbIterationStep(edge, nodesCount), 1000);
        }

        public int IterationsCount => _iterations.Sum(x => x.Value.Count);

        public void RegisterGoodPath(BbIterationStep step)
        {
            if (step._uniqPassedNodesCount < MaxNodesVisited)
                return;

            if (step._uniqPassedNodesCount > MaxNodesVisited)
            {
                BestPath.Clear();
                MaxNodesVisited = step._uniqPassedNodesCount;
            }

            BestPath.Add(step);
        }

        public void DoStep()
        {
            var min = _iterations.Last();
            var list = min.Value;
            _iterations.Remove(min.Key);

            foreach (var step in list)
                step.DoStep();
        }

        public void AddStep(BbIterationStep step, float cost)
        {
            step.VariantId = IdCounter++;

            if (!_iterations.TryGetValue(cost, out var list))
            {
                list = new List<BbIterationStep>();
                _iterations.Add(cost, list);
            }

            list.Add(step);
        }
    }

    public class BbIterationStep
    {
        private readonly int _totalNodesCount;
        private readonly Edge _currentEdge;
        private int _totalPassedNodesCount;
        public int _uniqPassedNodesCount;

        public string Debug;
        public List<Node> LocalPath = new List<Node>();
        public Node Node;
        public BbIterationStep Parent;
        public float Score;

        public int VariantId;

        public BbIterationStep(Edge currentEdge, int nodesCount)
        {
            _currentEdge = currentEdge;
            _totalNodesCount = nodesCount;
            Node = _currentEdge.From;
            _uniqPassedNodesCount++;
            _totalPassedNodesCount++;
        }

        public BbIterationStep(BbIterationStep from, Edge currentEdge, string debug, float score)
        {
            Parent = from;
            Score = score;
            _currentEdge = currentEdge;
            Debug = debug;

            Node = _currentEdge.From;
            _uniqPassedNodesCount = from._uniqPassedNodesCount;
            _totalPassedNodesCount = from._totalPassedNodesCount;
            _totalNodesCount = from._totalNodesCount;
        }

        public int Id => _currentEdge.From.Id;
        public Node NodeTo => _currentEdge.To;

        public void DoStep()
        {
            _currentEdge.Pass(false);
            _currentEdge.To.SetProcessed();
            var passed = CheckPassed(_currentEdge.To);

            if (!passed)
            {
                _uniqPassedNodesCount++;

                if (BranchNBound.Instance.MaxNodesVisited < _uniqPassedNodesCount)
                    BranchNBound.Instance.RegisterGoodPath(this);

                if (_uniqPassedNodesCount == _totalNodesCount)
                    BranchNBound.Instance.PathNode = this;
            }

            _totalPassedNodesCount++;

            var totalDistFromStartMin = float.MaxValue;
            var totalDistFromStartMax = float.MinValue;

            foreach (var edge in _currentEdge.To.Edges)
            {
                var dist = edge.To.DistanceFromStart;
                var nextNodePassedCount = CountPassed(edge.To);

                if (nextNodePassedCount > 0)
                    dist *= nextNodePassedCount + 2;

                if (totalDistFromStartMin > dist)
                    totalDistFromStartMin = dist;

                if (totalDistFromStartMax < dist)
                    totalDistFromStartMax = dist;
            }

            var delta = totalDistFromStartMax - totalDistFromStartMin;

            if (delta == 0)
                delta = totalDistFromStartMax;

            foreach (var edge in _currentEdge.To.Edges)
            {
                if (BranchNBound.Instance._ignoreDeadEnds && edge.To.IsDeadEnd)
                    continue;

                var deltaGoodFromStart = 1 - (edge.To.DistanceFromStart - totalDistFromStartMin) / delta; // + float.Epsilon;

                if (float.IsNaN(deltaGoodFromStart))
                {
                    var test = 1;
                }

                MoveNextEdge(edge, deltaGoodFromStart);
            }
        }

        private void MoveNextEdge(Edge edge, float deltaGoodFromStart)
        {
            var nextNodePassedCount = CountPassed(edge.To);

            var progressScale = (float) _uniqPassedNodesCount / _totalNodesCount; //weight 200    :Total path search progress (how much it is completed/finished)
            var nextNodeScoreScale = 1f / (nextNodePassedCount * nextNodePassedCount + 1); //weight 200    :Lower value if next node was visited more times

            var pc = _uniqPassedNodesCount;

            if (nextNodePassedCount == 0)
                pc++;

            var pathNoRepeatedNodesScoreScale = (float) pc / (_totalPassedNodesCount + 1); //weight 400    :Higher value if all nodes was visited less times

            var progressScaleValue = progressScale * 1;
            var nextNodeScoreValue = nextNodeScoreScale * 300;
            var deltaGoodFromStartValue = deltaGoodFromStart * 500 * nextNodeScoreScale;
            var pathNoRepeatedNodesScoreValue = pathNoRepeatedNodesScoreScale * 800;

             //iterations with bigger score will be processed earlier
            var totalScore = progressScaleValue +
                             nextNodeScoreValue +
                             deltaGoodFromStartValue +
                             pathNoRepeatedNodesScoreValue;

            var dbg = $"Progress: {progressScaleValue} NextNode({edge.To.Id}): {nextNodeScoreValue} GoodStart: {deltaGoodFromStartValue} NoRepeat: {pathNoRepeatedNodesScoreValue}";

            var newStep = new BbIterationStep(this, edge, dbg, totalScore);
            BranchNBound.Instance.AddStep(newStep, totalScore);
        }

        public bool CheckPassed(Node node)
        {
            var checkStep = this;

            do
            {
                if (checkStep.Node == node)
                    return true;

                checkStep = checkStep.Parent;
            } while (checkStep != null);

            return false;
        }

        public void GetPathEdges(List<Edge> result)
        {
            var checkStep = this;

            do
            {
                result.Add(checkStep._currentEdge);
                checkStep = checkStep.Parent;
            } while (checkStep != null);
        }

        private int CountPassed(Node node)
        {
            var passedCount = 0;
            var checkStep = this;

            do
            {
                if (checkStep.Node == node)
                    passedCount++;

                checkStep = checkStep.Parent;
            } while (checkStep != null);

            return passedCount;
        }

        public override string ToString()
        {
            return Parent == null ? Id.ToString() : $"({Score}) ({VariantId}), {Debug}";
        }

        public string GetPath()
        {
            return Parent == null ? Id.ToString() : $"{Parent.GetPath()}-{Id}";
        }
    }
}```

Most interesting part is MoveNextEdge function that calculates a score for each permutation.

Body:
I  my case this NP-hard problem should be solved fast as possible and not so perfectly, so I used the best solution for me (simplified version) (best case scenario should be O(n+n*m), n - nodes, m - edges):

Use Breadth-first search (BFS) to find the deepest (far) node from start (let's call it FAR_NODE)

Use Djkstra algorithm to calculate distance from FAR_NODE to all the other nodes (actually I was using BFS algorithm here too because for euclidian space it is faster and gives the same result)... so just save distance in all nodes from FAR_NODE.

Start walking through the graph from start node to nearest not passed, prefer nodes with bigger "distance from FAR_NODE"

If there is no not passed nodes linked to current node- chose the nearest not passed node (preferred with with biggest "distance" value)(can use BFS too).

Algorithm is published and documented here(with animations): https://github.com/Stridemann/TravelShortPathFinder

===================================================

Using Branch&Bound way:

As I mentioned in comment to my question I almost solved this in branch&bound way. The idea is to give a score to each permutation and process only with bigger score.

If someone interesting this is example code:

using System.Collections.Generic;
using System.Linq;
using GraphFastPath.GraphData;

namespace GraphFastPath
{
    public class BranchNBound
    {
        public static BranchNBound Instance;
        private readonly Graph _graph;
        public bool _ignoreDeadEnds;
        public SortedDictionary<float, List<BbIterationStep>> _iterations = new SortedDictionary<float, List<BbIterationStep>>();
        public List<BbIterationStep> BestPath = new List<BbIterationStep>();
        public int IdCounter;
        public int MaxNodesVisited;
        public BbIterationStep PathNode;

        public BranchNBound(Graph graph, bool ignoreDeadEnds)
        {
            _graph = graph;
            _ignoreDeadEnds = ignoreDeadEnds;
            Instance = this;

            var nodesCount = ignoreDeadEnds ? _graph.Nodes.Count(x => !x.IsDeadEnd) : _graph.Nodes.Count;

            foreach (var edge in _graph.Nodes[0].Edges)
                AddStep(new BbIterationStep(edge, nodesCount), 1000);
        }

        public int IterationsCount => _iterations.Sum(x => x.Value.Count);

        public void RegisterGoodPath(BbIterationStep step)
        {
            if (step._uniqPassedNodesCount < MaxNodesVisited)
                return;

            if (step._uniqPassedNodesCount > MaxNodesVisited)
            {
                BestPath.Clear();
                MaxNodesVisited = step._uniqPassedNodesCount;
            }

            BestPath.Add(step);
        }

        public void DoStep()
        {
            var min = _iterations.Last();
            var list = min.Value;
            _iterations.Remove(min.Key);

            foreach (var step in list)
                step.DoStep();
        }

        public void AddStep(BbIterationStep step, float cost)
        {
            step.VariantId = IdCounter++;

            if (!_iterations.TryGetValue(cost, out var list))
            {
                list = new List<BbIterationStep>();
                _iterations.Add(cost, list);
            }

            list.Add(step);
        }
    }

    public class BbIterationStep
    {
        private readonly int _totalNodesCount;
        private readonly Edge _currentEdge;
        private int _totalPassedNodesCount;
        public int _uniqPassedNodesCount;

        public string Debug;
        public List<Node> LocalPath = new List<Node>();
        public Node Node;
        public BbIterationStep Parent;
        public float Score;

        public int VariantId;

        public BbIterationStep(Edge currentEdge, int nodesCount)
        {
            _currentEdge = currentEdge;
            _totalNodesCount = nodesCount;
            Node = _currentEdge.From;
            _uniqPassedNodesCount++;
            _totalPassedNodesCount++;
        }

        public BbIterationStep(BbIterationStep from, Edge currentEdge, string debug, float score)
        {
            Parent = from;
            Score = score;
            _currentEdge = currentEdge;
            Debug = debug;

            Node = _currentEdge.From;
            _uniqPassedNodesCount = from._uniqPassedNodesCount;
            _totalPassedNodesCount = from._totalPassedNodesCount;
            _totalNodesCount = from._totalNodesCount;
        }

        public int Id => _currentEdge.From.Id;
        public Node NodeTo => _currentEdge.To;

        public void DoStep()
        {
            _currentEdge.Pass(false);
            _currentEdge.To.SetProcessed();
            var passed = CheckPassed(_currentEdge.To);

            if (!passed)
            {
                _uniqPassedNodesCount++;

                if (BranchNBound.Instance.MaxNodesVisited < _uniqPassedNodesCount)
                    BranchNBound.Instance.RegisterGoodPath(this);

                if (_uniqPassedNodesCount == _totalNodesCount)
                    BranchNBound.Instance.PathNode = this;
            }

            _totalPassedNodesCount++;

            var totalDistFromStartMin = float.MaxValue;
            var totalDistFromStartMax = float.MinValue;

            foreach (var edge in _currentEdge.To.Edges)
            {
                var dist = edge.To.DistanceFromStart;
                var nextNodePassedCount = CountPassed(edge.To);

                if (nextNodePassedCount > 0)
                    dist *= nextNodePassedCount + 2;

                if (totalDistFromStartMin > dist)
                    totalDistFromStartMin = dist;

                if (totalDistFromStartMax < dist)
                    totalDistFromStartMax = dist;
            }

            var delta = totalDistFromStartMax - totalDistFromStartMin;

            if (delta == 0)
                delta = totalDistFromStartMax;

            foreach (var edge in _currentEdge.To.Edges)
            {
                if (BranchNBound.Instance._ignoreDeadEnds && edge.To.IsDeadEnd)
                    continue;

                var deltaGoodFromStart = 1 - (edge.To.DistanceFromStart - totalDistFromStartMin) / delta; // + float.Epsilon;

                if (float.IsNaN(deltaGoodFromStart))
                {
                    var test = 1;
                }

                MoveNextEdge(edge, deltaGoodFromStart);
            }
        }

        private void MoveNextEdge(Edge edge, float deltaGoodFromStart)
        {
            var nextNodePassedCount = CountPassed(edge.To);

            var progressScale = (float) _uniqPassedNodesCount / _totalNodesCount; //weight 200    :Total path search progress (how much it is completed/finished)
            var nextNodeScoreScale = 1f / (nextNodePassedCount * nextNodePassedCount + 1); //weight 200    :Lower value if next node was visited more times

            var pc = _uniqPassedNodesCount;

            if (nextNodePassedCount == 0)
                pc++;

            var pathNoRepeatedNodesScoreScale = (float) pc / (_totalPassedNodesCount + 1); //weight 400    :Higher value if all nodes was visited less times

            var progressScaleValue = progressScale * 1;
            var nextNodeScoreValue = nextNodeScoreScale * 300;
            var deltaGoodFromStartValue = deltaGoodFromStart * 500 * nextNodeScoreScale;
            var pathNoRepeatedNodesScoreValue = pathNoRepeatedNodesScoreScale * 800;

             //iterations with bigger score will be processed earlier
            var totalScore = progressScaleValue +
                             nextNodeScoreValue +
                             deltaGoodFromStartValue +
                             pathNoRepeatedNodesScoreValue;

            var dbg = $"Progress: {progressScaleValue} NextNode({edge.To.Id}): {nextNodeScoreValue} GoodStart: {deltaGoodFromStartValue} NoRepeat: {pathNoRepeatedNodesScoreValue}";

            var newStep = new BbIterationStep(this, edge, dbg, totalScore);
            BranchNBound.Instance.AddStep(newStep, totalScore);
        }

        public bool CheckPassed(Node node)
        {
            var checkStep = this;

            do
            {
                if (checkStep.Node == node)
                    return true;

                checkStep = checkStep.Parent;
            } while (checkStep != null);

            return false;
        }

        public void GetPathEdges(List<Edge> result)
        {
            var checkStep = this;

            do
            {
                result.Add(checkStep._currentEdge);
                checkStep = checkStep.Parent;
            } while (checkStep != null);
        }

        private int CountPassed(Node node)
        {
            var passedCount = 0;
            var checkStep = this;

            do
            {
                if (checkStep.Node == node)
                    passedCount++;

                checkStep = checkStep.Parent;
            } while (checkStep != null);

            return passedCount;
        }

        public override string ToString()
        {
            return Parent == null ? Id.ToString() : $"({Score}) ({VariantId}), {Debug}";
        }

        public string GetPath()
        {
            return Parent == null ? Id.ToString() : $"{Parent.GetPath()}-{Id}";
        }
    }
}

Most interesting part is MoveNextEdge function that calculates a score for each permutation.


问:
Change iFrame src on ajax complete
using jQuery's $.ajax() I want to retrieve some information from the server, and then, based on that info, change the src attribute of an iframe.

Something like:

```<code>$.ajax(
                {
                    url: "someUrl.aspx/getInfo",
                    dataType: "json",
                    data: "{'data':{'data1':'data1'}}",
                    type: "post",
                    contentType: "application/json; charset=utf-8",
                    complete: function(data, stat) {
                        if (stat == "success" )
                        {
                           var src = JSON.parse(jsondata.responseText).d.src
                           $('#myframe').attr("src",src);
                        }

                    }
                }
                );
</code>```

The page I am trying to load is returning a PDF file, so the goal is to show the user the dialog to choose between downloading or opening that file. On IE7 and 8 the browser is showing the info bar with this message : "To help protect your security, Internet Explorer blocked this site from downloading files to your computer. Click here for options."

Changing the iframe's src attribute OUTSIDE the ajax call works fine and the dialog to choose between opening or saving the PDF is shown.

Any workarounds to avoid the info bar showing?
Thanks in advance.

答:
I am not sure if it'll work, but you can try this:

```<code>var alterIframe = function(src){
   $('#myframe').attr("src",src);
};

$.ajax(
        {
            url: "someUrl.aspx/getInfo",
            dataType: "json",
            data: "{'data':{'data1':'data1'}}",
            type: "post",
            contentType: "application/json; charset=utf-8",
            complete: function(data, stat) {
                if (stat == "success" ) {
                    data = $.parseJSON(data);
                    setTimeout('alterIframe("' + data.src + '")',300);
                }
            }
        }
);
</code>```

I hope this helps you ;)

Title: Change iFrame src on ajax complete

Body:
using jQuery's $.ajax() I want to retrieve some information from the server, and then, based on that info, change the src attribute of an iframe.

Something like:

$.ajax(
                {
                    url: "someUrl.aspx/getInfo",
                    dataType: "json",
                    data: "{'data':{'data1':'data1'}}",
                    type: "post",
                    contentType: "application/json; charset=utf-8",
                    complete: function(data, stat) {
                        if (stat == "success" )
                        {
                           var src = JSON.parse(jsondata.responseText).d.src
                           $('#myframe').attr("src",src);
                        }

                    }
                }
                );

The page I am trying to load is returning a PDF file, so the goal is to show the user the dialog to choose between downloading or opening that file. On IE7 and 8 the browser is showing the info bar with this message : "To help protect your security, Internet Explorer blocked this site from downloading files to your computer. Click here for options."

Changing the iframe's src attribute OUTSIDE the ajax call works fine and the dialog to choose between opening or saving the PDF is shown.

Any workarounds to avoid the info bar showing?
Thanks in advance.

Body:
I am not sure if it'll work, but you can try this:

var alterIframe = function(src){
   $('#myframe').attr("src",src);
};

$.ajax(
        {
            url: "someUrl.aspx/getInfo",
            dataType: "json",
            data: "{'data':{'data1':'data1'}}",
            type: "post",
            contentType: "application/json; charset=utf-8",
            complete: function(data, stat) {
                if (stat == "success" ) {
                    data = $.parseJSON(data);
                    setTimeout('alterIframe("' + data.src + '")',300);
                }
            }
        }
);

I hope this helps you ;)


问:
Where do I put the Main method?
I am new to Java and I am confused on where to place the Main method. I am still getting an error that reads "Could not find or load main class PuzzleJava.java"

I have tried to run numerous terminal commands and switch up the placement of the main method but I have had no luck.

```<code> import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Random;

 public class PuzzleJava{

     public static ArrayList<Integer> firstArray (){
         ArrayList<Integer> numbers = new ArrayList<Integer>();
         int[] myArray = {3,5,1,2,7,9,8,13,25,32};
         int sum = 0;
         for(int num : myArray){
             sum+=num;
             if(num>10){
                 numbers.add(num);
             }
         }
         System.out.println("Sum: "+sum);
         return numbers;

     }
      public static void main(String[] args){
         System.out.println(firstArray());
 }
</code>```

I want this to be able to print out a new array of numbers greater than 10.

答:
IDK what error you were getting but I think you are missing are curly bracket. It ran fine on my IDE.

```<code>import java.util.ArrayList;

public class PuzzleJava {

    public static ArrayList<Integer> firstArray() {
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        int[] myArray = { 3, 5, 1, 2, 7, 9, 8, 13, 25, 32 };
        int sum = 0;
        for (int num : myArray) {
            sum += num;
            if (num > 10) {
                numbers.add(num);
            }
        }
        System.out.println("Sum: " + sum);
        return numbers;

    }

    public static void main(String[] args) {
        System.out.println(firstArray());
    } //<- you forgot this
}
</code>```

output:

```<code>Sum: 105
[13, 25, 32]
</code>```

These imports are not being used in the code snippet above that's why I removed it.

```<code>import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
</code>```

Title: Where do I put the Main method?

Body:
I am new to Java and I am confused on where to place the Main method. I am still getting an error that reads "Could not find or load main class PuzzleJava.java"

I have tried to run numerous terminal commands and switch up the placement of the main method but I have had no luck.

 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Random;

 public class PuzzleJava{

     public static ArrayList<Integer> firstArray (){
         ArrayList<Integer> numbers = new ArrayList<Integer>();
         int[] myArray = {3,5,1,2,7,9,8,13,25,32};
         int sum = 0;
         for(int num : myArray){
             sum+=num;
             if(num>10){
                 numbers.add(num);
             }
         }
         System.out.println("Sum: "+sum);
         return numbers;

     }
      public static void main(String[] args){
         System.out.println(firstArray());
 }

I want this to be able to print out a new array of numbers greater than 10.

Body:
IDK what error you were getting but I think you are missing are curly bracket. It ran fine on my IDE.

import java.util.ArrayList;

public class PuzzleJava {

    public static ArrayList<Integer> firstArray() {
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        int[] myArray = { 3, 5, 1, 2, 7, 9, 8, 13, 25, 32 };
        int sum = 0;
        for (int num : myArray) {
            sum += num;
            if (num > 10) {
                numbers.add(num);
            }
        }
        System.out.println("Sum: " + sum);
        return numbers;

    }

    public static void main(String[] args) {
        System.out.println(firstArray());
    } //<- you forgot this
}

output:

Sum: 105
[13, 25, 32]

These imports are not being used in the code snippet above that's why I removed it.

import java.util.Arrays;
import java.util.Collections;
import java.util.Random;


问:
AttributeError: 'numpy.ndarray' object has no attribute 'nipy_spectral'
I am dealing with error

"AttributeError: 'numpy.ndarray' object has no attribute 'nipy_spectral'"

while running silhouette analysis.

The original code was taken from here. I have added the line that shows the error:

```<code>color = cm.nipy_spectral(float(i) / n_clusters)
</code>```

答:
Here is the snippet of the input data and the result of running print(type(cm)).
Screenshot</p>

Body:
I am dealing with error

"AttributeError: 'numpy.ndarray' object has no attribute 'nipy_spectral'"

while running silhouette analysis.

The original code was taken from here. I have added the line that shows the error:

color = cm.nipy_spectral(float(i) / n_clusters)


问:
How to match table 	 based on 	 in Umbraco
i have some issues trying to match th with the td elements on the table, my code works fine but i shows the data but not in order of the th.
What can i do to make this works as pretend??
Any Help would be apreciated

My Code

```<code><div class="table-responsive ">
                <table class="table table-striped ">
                  <thead>
                    <tr>
                      <th scope="col">Fundo</th>
                      <th scope="col">IFI</th>
                      <th scope="col">Prospeto</th>
                      <th scope="col">KiiD</th>
                      <th scope="col">Mercado Alvo</th>
                      <th scope="col">Síntese Mensal</th>
                      <th scope="col">Relatório Mensal</th>
                      <th scope="col">Relatório Semestral</th>
                      <th scope="col">Relatório Anual</th>
                    </tr>
                  </thead>
                 <tbody>

                     @foreach (var page in selection.Children){

                        if(page.Children.Count() > 0){

                        foreach(var subpage in page.Children){

                            var listaPdf = subpage.GetPropertyValue<IEnumerable<IPublishedContent>>("listaPdfsFundos");

                               if(listaPdf == null) {
                                    listaPdf = new List<IPublishedContent>();
                                }

                                 <tr>

                                 <td >@subpage.Name</td>

                                 @if(listaPdf != null){

                                    foreach(var row in listaPdf) {

                                    var name = Umbraco.Field(row, "categoriaDoFundo");

                                    var id = Umbraco.Field(row, "documentos").ToString();

                                    var mediaItem = Umbraco.TypedMedia(id);

                                    var url = mediaItem.Url;

                                    <td> <a href="@url" target="_blank"><i class="far fa-file-pdf"></i> </a> </td>

                                    }
                                }
                       </tr>
                    }
                }
             }

              </div>
</code>```

答:
This is all to do with the structure of your data and the way you are trying to lay it out in a table that has a fixed number of columns

Anyway from your picture and your html, it looks like you have 9 columns.

You populate listaPdf with

```<code>var listaPdf = subpage.GetPropertyValue<IEnumerable<IPublishedContent>>("listaPdfsFundos");`
</code>```

A little after that, you write the first column

```<code><td >@subpage.Name</td>
</code>```

which is definitely okay. So that is 1 column down and 8 to go.

Now your problems start.  In order for your code to work, you must write out 8 *  items in order to match your  headers (1 already written)  + 8).

If listaPdf does not contain exactly 8 items then it is not going to work. Your picture above suggests that listPdf contained 3 items so you have written out 4 *  which do not match up with the 9 *

So the first thing to check is whether listaPdf contains 8 items.  If it doesn't you cannot make the above code work without finding some way to link each mediaItem to the correct column.

Is there anything in each mediaItem that links that item to the correct column?

Title: How to match table 	 based on 	 in Umbraco

Body:
i have some issues trying to match th with the td elements on the table, my code works fine but i shows the data but not in order of the th.
What can i do to make this works as pretend??
Any Help would be apreciated

My Code

                      Fundo
                      IFI
                      Prospeto
                      KiiD
                      Mercado Alvo
                      Síntese Mensal
                      Relatório Mensal
                      Relatório Semestral
                      Relatório Anual

                     @foreach (var page in selection.Children){

                        if(page.Children.Count() > 0){

                        foreach(var subpage in page.Children){

                            var listaPdf = subpage.GetPropertyValue<IEnumerable<IPublishedContent>>("listaPdfsFundos");

                               if(listaPdf == null) {
                                    listaPdf = new List<IPublishedContent>();
                                }

                                 @subpage.Name

                                 @if(listaPdf != null){

                                    foreach(var row in listaPdf) {

                                    var name = Umbraco.Field(row, "categoriaDoFundo");

                                    var id = Umbraco.Field(row, "documentos").ToString();

                                    var mediaItem = Umbraco.TypedMedia(id);

                                    var url = mediaItem.Url;

                                    }
                                }

                    }
                }
             }

Body:
This is all to do with the structure of your data and the way you are trying to lay it out in a table that has a fixed number of columns

Anyway from your picture and your html, it looks like you have 9 columns.

You populate listaPdf with

var listaPdf = subpage.GetPropertyValue<IEnumerable<IPublishedContent>>("listaPdfsFundos");`

A little after that, you write the first column

<td >@subpage.Name</td>

which is definitely okay. So that is 1 column down and 8 to go.

Now your problems start.  In order for your code to work, you must write out 8 * <td> items in order to match your <th> headers (1 already written)  + 8).

If listaPdf does not contain exactly 8 items then it is not going to work. Your picture above suggests that listPdf contained 3 items so you have written out 4 * <td> which do not match up with the 9 * <th>

So the first thing to check is whether listaPdf contains 8 items.  If it doesn't you cannot make the above code work without finding some way to link each mediaItem to the correct column.

Is there anything in each mediaItem that links that item to the correct column?


问:
Google Chrome doesn't offer translation for my website
Google translation icon doens't appear on a website I'm working on, and I can't find a reason for this. Should I add a specific code to enable chrome to suggest translating it?

Please note that I don't want to add Google Chrome widget, and Chrome settings are OK.

I'd like to make Chrome suggests to translate the pages of the website.

Here's an example: https://drive.google.com/file/d/1hKlPcs_HnIXApSa7jYX1pvDZigvdh9mc/view?usp=sharing

答:
You can force the Chrome Translate dialog to show up by adding the lang tag with the language.  This should work as long as the user doesn't have the settings in Chrome to never translate. Some people turn off that dialog in the chrome settings because they do not want to be annoyed by the translate dialog.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language

sample html.

```<code><!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<p>这只是一个测试。</p>
</body>
</html>
</code>```

Body:
You can force the Chrome Translate dialog to show up by adding the lang tag with the language.  This should work as long as the user doesn't have the settings in Chrome to never translate. Some people turn off that dialog in the chrome settings because they do not want to be annoyed by the translate dialog.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language

sample html.

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<p>这只是一个测试。</p>
</body>
</html>