问:
Example GET request to manage topic subscriptions from the server side using Firebase Cloud Messaging
I found at https://developers.google.com/instance-id/reference/server#get_information_about_app_instances the following example GET request:

```<code>https://iid.googleapis.com/iid/info/nKctODamlM4:CKrh_PC8kIb7O...clJONHoA?details=trueAuthorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
</code>```

The key in that example is: AIzaSyZ-1u...0GBYzPu7Udno5aA. Where can I find my key, the one that I should use in my GET request? I am trying to find it at https://console.developers.google.com/apis/credentials, and this is what I see:

I tried using all of the four keys that you see in the image above, and I always receive this message from the browser:

```<code>{"error":"MissingAuthorization"}
</code>```

Does this error refer to the key being wrong, or to something else? Am I looking in the right place for the key? Thank you.

EDIT 1: I was looking at the question at How to check how many topics has been subscribed?, and I also tried using the keys that I found in my Firebase Console, under the "Cloud Messaing" tab. This is what I see:

I tried the GET request using those keys in the image above as well and I still see the same error: {"error":"MissingAuthorization"}.

EDIT 2: I am using this from the command line:

```<code>C:\curl>curl -k https://iid.googleapis.com/iid/info/nKctODamlM4:CKrh_PC8kIb7O...clJONHoA?details=trueAuthorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{"error":"MissingAuthorization"}
C:\curl>
</code>```

Notice how I simply copied/pasted what I found at https://developers.google.com/instance-id/reference/server#get_information_about_app_instances under the "Example GET request" heading. I am not even attempting to use my own keys and I see the same error: {"error":"MissingAuthorization"}. Does it mean the problem is with the key I am using? Is not it the one I see in the Firebase Console?

答:
Based on the instructions at https://developers.google.com/instance-id/reference/server, under the heading "Get information about app instances", it shows that it is necessary to provide the Authorization: key=YOUR_API_KEY, which is set in the header. See at https://android.jlelse.eu/firebase-push-notification-using-curl-command-devoid-backend-e63795d282c4 an example of how to provide a parameter in the header.

Concerning the Authorization: key=YOUR_API_KEY that has to be used, it is the key that appears in the "EDIT 1" section of this question. I used the Server key, not the Legacy server key, and it worked for me.

https://developers.google.com/instance-id/reference/server shows this end point: https://iid.googleapis.com/iid/info/IID_TOKEN. But IID_TOKEN must be replaced with the instance ID token which corresponds to the instance of the app that was installed on a device. In my case, I found it by printing the instance ID or token of the device, using the following code in the first activity of my Android app:

```<code>Log.d("The token of device: ", FirebaseInstanceId.getInstance().getToken());
</code>```

In the log of the Android monitor, I found the IID_TOKEN that I needed:

```<code>D/The token of device:: f35EFw4bsef:QWE34bFm56ZuQLWYSDDgPlkf4a88Lu6Gp4DoXVDJ5dRIlsdDncq0UdNnlDi7wxbbut6YX7Z1kwgyS3bzk_Zrl-1doHCf9XFdOXTThNzo4sDFEWqQjHKfNa3uH2Js4Flbf_CnRkD2Mftr
</code>```

Finally, I used cURL from the command prompt, and you can see how I obtained results correctly:

```<code>C:\curl>curl -X GET -k --header "Authorization: key=AAAAJ5XteYp:DKE32aIdFalyFXku6A-eR_wHL6ZBUFxfyPtcrm3wwF2l-nPEv_vAeYqo3NJzaIKKcSSow6gqoAwf3cBEm8QWYbF6w-asW0SX0RmHZftQglwmo_ziwrk8wFcGp1_DOQ1PLFFgP4BFWXAD" "https://iid.googleapis.com/iid/info/f35EFw4bsef:QWE34bFm56ZuQLWYSDDgPlkf4a88Lu6Gp4DoXVDJ5dRIlsdDncq0UdNnlDi7wxbbut6YX7Z1kwgyS3bzk_Zrl-1doHCf9XFdOXTThNzo4sDFEWqQjHKfNa3uH2Js4Flbf_CnRkD2Mftr
{"applicationVersion":"22","attestStatus":"NOT_ROOTED","application":"com.[myapp]","scope":"*","authorizedEntity":"232255245625","appSigner":"3d34g3fs3443292d825f21da4fdd5b34a56f2a3h","platform":"ANDROID"}
C:\curl>
</code>```

Note: In the code above I have changed the values of things such as tokens and keys for privacy purposes, but you need to use your values and everything should work.

Body:
I found at https://developers.google.com/instance-id/reference/server#get_information_about_app_instances the following example GET request:

https://iid.googleapis.com/iid/info/nKctODamlM4:CKrh_PC8kIb7O...clJONHoA?details=trueAuthorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

The key in that example is: AIzaSyZ-1u...0GBYzPu7Udno5aA. Where can I find my key, the one that I should use in my GET request? I am trying to find it at https://console.developers.google.com/apis/credentials, and this is what I see:

I tried using all of the four keys that you see in the image above, and I always receive this message from the browser:

{"error":"MissingAuthorization"}

Does this error refer to the key being wrong, or to something else? Am I looking in the right place for the key? Thank you.

EDIT 1: I was looking at the question at How to check how many topics has been subscribed?, and I also tried using the keys that I found in my Firebase Console, under the "Cloud Messaing" tab. This is what I see:

I tried the GET request using those keys in the image above as well and I still see the same error: {"error":"MissingAuthorization"}.

EDIT 2: I am using this from the command line:

C:\curl>curl -k https://iid.googleapis.com/iid/info/nKctODamlM4:CKrh_PC8kIb7O...clJONHoA?details=trueAuthorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{"error":"MissingAuthorization"}
C:\curl>

Notice how I simply copied/pasted what I found at https://developers.google.com/instance-id/reference/server#get_information_about_app_instances under the "Example GET request" heading. I am not even attempting to use my own keys and I see the same error: {"error":"MissingAuthorization"}. Does it mean the problem is with the key I am using? Is not it the one I see in the Firebase Console?

Body:
Based on the instructions at https://developers.google.com/instance-id/reference/server, under the heading "Get information about app instances", it shows that it is necessary to provide the Authorization: key=YOUR_API_KEY, which is set in the header. See at https://android.jlelse.eu/firebase-push-notification-using-curl-command-devoid-backend-e63795d282c4 an example of how to provide a parameter in the header.

Concerning the Authorization: key=YOUR_API_KEY that has to be used, it is the key that appears in the "EDIT 1" section of this question. I used the Server key, not the Legacy server key, and it worked for me.

https://developers.google.com/instance-id/reference/server shows this end point: https://iid.googleapis.com/iid/info/IID_TOKEN. But IID_TOKEN must be replaced with the instance ID token which corresponds to the instance of the app that was installed on a device. In my case, I found it by printing the instance ID or token of the device, using the following code in the first activity of my Android app:

Log.d("The token of device: ", FirebaseInstanceId.getInstance().getToken());

In the log of the Android monitor, I found the IID_TOKEN that I needed:

D/The token of device:: f35EFw4bsef:QWE34bFm56ZuQLWYSDDgPlkf4a88Lu6Gp4DoXVDJ5dRIlsdDncq0UdNnlDi7wxbbut6YX7Z1kwgyS3bzk_Zrl-1doHCf9XFdOXTThNzo4sDFEWqQjHKfNa3uH2Js4Flbf_CnRkD2Mftr

Finally, I used cURL from the command prompt, and you can see how I obtained results correctly:

C:\curl>curl -X GET -k --header "Authorization: key=AAAAJ5XteYp:DKE32aIdFalyFXku6A-eR_wHL6ZBUFxfyPtcrm3wwF2l-nPEv_vAeYqo3NJzaIKKcSSow6gqoAwf3cBEm8QWYbF6w-asW0SX0RmHZftQglwmo_ziwrk8wFcGp1_DOQ1PLFFgP4BFWXAD" "https://iid.googleapis.com/iid/info/f35EFw4bsef:QWE34bFm56ZuQLWYSDDgPlkf4a88Lu6Gp4DoXVDJ5dRIlsdDncq0UdNnlDi7wxbbut6YX7Z1kwgyS3bzk_Zrl-1doHCf9XFdOXTThNzo4sDFEWqQjHKfNa3uH2Js4Flbf_CnRkD2Mftr
{"applicationVersion":"22","attestStatus":"NOT_ROOTED","application":"com.[myapp]","scope":"*","authorizedEntity":"232255245625","appSigner":"3d34g3fs3443292d825f21da4fdd5b34a56f2a3h","platform":"ANDROID"}
C:\curl>

Note: In the code above I have changed the values of things such as tokens and keys for privacy purposes, but you need to use your values and everything should work.


来源: stackexchange

问:
Using Mako Templates in Pyramid with Google App Engine
With Pyramid and mod_wsgi, to use mako templates you just add this line to development.ini:

```<code>mako.directories = house:templates
</code>```

Unfortunately, Pyramid in the Google App Engine doesn't have an development.ini file, and I get the following error:

```<code>File "appengine-monkey/pyramidapp/app/lib/python/pyramid-1.0a9-py2.5.egg/pyramid/mako_templating.py", line 74, in renderer_factory
'Mako template used without a ``mako.directories`` setting')
ConfigurationError: Mako template used without a ``mako.directories`` setting
</code>```

Is there any way to pass this environment variable?

答:
I found out from the pylons-devel mailing list. Figured I would post the answer here.

The way to do this is pass it to the Configurator as a setting.  So in the __init__.py file make the following change:

```<code>config = Configurator(settings={'mako.directories':['house:templates']})
</code>```

ContentLicense: CC BY-SA 2.5

Body:
With Pyramid and mod_wsgi, to use mako templates you just add this line to development.ini:

mako.directories = house:templates

Unfortunately, Pyramid in the Google App Engine doesn't have an development.ini file, and I get the following error:

File "appengine-monkey/pyramidapp/app/lib/python/pyramid-1.0a9-py2.5.egg/pyramid/mako_templating.py", line 74, in renderer_factory
'Mako template used without a ``mako.directories`` setting')
ConfigurationError: Mako template used without a ``mako.directories`` setting

Is there any way to pass this environment variable?

Body:
I found out from the pylons-devel mailing list. Figured I would post the answer here.

The way to do this is pass it to the Configurator as a setting.  So in the __init__.py file make the following change:

config = Configurator(settings={'mako.directories':['house:templates']})


问:
SonarQube Inspectcode/Resharper plugin result is not matching with Visual Studio Inspection
I have been using the same set of rules defined in DotSettings files.

I have set this file under resharper \ manage options. Also when I am running InspectCode.exe I have provided the same.

I am using resharper plugin that comes with default rulesets repository and we have activated all those rules. (http://docs.sonarqube.org/display/PLUG/ReSharper+Plugin)

However, the result is not matching between SonarQube and Visual Studio.

Any idea what is going wrong here please?

Here are the stats screen shots.

Visual Studio shows 39 issues - 2 for web.config = 37 issues in total.

In SonarQube, using MSBuild.Runner and Resharper plugin is 32 violations.

Why there is a difference when I am download dotsettings file from the sonarqube and using the same for inspection in sonarqube as well as visual studio?

SonarQube Version Details:

SonarQube: 5.4

Resharper Plugin: 2.0

C# Plugin: 5.2 (http://docs.sonarqube.org/display/PLUG/C%23+Plugin)

In case of sonarqube I know all details about version and stuff. But in case of Visual Studio all I know is the Resharper plugin version. Thus, I don't why there is any difference.

答:
This is due to an open issue that jetbrains hasn't resolved yet (and as of now has no plans of resolving).

https://youtrack.jetbrains.com/issue/RSRP-463819

ContentLicense: CC BY-SA 3.0


问:
C++ - multiple #DEFINE values cause simple arithmetics to fail
I am running a program, where I keep incrementing "long int" in a big loop (the value is expected up to 10^8). The "long int" in question is initialized to 0. My console print looks like this :

errorous messages   : 400000/5000 = 800000 instances

Please notice the division is incorrect. Code printing the line above :

```<code>std::cout << "errorous messages   : " << total_error << "/" << GRID_SIZE << " = " << (long)((long)total_error / (long)GRID_SIZE) << " instances" << std::endl;
</code>```

Where the variables in question are :

```<code>#define BLOCKS      50
#define THREADS     100
#define GRID_SIZE   BLOCKS*THREADS
</code>```

and

```<code>long int total_error;  <--- incremented in a loop (never decremented, no overflow)
</code>```

What I have tried

I have played around with recasting the division of (long)((long)total_error / (long)GRID_SIZE) to (long)(total_error / GRID_SIZE) and some others, the result is the same.

Compilation Info

```<code> /opt/ohpc/pub/mpi/openmpi-gnu/1.10.6/bin/mpicxx
-I../../common/inc -I/usr/local/cuda-8.0/include
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code/Utility
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code/Data_objects
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code/cereal
-std=c++11    -o main.o -c main.cpp
</code>```

I am compiling with OpenMPI. There is CUDA as well, but this is main.cpp and there is no CUDA code.

QUESTION

What am I missing ? Why do I get wrong result for such a trivial operation ?

Justification of the question

The proposed duplicate is not related to my issue, as it defines macro functions, furthermore it doesnt explain why pre-processor behaves the way it does. It merely explains the way the macro function is executed.

My question is well explained and backed up by code producing the explained behavior. Please see how people answering this question had no issues understanding the cause of the problem.

答:
Because #defines are merely textual replacement, so your

```<code>(long)((long)total_error / (long)GRID_SIZE)
</code>```

is expanded to

```<code>(long)((long)total_error / (long)BLOCKS*THREADS)
</code>```

And, because division (/), and multiplication (*) operators have the same precedence, entire expression is evaluated from left to right, effectively equaling:

400000 / 50 * 100 = 8000 * 100 = 800000

Consider wrapping calculations done in #defines, in parenthesis, to prevent such issues:

```<code>#define GRID_SIZE   (BLOCKS*THREADS)
</code>```

Body:
I am running a program, where I keep incrementing "long int" in a big loop (the value is expected up to 10^8). The "long int" in question is initialized to 0. My console print looks like this :

errorous messages   : 400000/5000 = 800000 instances

Please notice the division is incorrect. Code printing the line above :

std::cout << "errorous messages   : " << total_error << "/" << GRID_SIZE << " = " << (long)((long)total_error / (long)GRID_SIZE) << " instances" << std::endl;

Where the variables in question are :

#define BLOCKS      50
#define THREADS     100
#define GRID_SIZE   BLOCKS*THREADS

and

long int total_error;  <--- incremented in a loop (never decremented, no overflow)

What I have tried

I have played around with recasting the division of (long)((long)total_error / (long)GRID_SIZE) to (long)(total_error / GRID_SIZE) and some others, the result is the same.

Compilation Info

 /opt/ohpc/pub/mpi/openmpi-gnu/1.10.6/bin/mpicxx
-I../../common/inc -I/usr/local/cuda-8.0/include
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code/Utility
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code/Data_objects
-I/export/home/ra2/test_cuda/test_cuda_v0_1/source_code/cereal
-std=c++11    -o main.o -c main.cpp

I am compiling with OpenMPI. There is CUDA as well, but this is main.cpp and there is no CUDA code.

QUESTION

What am I missing ? Why do I get wrong result for such a trivial operation ?

Justification of the question

The proposed duplicate is not related to my issue, as it defines macro functions, furthermore it doesnt explain why pre-processor behaves the way it does. It merely explains the way the macro function is executed.

My question is well explained and backed up by code producing the explained behavior. Please see how people answering this question had no issues understanding the cause of the problem.

Body:
Because #defines are merely textual replacement, so your

(long)((long)total_error / (long)GRID_SIZE)

is expanded to

(long)((long)total_error / (long)BLOCKS*THREADS)

And, because division (/), and multiplication (*) operators have the same precedence, entire expression is evaluated from left to right, effectively equaling:

400000 / 50 * 100 = 8000 * 100 = 800000

Consider wrapping calculations done in #defines, in parenthesis, to prevent such issues:

#define GRID_SIZE   (BLOCKS*THREADS)


问:
Transitive efficient comparison and value assignment to dataframe variables in R?
I have 3 data frames:

df1:

```<code>    key       value
1   rs1057079     C
2   rs4845882     A
3   rs1891932     T
4    rs530296     A
5  rs10497340     G
</code>```

df2:

```<code>    key       value
1   rs1057079     T
2   rs4845882     G
3   rs1891932     T
4    rs530296     A
5  rs10497340     A
</code>```

and third control df3:

```<code>    key       value
1   rs1057079     C
2   rs4845882     A
3   rs1891932     C
4    rs530296     G
5  rs10497340     G
</code>```

I want to check for all keys in df1 and df2 if they are equal or not to the control df3. For example check if df1$rs1057079 == df3$rs1057079, same with df2.

I want to do this without a for loop, what is the most simple and efficient way?
I thought about dplyr filter and mutate functions but will be happy to hear from the experts how to compare n df's to a control df?

答:
I'll create a function that takes two datasets (test and control) and returns the values (next to each other) and a flag to spot when they are the same.

```<code>df1 = read.table(text = "
key       value
1   rs1057079     C
2   rs4845882     A
3   rs1891932     T
4    rs530296     A
5  rs10497340     G
", header=T, stringsAsFactors=F)

df2 = read.table(text = "
key       value
1   rs1057079     T
2   rs4845882     G
3   rs1891932     T
4    rs530296     A
5  rs10497340     A
", header=T, stringsAsFactors=F)

df3 = read.table(text = "
key       value
1   rs1057079     C
2   rs4845882     A
3   rs1891932     C
4    rs530296     G
5  rs10497340     G
", header=T, stringsAsFactors=F)

library(dplyr)

# function that compares the values based on the key column
CompareDatasets = function(d1, d2) {
d1 %>%
  left_join(d2, by="key") %>%
  mutate(IsSame = value.x == value.y)
}

# apply function
CompareDatasets(df1, df3)

#          key value.x value.y IsSame
# 1  rs1057079       C       C   TRUE
# 2  rs4845882       A       A   TRUE
# 3  rs1891932       T       C  FALSE
# 4   rs530296       A       G  FALSE
# 5 rs10497340       G       G   TRUE
</code>```

Column key represents both datasets, value.x is the value of the test dataset, value.y is the value of the control dataset (depends on which dataset you pass first to the function) and flag spot when values are equal.

Another way to do this is by creating a single dataframe output (i.e. compare all test datasets with control at the same time), but you need to create a column with the dataset name:

```<code>library(dplyr)
library(purrr)

# fucntion that gets the name of a dataset and returns the dataset with the name as a column
GetNameData = function(x) {
  d = get(x)
  d$name = x
  d
}

# vector of test datsets' names (multiple names)
# df3 will be the control
test = c("df1", "df2")

test %>%                                    # get the dataset names
  map_df(GetNameData) %>%                   # apply the function and get data (single dataframe)
  left_join(df3, by="key") %>%              # join the control group
  mutate(IsSame = value.x == value.y) %>%   # flag equal values
  select(name, everything())                # re-arrange columns

#    name        key value.x value.y IsSame
# 1   df1  rs1057079       C       C   TRUE
# 2   df1  rs4845882       A       A   TRUE
# 3   df1  rs1891932       T       C  FALSE
# 4   df1   rs530296       A       G  FALSE
# 5   df1 rs10497340       G       G   TRUE
# 6   df2  rs1057079       T       C  FALSE
# 7   df2  rs4845882       G       A  FALSE
# 8   df2  rs1891932       T       C  FALSE
# 9   df2   rs530296       A       G  FALSE
# 10  df2 rs10497340       A       G  FALSE
</code>```

Body:
I have 3 data frames:

df1:

    key       value
1   rs1057079     C
2   rs4845882     A
3   rs1891932     T
4    rs530296     A
5  rs10497340     G

df2:

    key       value
1   rs1057079     T
2   rs4845882     G
3   rs1891932     T
4    rs530296     A
5  rs10497340     A

and third control df3:

    key       value
1   rs1057079     C
2   rs4845882     A
3   rs1891932     C
4    rs530296     G
5  rs10497340     G

I want to check for all keys in df1 and df2 if they are equal or not to the control df3. For example check if df1$rs1057079 == df3$rs1057079, same with df2.

I want to do this without a for loop, what is the most simple and efficient way?
I thought about dplyr filter and mutate functions but will be happy to hear from the experts how to compare n df's to a control df?

Body:
I'll create a function that takes two datasets (test and control) and returns the values (next to each other) and a flag to spot when they are the same.

df1 = read.table(text = "
key       value
1   rs1057079     C
2   rs4845882     A
3   rs1891932     T
4    rs530296     A
5  rs10497340     G
", header=T, stringsAsFactors=F)

df2 = read.table(text = "
key       value
1   rs1057079     T
2   rs4845882     G
3   rs1891932     T
4    rs530296     A
5  rs10497340     A
", header=T, stringsAsFactors=F)

df3 = read.table(text = "
key       value
1   rs1057079     C
2   rs4845882     A
3   rs1891932     C
4    rs530296     G
5  rs10497340     G
", header=T, stringsAsFactors=F)

library(dplyr)

# function that compares the values based on the key column
CompareDatasets = function(d1, d2) {
d1 %>%
  left_join(d2, by="key") %>%
  mutate(IsSame = value.x == value.y)
}

# apply function
CompareDatasets(df1, df3)

#          key value.x value.y IsSame
# 1  rs1057079       C       C   TRUE
# 2  rs4845882       A       A   TRUE
# 3  rs1891932       T       C  FALSE
# 4   rs530296       A       G  FALSE
# 5 rs10497340       G       G   TRUE

Column key represents both datasets, value.x is the value of the test dataset, value.y is the value of the control dataset (depends on which dataset you pass first to the function) and flag spot when values are equal.

Another way to do this is by creating a single dataframe output (i.e. compare all test datasets with control at the same time), but you need to create a column with the dataset name:

library(dplyr)
library(purrr)

# fucntion that gets the name of a dataset and returns the dataset with the name as a column
GetNameData = function(x) {
  d = get(x)
  d$name = x
  d
}

# vector of test datsets' names (multiple names)
# df3 will be the control
test = c("df1", "df2")

test %>%                                    # get the dataset names
  map_df(GetNameData) %>%                   # apply the function and get data (single dataframe)
  left_join(df3, by="key") %>%              # join the control group
  mutate(IsSame = value.x == value.y) %>%   # flag equal values
  select(name, everything())                # re-arrange columns

#    name        key value.x value.y IsSame
# 1   df1  rs1057079       C       C   TRUE
# 2   df1  rs4845882       A       A   TRUE
# 3   df1  rs1891932       T       C  FALSE
# 4   df1   rs530296       A       G  FALSE
# 5   df1 rs10497340       G       G   TRUE
# 6   df2  rs1057079       T       C  FALSE
# 7   df2  rs4845882       G       A  FALSE
# 8   df2  rs1891932       T       C  FALSE
# 9   df2   rs530296       A       G  FALSE
# 10  df2 rs10497340       A       G  FALSE


问:
Sorting Words from a input text depending on how many times it was repeated?
I am trying to make a Program that reads an input text from the user and then  prints out each word and how many times it was repeated in a sorted order. ( the input is separated by white spaces and it can hold punctuation but no new lines)

Example of Input : I am a good programmer and I love C language.

output should be :

a : 2 times

                   I : 1 time

                 am : 1 time

                 good : 1 time

... and so on.

** for the input I used a vector and classes  but i don't know why i can't push several items in it.

```<code>class word {public:
word();
void set_data(string data_value);
void printing_data();
void counter_addition();
int count;
string data;};
</code>```

```<code>int main(){ /*creating vecotr called items of list class type*/
vector<word>items;

/*creating a variable of list class type which is used to push data into the vector*/

word *element;

/*Reading the input text seperated by white spaces*/
int size = 0;
string text;

cout << "Enter the text: " << endl;
getline(cin, text);

size = text.length();
int left_space = -1;
int right_space = 0;
string Sub_String;

/*main loop for constructing substring of words and then manipulating them*/

for (int i = 0; i<size; i++)
{

    /*splitting the string into words*/
    if (isspace(text[i]) || ispunct(text[i]))
    {
        right_space = i;

        Sub_String = text.substr(left_space + 1, right_space - left_space - 1);
        /*for first word just push it*/

        if (left_space == -1)
        {
            element = new word();
            element->set_data(Sub_String);
            items.push_back(*element);

        }

        else
        {
            /*compare to vector's data */
            for (int j = 0; j < items.size(); j++)
            {
                if (Sub_String == items[j].data)
                {
                    items[j].count = items[j].count + 1;
                }
                else
                {
                    element = new word();
                    element->set_data(Sub_String);
                    items.push_back(*element);
                }

            }
        }
            left_space = right_space;
    }
</code>```

if the words are the same the output is correct .

input : Life life life life

output: Life repeated:4

Please help me through this I am new to programming .

答: Store the string values and count into std::map< std::string, int > and for each word, check if it is already in the map. If it is there, increment the count. In opposite case insert it with count = 1</p>

Body:
I am trying to make a Program that reads an input text from the user and then  prints out each word and how many times it was repeated in a sorted order. ( the input is separated by white spaces and it can hold punctuation but no new lines)

Example of Input : I am a good programmer and I love C language.

output should be :

a : 2 times

                   I : 1 time

                 am : 1 time

                 good : 1 time

... and so on.

** for the input I used a vector and classes  but i don't know why i can't push several items in it.

class word {public:
word();
void set_data(string data_value);
void printing_data();
void counter_addition();
int count;
string data;};

int main(){ /*creating vecotr called items of list class type*/
vector<word>items;

/*creating a variable of list class type which is used to push data into the vector*/

word *element;

/*Reading the input text seperated by white spaces*/
int size = 0;
string text;

cout << "Enter the text: " << endl;
getline(cin, text);

size = text.length();
int left_space = -1;
int right_space = 0;
string Sub_String;

/*main loop for constructing substring of words and then manipulating them*/

for (int i = 0; i<size; i++)
{

    /*splitting the string into words*/
    if (isspace(text[i]) || ispunct(text[i]))
    {
        right_space = i;

        Sub_String = text.substr(left_space + 1, right_space - left_space - 1);
        /*for first word just push it*/

        if (left_space == -1)
        {
            element = new word();
            element->set_data(Sub_String);
            items.push_back(*element);

        }

        else
        {
            /*compare to vector's data */
            for (int j = 0; j < items.size(); j++)
            {
                if (Sub_String == items[j].data)
                {
                    items[j].count = items[j].count + 1;
                }
                else
                {
                    element = new word();
                    element->set_data(Sub_String);
                    items.push_back(*element);
                }

            }
        }
            left_space = right_space;
    }

if the words are the same the output is correct .

input : Life life life life

output: Life repeated:4

Please help me through this I am new to programming .


问:
Sending System.out to a file and Commons Logging
I am using commons logging:

```<code>  private static final Log LOG = LogFactory.getLog(MyClass.class);
</code>```

Why those logs doesn't go into the log file when I run

```<code>sh Main 2>&1 > logfile
</code>```

I am using the default properties and no log4j.properties are in the classpath.

答:
You have the redirections backwards. They're processed from left to right. Try this:</p>

```<code>sh Main > logfile 2>&1
</code>```

Body:
I am using commons logging:

  private static final Log LOG = LogFactory.getLog(MyClass.class);

Why those logs doesn't go into the log file when I run

sh Main 2>&1 > logfile

I am using the default properties and no log4j.properties are in the classpath.

Body:
You have the redirections backwards. They're processed from left to right. Try this:

sh Main > logfile 2>&1


问:
Conditional module aliasing
For a class project I am writing a program that evaluates the performance of different implementations of the same abstract data structure.  Since I am using identical code to test each of them, I would like to be able to set a module alias depending on user input and just run that module through the testing code.

In other words, I want something like:

```<code>let module M =
  if model = "tree" then TreeModel else
  if model = "hash" then HashModel else
  ListModel
in ...
</code>```

Is there a way I can make this work, or am I going about this all wrong?

答:
As a follow-up to @Andreas, at least in recent ocaml versions you can also write:</p>

```<code>let (module M : MODEL) = match model with
  | "tree" -> (module TreeModel : MODEL)
  | "hash" -> (module HashModel : MODEL)
  | "list" -> (module ListModel : MODEL)
in ...
</code>```

Title: Conditional module aliasing

Body:
For a class project I am writing a program that evaluates the performance of different implementations of the same abstract data structure.  Since I am using identical code to test each of them, I would like to be able to set a module alias depending on user input and just run that module through the testing code.

In other words, I want something like:

let module M =
  if model = "tree" then TreeModel else
  if model = "hash" then HashModel else
  ListModel
in ...

Is there a way I can make this work, or am I going about this all wrong?

Body:
As a follow-up to @Andreas, at least in recent ocaml versions you can also write:

let (module M : MODEL) = match model with
  | "tree" -> (module TreeModel : MODEL)
  | "hash" -> (module HashModel : MODEL)
  | "list" -> (module ListModel : MODEL)
in ...


问:
Modify html content using JQuery by style tag
I am trying to edit html content based on style tags

Here is the section of html:

```<code><!DOCTYPE html>
<html>
  <body>
    <span style="color:restest">Testing</span>
    <br>
    <span style="color:restest">Testing Again</span>
  </body>
</html>
</code>```

I want to modify all instances of spans with style="color:restest" and add html tags to the contents.

They should become something like:

```<code><a href="example.com/testing">Testing</a>
<a href="example.com/testing_again">Testing_Again</a>
</code>```

答:
The easiest way to do this would be with jQuery#replaceWith:

$('span[style="color:restest"]').each((i,e) => {
  $(e).replaceWith(`${e.innerHTML}`);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span style="color:restest">Testing</span>
<span style="color:restest">Testing Again</span></code>```

Body:
I am trying to edit html content based on style tags

Here is the section of html:

<!DOCTYPE html>

    Testing

    Testing Again

I want to modify all instances of spans with style="color:restest" and add html tags to the contents.

They should become something like:

Testing
Testing_Again

Body:
The easiest way to do this would be with jQuery#replaceWith:

$('span[style="color:restest"]').each((i,e) => {
  $(e).replaceWith(`<a href="example.com/${e.innerHTML}">${e.innerHTML}</a>`);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span style="color:restest">Testing</span>
<span style="color:restest">Testing Again</span>


问:
Verifying HMAC from Microsoft Teams custom Bot in PHP
I am trying to authenticate a Microsoft Teams custom Bot with PHP, following the Microsoft instructions and read de C# example code.

Microsoft Intructions steps:

  1. Generate the hmac from the request body of the message. There are standard libraries on most platforms. Microsoft Teams uses standard
  SHA256 HMAC cryptography. You will need to convert the body to a byte
  array in UTF8.

  2. To compute the hash, provide the byte array of the shared secret.

  3. Convert the hash to a string using UTF8 encoding.

  4. Compare the string value of the generated hash with the value provided in the HTTP request.

I had write a small php script to test this in local:

```<code>        <?php
        //Function to generate C# byte[] equivalent
        function unpak_str($val){
            $b = unpack('C*', $val);
            foreach ($b as $key => $value)
                $byte_a .= $value;

           return $byte_a;
          }

        //multi test outputs
        function hasher($values=[], &$output){
            //my secret share
            $secret="ejWiKHgsKY1ZfpJwJ+wIiN4+bgsFad/lkpu9/MWNXgM=";
            //diferent test
            $secret_64=base64_decode($secret);
            $secret_b=unpak_str($secret);
            $secret_b_64=unpak_str(base64_decode($secret));

            foreach($values as $msg){
                $hs = hash_hmac("sha256",$msg,$secret, true);
                $hs_64 = hash_hmac("sha256",$msg,$secret_64, true);
                $hs_b = hash_hmac("sha256",$msg,$secret_b, true);
                $hs_b_64 = hash_hmac("sha256",$msg,$secret_b_64, true);

                $output.=base64_encode($hs)." <BR>";
                $output.=base64_encode($hs_64)." <BR>";
                $output.=base64_encode($hs_b)." <BR>";
                $output.=base64_encode($hs_b_64)." <BR>";
             }
          }

    //Get data
    $data=file_get_contents('php://input');

    //real data request content for test
    $data ='{type":"message","id":"1512376018086","timestamp":"2017-12-04T08:26:58.237Z","localTimestamp":"2017-12-04T09:26:58.237+01:00","serviceUrl":"https://smba.trafficmanager.net/emea-client-ss.msg/","channelId":"msteams","from":{"id":"29:1aq6GCrC6lM9dv3YkAYi1gxTPiLnojGFgVr0_Th-2x6DhqmHAOhFwQHFzSyDy5RruXY4_FZjJebKHU7bpxfHpXA","name":"ROBERTO ALONSO FERNANDEZ","aadObjectId":"1e0dc7a0-9d5e-488b-bcf2-7e39c84076b8"},"conversation":{"isGroup":true,"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype;messageid=1512376018086","name":null},"recipient":null,"textFormat":"plain","attachmentLayout":null,"membersAdded":[],"membersRemoved":[],"topicName":null,"historyDisclosed":null,"locale":null,"text":"<at>PandoBot</at> fff","speak":null,"inputHint":null,"summary":null,"suggestedActions":null,"attachments":[{"contentType":"text/html","contentUrl":null,"content":"<div><span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">PandoBot</span> fff</div>","name":null,"thumbnailUrl":null}],"entities":[{"type":"clientInfo","locale":"es-ES","country":"ES","platform":"iOS"}],"channelData":{"teamsChannelId":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype","teamsTeamId":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype","channel":{"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype"},"team":{"id":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype"},"tenant":{"id":"9744600e-3e04-492e-baa1-25ec245c6f10"}},"action":null,"replyToId":null,"value":null,"name":null,"relatesTo":null,"code":null}';

    //generate HMAC hash with diferent $data formats
    $test = [$data, unpak_str($data), base64_encode($data), unpak_str(base64_encode($data))];
    hasher($test, $output);

    //microsoft provided HMAC
    $output.="<HR>EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=";

    echo $output;
    /*
    Calculates:
    0HsKoHza/QBvdz+nZw9tOti/eSWjyMMt/U77bfDqiE8=
    3jSq3I0HNQkjB9QfnnsxC1c3pF5PjqweHlSVcicrShY=
    bTQcGVTHX8/Gh4xovnN0WiJUiNaOQwvUZnwyFfiCaJE=
    qHBT2Y2ITyoxz2gmBbG8P1CrClvETus6dTffET3bAR8=
    8BcrXEQDDi77qgxCZLYyb/6ez8p9Qg2ZhTyZPWkdn/g=
    +8RSU5SSJKxqRLKkI+NkTE01xwu6PwPkKKMuvyyUvlo=
    PdL5ZpEwcN6Fe5kfX7zeAZLJvt0uLNTzu7lhuoOcr2o=
    s6M5pYruEgWeNMEOFfQRjVKQqtPBVaW3TJb2MzObF2c=
    xOTLhddbAwczQVneuTDQhPzmoIXGQljpf27c+hlhQII=
    aUMm5b2sKfmwGZOglfiu228fWqoLlwjc7z1QRdIbakE=
    5a7bAj9tzqhP9l85OvfVasURW0GSV5rykRutFFPO2fk=
    kwg6P2LoDL9rc3SSwJxQeoYJzZYlh+FHFefe38UokBM=
    eHeAzI7TV6vYDzxTxwyKWxMeVKFiFlIffWRiIMAk6fk=
    ZCyj2UppacQOTXogLPMFLDeMArQg03rhhlIwhynDvng=
    uQYK+7u9fppb62zXqtVYfkNK9wVawB3g+BlTyu4dc74=
    vjOFA3fqpwUx/VO9dQv3XviNhpjTNQsUwaJIwH4JjdY=
    ------------ MS PROVIDED HMAC ---------------
    EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=
     */
</code>```

I've zero hash matching...

答:
Finally after lots of trial, it maked me crazy and decided to start a new bot with a new secret. Now works fine. I'm human while MS Teams no... I suppos that was my fault with copy/paste but is a really stranger thing and the other hand old bot fails a lot of times with no response and the newest no

Full example validation HMAC in PHP for Microsoft Teams Custom Bot:

```<code>        <?php

        //The secret share with Microsoft Teams
        $secret="jond3021g9imMkrt8txF5AVPIwPFouNV/I72cQFii18=";

        //get headers
        $a = getallheaders();
        $provided_hmac=substr($a['Authorization'],5);

        //Get data from request
        $data=file_get_contents('php://input');

        //json decode into array
        $json=json_decode($data, true);

        //hashing
        $hash = hash_hmac("sha256",$data,base64_decode($secret), true);
        $calculated_hmac = base64_encode($hash);

        //start log var
        $log = "\n========".date("Y-m-d H:i:s")."========\n".$provided_hmac."\n".$calculated_hmac."\n";

        try{
            //compare hashs
            if(!hash_equals($provided_hmac,$calculated_hmac))
                throw new Exception("No hash matching");
            //response text
            $txt="Hi {$json["from"]["name"]} welcome to your custom bot";
            echo '{
                "type": "message",
                "text": "'.$txt.'"
                 }';
            $log .= "Sended: {$txt}";
        }catch (Exception $e){
            $log .= $e->getMessage();
        }
        //write log
        $fp = fopen("log.txt","a");
        fwrite($fp, $log . PHP_EOL);
        fclose($fp);
</code>```

Body:
I am trying to authenticate a Microsoft Teams custom Bot with PHP, following the Microsoft instructions and read de C# example code.

Microsoft Intructions steps:

  1. Generate the hmac from the request body of the message. There are standard libraries on most platforms. Microsoft Teams uses standard
  SHA256 HMAC cryptography. You will need to convert the body to a byte
  array in UTF8.

  2. To compute the hash, provide the byte array of the shared secret.

  3. Convert the hash to a string using UTF8 encoding.

  4. Compare the string value of the generated hash with the value provided in the HTTP request.

I had write a small php script to test this in local:

        <?php
        //Function to generate C# byte[] equivalent
        function unpak_str($val){
            $b = unpack('C*', $val);
            foreach ($b as $key => $value)
                $byte_a .= $value;

           return $byte_a;
          }

        //multi test outputs
        function hasher($values=[], &$output){
            //my secret share
            $secret="ejWiKHgsKY1ZfpJwJ+wIiN4+bgsFad/lkpu9/MWNXgM=";
            //diferent test
            $secret_64=base64_decode($secret);
            $secret_b=unpak_str($secret);
            $secret_b_64=unpak_str(base64_decode($secret));

            foreach($values as $msg){
                $hs = hash_hmac("sha256",$msg,$secret, true);
                $hs_64 = hash_hmac("sha256",$msg,$secret_64, true);
                $hs_b = hash_hmac("sha256",$msg,$secret_b, true);
                $hs_b_64 = hash_hmac("sha256",$msg,$secret_b_64, true);

                $output.=base64_encode($hs)."
";
                $output.=base64_encode($hs_64)."
";
                $output.=base64_encode($hs_b)."
";
                $output.=base64_encode($hs_b_64)."
";
             }
          }

    //Get data
    $data=file_get_contents('php://input');

    //real data request content for test
    $data ='{type":"message","id":"1512376018086","timestamp":"2017-12-04T08:26:58.237Z","localTimestamp":"2017-12-04T09:26:58.237+01:00","serviceUrl":"https://smba.trafficmanager.net/emea-client-ss.msg/","channelId":"msteams","from":{"id":"29:1aq6GCrC6lM9dv3YkAYi1gxTPiLnojGFgVr0_Th-2x6DhqmHAOhFwQHFzSyDy5RruXY4_FZjJebKHU7bpxfHpXA","name":"ROBERTO ALONSO FERNANDEZ","aadObjectId":"1e0dc7a0-9d5e-488b-bcf2-7e39c84076b8"},"conversation":{"isGroup":true,"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype;messageid=1512376018086","name":null},"recipient":null,"textFormat":"plain","attachmentLayout":null,"membersAdded":[],"membersRemoved":[],"topicName":null,"historyDisclosed":null,"locale":null,"text":"<at>PandoBot</at> fff","speak":null,"inputHint":null,"summary":null,"suggestedActions":null,"attachments":[{"contentType":"text/html","contentUrl":null,"content":"
PandoBot fff
","name":null,"thumbnailUrl":null}],"entities":[{"type":"clientInfo","locale":"es-ES","country":"ES","platform":"iOS"}],"channelData":{"teamsChannelId":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype","teamsTeamId":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype","channel":{"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype"},"team":{"id":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype"},"tenant":{"id":"9744600e-3e04-492e-baa1-25ec245c6f10"}},"action":null,"replyToId":null,"value":null,"name":null,"relatesTo":null,"code":null}';

    //generate HMAC hash with diferent $data formats
    $test = [$data, unpak_str($data), base64_encode($data), unpak_str(base64_encode($data))];
    hasher($test, $output);

    //microsoft provided HMAC
    $output.="
EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=";

    echo $output;
    /*
    Calculates:
    0HsKoHza/QBvdz+nZw9tOti/eSWjyMMt/U77bfDqiE8=
    3jSq3I0HNQkjB9QfnnsxC1c3pF5PjqweHlSVcicrShY=
    bTQcGVTHX8/Gh4xovnN0WiJUiNaOQwvUZnwyFfiCaJE=
    qHBT2Y2ITyoxz2gmBbG8P1CrClvETus6dTffET3bAR8=
    8BcrXEQDDi77qgxCZLYyb/6ez8p9Qg2ZhTyZPWkdn/g=
    +8RSU5SSJKxqRLKkI+NkTE01xwu6PwPkKKMuvyyUvlo=
    PdL5ZpEwcN6Fe5kfX7zeAZLJvt0uLNTzu7lhuoOcr2o=
    s6M5pYruEgWeNMEOFfQRjVKQqtPBVaW3TJb2MzObF2c=
    xOTLhddbAwczQVneuTDQhPzmoIXGQljpf27c+hlhQII=
    aUMm5b2sKfmwGZOglfiu228fWqoLlwjc7z1QRdIbakE=
    5a7bAj9tzqhP9l85OvfVasURW0GSV5rykRutFFPO2fk=
    kwg6P2LoDL9rc3SSwJxQeoYJzZYlh+FHFefe38UokBM=
    eHeAzI7TV6vYDzxTxwyKWxMeVKFiFlIffWRiIMAk6fk=
    ZCyj2UppacQOTXogLPMFLDeMArQg03rhhlIwhynDvng=
    uQYK+7u9fppb62zXqtVYfkNK9wVawB3g+BlTyu4dc74=
    vjOFA3fqpwUx/VO9dQv3XviNhpjTNQsUwaJIwH4JjdY=
    ------------ MS PROVIDED HMAC ---------------
    EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=
     */

I've zero hash matching...

Body:
Finally after lots of trial, it maked me crazy and decided to start a new bot with a new secret. Now works fine. I'm human while MS Teams no... I suppos that was my fault with copy/paste but is a really stranger thing and the other hand old bot fails a lot of times with no response and the newest no

Full example validation HMAC in PHP for Microsoft Teams Custom Bot:

        <?php

        //The secret share with Microsoft Teams
        $secret="jond3021g9imMkrt8txF5AVPIwPFouNV/I72cQFii18=";

        //get headers
        $a = getallheaders();
        $provided_hmac=substr($a['Authorization'],5);

        //Get data from request
        $data=file_get_contents('php://input');

        //json decode into array
        $json=json_decode($data, true);

        //hashing
        $hash = hash_hmac("sha256",$data,base64_decode($secret), true);
        $calculated_hmac = base64_encode($hash);

        //start log var
        $log = "\n========".date("Y-m-d H:i:s")."========\n".$provided_hmac."\n".$calculated_hmac."\n";

        try{
            //compare hashs
            if(!hash_equals($provided_hmac,$calculated_hmac))
                throw new Exception("No hash matching");
            //response text
            $txt="Hi {$json["from"]["name"]} welcome to your custom bot";
            echo '{
                "type": "message",
                "text": "'.$txt.'"
                 }';
            $log .= "Sended: {$txt}";
        }catch (Exception $e){
            $log .= $e->getMessage();
        }
        //write log
        $fp = fopen("log.txt","a");
        fwrite($fp, $log . PHP_EOL);
        fclose($fp);


问:
How do I rollback a SQL CLR stored procedure when a user cancels the query?
I'm trying to create a SQL CLR stored procedure that will create a table, pass the table name onto a service which will bulk insert some data into it, display the results of the table, then clean up the table.

What I've tried so far:

Use SqlTransaction. Cancelling the transaction works, but it puts my query window into a state where I couldn't continue working on it.

The transaction active in this session has been committed or aborted by another session

Use TransactionScope. Same issue as 1.

Manually clean up the table in a finally clause by issuing a DROP TABLE SqlCommand. This doesn't seem to get run, though my SqlContext.Pipe.Send() prior to issuing the command does. It doesn't seem like it's related to any time constraints since if I issue a Thread.Sleep(2000) before printing another line, it still prints the second line whereas the command.ExecuteNonQuery() would stop before printing the second line.

Placing the manual cleanup code into a CER or SafeHandle. This doesn't work as having a CER requires some guarantees, including not allocating additional memory or calling methods that are not decorated with a ReliabilityContract.

Am I missing something obvious here?  How do I handle the user cancelling their query?

Edit: There were multiple iterations of the code for each scenario, but the general actions taken are along the lines of the following:

```<code>    [SqlProcedure]
    public static void GetData(SqlString code)
    {
        Guid guid = Guid.NewGuid();
        using (var connection = new SqlConnection("context connection=true"))
        {
            connection.Open();

            try
            {
                SqlContext.Pipe?.Send("Constrain");

                SqlCommand command1 = new SqlCommand($"CREATE TABLE qb.{code}_{guid:N} (Id INT)", connection);
                command1.ExecuteNonQuery();
                SqlContext.Pipe?.Send($"Create: qb.{code}_{guid:N}");

                //emulate service call
                Thread.Sleep(TimeSpan.FromSeconds(10));

                SqlContext.Pipe?.Send($"Done: qb.{code}_{guid:N}");
            }
            finally
            {
                SqlContext.Pipe?.Send("1");
                //drop table here instead of sleep
                Thread.Sleep(2000);
                SqlContext.Pipe?.Send("2");
            }
        }
    }
</code>```

答:
Unfortunately SQLCLR does not handle query cancellation very well. However, given the error message, that seems to imply that the cancellation does its own ROLLBACK. Have you tried not using a Transaction within the SQLCLR code but instead handling it from outside? Such as:

BEGIN TRAN;

EXEC SQLCLR_Stored_Procedure;

IF (@@TRANCOUNT > 0) ROLLBACK TRAN;

The workflow noted above would need to be enforced. This can be done rather easily by creating a wrapper T-SQL Stored Procedure that executes those 3 steps and only give EXECUTE permission to the wrapper Stored Procedure. If permissions are then needed for the SQLCLR Stored Procedure, that can be accomplished rather easily using module signing:

Create an Asymmetric Key in the same DB as the SQLCLR Stored Procedure

Create a User from that Asymmetric Key

GRANT that Key-based User EXECUTE permission on the SQLCLR Stored Procedure

Sign the wrapper T-SQL Stored Procedure, using ADD SIGNATURE, with that Asymmetric Key

Those 4 steps allow the T-SQL wrapper proc to execute the SQLCLR proc, while the actual application Login can only execute the T-SQL wrapper proc :-). And, in, the event that the cancellation aborts the execution prior to executing ROLLBACK, the Transaction should be automatically rolled-back when the connection closes.

Also, do you have XACT_ABORT set to ON or OFF? UPDATE: O.P. states that it is set to OFF, and setting to ON did not seem to behave any differently.

Have you tried checking the connection state in the finally block? I am pretty sure that the SqlConnection is Closed upon the cancellation. You could try the following approaches, both in the finally block:

Test for the connection state and if Closed, re-open the SqlConnection and then execute the non-query command.

UPDATE: O.P. states that the connection is still open. Ok, how about closing it and re-opening it?

UPDATE 2: O.P. tested and found that the connection could not be re-opened.

Since the context is still available, as proven by your print commands working, use something like SqlContext.Pipe.ExecuteAndSend(new SqlCommand("DROP TABLE..;"));

UPDATE: O.P. states that this did not work.

OR, since you create a guaranteed unique table name in the code, you can try creating the table as a global temporary table (i.e. prefixed with two pound-signs: ##TableName) which will a) be available to the bulk import process, and b) clean itself up when the connection fully closes. In this approach, you technically wouldn't need to perform any manual clean up.

Of course, when Connection Pooling is enabled, the automatic cleanup happens only after the connection is re-opened and the first command is executed. In order to force an immediate cleanup, you would have to connect to SQL Server with Connection Pooling disabled. Is it possible to use a different Connection String just when this Stored Procedure is to be executed that includes Pooling=false;? Given how this Stored Procedure is being used, it does not seem like you would suffer any noticeable performance degradation from disabling Connection Pooling on just this one specific call. To better understand how Connection Pooling – enabled or disabled – affects the automatic cleanup of temporary objects, please see the blog post I just published that details this very behavior:

Sessions, Temporary Objects, and the Afterlife

This approach is probably the best overall since you probably cannot guarantee either that ROLLBACK would be executed (first approach mentioned) or that a finally clause would be executed (assuming you ever got that to work). In the end, uncommitted Transactions will be rolled-back, but if someone executes this via SSMS and it aborts without the ROLLBACK, then they are still in an open Transaction and might not be aware of it. Also, think about the connection being forcibly closed, or the Session being killed, or the server being shutdown / restarted. In those cases tempdb is your friend, whether by using a global temporary table, or at the very least creating the permanent Table in tempdb so that it is automatically removed the next time that the SQL Server starts (due to tempdb being created new, as a copy of model, upon each start of the SQL Server service).

Body:
I'm trying to create a SQL CLR stored procedure that will create a table, pass the table name onto a service which will bulk insert some data into it, display the results of the table, then clean up the table.

What I've tried so far:

Use SqlTransaction. Cancelling the transaction works, but it puts my query window into a state where I couldn't continue working on it.

The transaction active in this session has been committed or aborted by another session

Use TransactionScope. Same issue as 1.

Manually clean up the table in a finally clause by issuing a DROP TABLE SqlCommand. This doesn't seem to get run, though my SqlContext.Pipe.Send() prior to issuing the command does. It doesn't seem like it's related to any time constraints since if I issue a Thread.Sleep(2000) before printing another line, it still prints the second line whereas the command.ExecuteNonQuery() would stop before printing the second line.

Placing the manual cleanup code into a CER or SafeHandle. This doesn't work as having a CER requires some guarantees, including not allocating additional memory or calling methods that are not decorated with a ReliabilityContract.

Am I missing something obvious here?  How do I handle the user cancelling their query?

Edit: There were multiple iterations of the code for each scenario, but the general actions taken are along the lines of the following:

    [SqlProcedure]
    public static void GetData(SqlString code)
    {
        Guid guid = Guid.NewGuid();
        using (var connection = new SqlConnection("context connection=true"))
        {
            connection.Open();

            try
            {
                SqlContext.Pipe?.Send("Constrain");

                SqlCommand command1 = new SqlCommand($"CREATE TABLE qb.{code}_{guid:N} (Id INT)", connection);
                command1.ExecuteNonQuery();
                SqlContext.Pipe?.Send($"Create: qb.{code}_{guid:N}");

                //emulate service call
                Thread.Sleep(TimeSpan.FromSeconds(10));

                SqlContext.Pipe?.Send($"Done: qb.{code}_{guid:N}");
            }
            finally
            {
                SqlContext.Pipe?.Send("1");
                //drop table here instead of sleep
                Thread.Sleep(2000);
                SqlContext.Pipe?.Send("2");
            }
        }
    }


问:
std chrono time synchronization
I need to send some data over network with timestamps, this time should have high precision. Looking at std::chrono clocks I found out that std::chrono::*_clock::now() returns time_point which is depends at clock's epoch. I failed to find out which epoch is used in each clock and which of them can be used safely when sended wia network. For example on windows high_resolution_clock is wrapper around QueryPerformanceCounter it has good precision, but, I think, useless as timestamp for network tasks.

So question is how to "synchronize" high resolution clock over network?

答:
std::chrono::system_clock's epoch is currently unspecified.  However it is portably a measure of time since 1970-01-01 00:00:00 UTC, neglecting leap seconds.  This is consistent with what is called Unix Time.

I am currently working to standardize this existing practice.  I have private, unofficial assurances from the implementors of std::chrono::system_clock that they will not change their existing practice in the interim.

The other two std-defined chrono clocks:  high_resolution_clock, and steady_clock, do not have portably defined epochs.

Note that system_clock, though it has a (de-facto) portable epoch, does not have portable precision.  On clang/libc++ the precision is microseconds.  On gcc the precision is nanoseconds, and on Windows the precision is 100ns.  So you might time_point_cast<microseconds>(system_clock::now()) to obtain portable precision.

Title: std chrono time synchronization


问:
What verb would describe the relationship between a C# class and its Attribute?
Considering the following:

```<code>[Export]
public class BudgetView : ViewBase, IView
{
    // Members Galore
}
</code>```

It is clear that you would say BudgetView extends ViewBase, and it implements IView, but what does it to to poor old Export?

Perhaps BudgetView uses Export?
Or BudgetView applies Export?

I need this for my documentation.  I'm need to be very formal and very detailed.

Edit:

My UML tool is very restrictive about what I can and cannot do.  I cannot make custom stereotypes for instance.

答:
I would have to say:

BudgetView declares Export

Body:
Considering the following:

[Export]
public class BudgetView : ViewBase, IView
{
    // Members Galore
}

It is clear that you would say BudgetView extends ViewBase, and it implements IView, but what does it to to poor old Export?

Perhaps BudgetView uses Export?
Or BudgetView applies Export?

I need this for my documentation.  I'm need to be very formal and very detailed.

Edit:

My UML tool is very restrictive about what I can and cannot do.  I cannot make custom stereotypes for instance.


问:
non-const find() in std::unordered_set
Why for there is non-const find() in std::unordered_set()?

```<code>iterator find( const Key& key );
const_iterator find( const Key& key ) const;
</code>```

iterator is the same as const_iterator, why there is non-const version of find()?

http://en.cppreference.com/w/cpp/container/unordered_set/find

答:
iterator is the same as const_iterator, why there is non-const version of find()?

Because iterator is not mandatory the same as const_iterator, as stated in documentation:

The member types iterator and const_iterator may be aliases to the same type. Since iterator is convertible to const_iterator, const_iterator should be used in function parameter lists to avoid violations of the One Definition Rule.

emphasis is mine. Since they are not mandatory the same some generic code can depend on particular type of iterator returned by find() and it should be consistent with other containers.

Title: non-const find() in std::unordered_set

Body:
Why for there is non-const find() in std::unordered_set()?

iterator find( const Key& key );
const_iterator find( const Key& key ) const;

iterator is the same as const_iterator, why there is non-const version of find()?

http://en.cppreference.com/w/cpp/container/unordered_set/find


答: If you want "high precision" (you should specify better) synchronization  you would need first of all to make all your network devices to regularly synchronize with the same NTP server. You need to configure the machines in order to adjust the clocks every few minutes (or seconds), because after updated (with some network delays which will make them not precise at the millisecond) , the clocks will start to drift again.</p>

Title: std chrono time synchronization

Body:
I need to send some data over network with timestamps, this time should have high precision. Looking at std::chrono clocks I found out that std::chrono::*_clock::now() returns time_point which is depends at clock's epoch. I failed to find out which epoch is used in each clock and which of them can be used safely when sended wia network. For example on windows high_resolution_clock is wrapper around QueryPerformanceCounter it has good precision, but, I think, useless as timestamp for network tasks.

So question is how to "synchronize" high resolution clock over network?


问:
C++ a class inherit from a type
I created a type, which is a list of priority queues of strings (not my idea, I have to do it):

```<code>typedef list<priority_queue<string>> L;
L myList;
</code>```

Now I need to create a class M, which will inherit from this type. From what I acknowledged, I need to use templates to do so, but I still have no idea how to do it and I haven't found anything online.

How do I make a class inherit from a type?

答:
It's as simple as:

```<code>class foo : L { // Note this is private inheritance
};
</code>```

The type alias is just a name for another type, not a type in its own right. Since std::list is a class template and L names a complete specialization, you can just do it.

Just be sure not to use it in any polymorphic way that involves deleteing a pointer to a std::list. It's not designed for it, since it lacks a virtual destructor.

Title: C++ a class inherit from a type

Body:
I created a type, which is a list of priority queues of strings (not my idea, I have to do it):

typedef list<priority_queue<string>> L;
L myList;

Now I need to create a class M, which will inherit from this type. From what I acknowledged, I need to use templates to do so, but I still have no idea how to do it and I haven't found anything online.

How do I make a class inherit from a type?

Body:
It's as simple as:

class foo : L { // Note this is private inheritance
};

The type alias is just a name for another type, not a type in its own right. Since std::list is a class template and L names a complete specialization, you can just do it.

Just be sure not to use it in any polymorphic way that involves deleteing a pointer to a std::list. It's not designed for it, since it lacks a virtual destructor.


问:
What Authorized IPs should I enter to request BlueSnap API credentials?
I'm developing an Ionic Cordova hybrid mobile app. I need to integrate BlueSnap's Hosted Payment Page into it. So I started with creating a request to get API credentials, following
this tutorial

But I don't know what IP address should I provide. I need enter the IP address to be used for API calls The backend for app is on Heroku platform. So what IP address should I type to get my API credentials ?

Thanks

答:
you need to enter the IP address of the server that will make the API calls,
If your backend server does not have a static IP address, you can contact Bluesnap support and ask them to disable the IP whitelist check on your bluesnap account. and then it does not meter what API address you set in the allowed IP list</p>


答:
MSDN uses the terminology of "applies."  Export is applied to the BudgetView type.

The C# Specification, Version 4 uses this terminology as well.  For example, from 1.12 Attributes:

Attributes can be applied by giving their name, along with any arguments, inside square brackets just before the associated declaration. If an attribute’s name ends in Attribute, that part of the name can be omitted when the attribute is referenced.

Title: What verb would describe the relationship between a C# class and its Attribute?


问:
How to convert multiple arrays into one array of multiple objects?
Given the following arrays:

```<code>let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];
</code>```

How to generated a new array of objects that look like that:

```<code>let z = [
    {x: a, y: e, w: i},
    {x: b, y: f, w: j},
    {x: c, y: g, w: k},
    {x: d, y: h, w: l}
];
</code>```

This is what I came up so far:

```<code>for(var i; i < x.length; i++) {

    x = x[i];
    y = y[i];
    w = w[i];

    obj = {
        x: x,
        y: y,
        w: w
    };

    z = [];
    z.push(obj);
}
</code>```

Thanks!

答:
Use Array#map function and get also the index, which you will use to get the items from the second and third array. I used also || if first array has more items that the others.

let x = ['a', 'b', 'c',' d'];
let y = ['e', 'f', 'g', 'h'];
let w = ['i', 'j', 'k', 'l'];

let mapped = x.map((item, index) => ({ x: item, y: y[index] || '', w: w[index] || '' }));

console.log(mapped);```

Body:
Given the following arrays:

let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];

How to generated a new array of objects that look like that:

let z = [
    {x: a, y: e, w: i},
    {x: b, y: f, w: j},
    {x: c, y: g, w: k},
    {x: d, y: h, w: l}
];

This is what I came up so far:

for(var i; i < x.length; i++) {

    x = x[i];
    y = y[i];
    w = w[i];

    obj = {
        x: x,
        y: y,
        w: w
    };

    z = [];
    z.push(obj);
}

Thanks!


问:
How to construct HighCharts data series to match returned Json via ajax call
I'm trying to construct an Highchart with a JSON returned from my .NET controller. The data is formatted in the following way (in the controller):

```<code>var data = new
        {
             sentiment = new[]
             {
              new { value = "Positive", data = positiveScore.ToString() },
              new { value = "Negative", data = negativeScore.ToString() },
              new { value = "Neutral", data = neutralScore.ToString() }
            }
        };

        return Json(data, JsonRequestBehavior.AllowGet);
</code>```

The data I'm receiving is the following:

My Highchart is constructed in the following way:

```<code>function sentimentAnalysisData(data)
//$(document).ready(function ()
{
var chart = new Highcharts.Chart({
    chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie',
        renderTo: 'highchart'
    },
    title: {
        text: 'Sentiment Analysis'
    },
    tooltip: {
        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
    },
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: true,
                format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                style: {
                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                }
            }
        }
    },
    series: [{data}]

    //});
})
};
</code>```

The data parameter passed to my function is actually the data you can see in the image I provided. I had a GET request via an ajax call, where I retrieved the data, then, in the "on success" callback I'm calling this function which will construct the chart.

My problem is the following: the Highchart is generated, I can see it on my front end, but since my data is passed in a wrong way to the series field, the chart body is actually empty, with no data to show. I've tried to generate it on the way, I also tried to loop through the object, parse it in two arrays and use those arrays (one for the description string and one for value) but I'm missing something. Any helpful thoughts?

答:
I was able to solve my problem in the following way:

I changed the way I constructed my JSON in order to match the pie chart structure in which I had a name and a value part (the name part must be noted as "name", and the value as "y")

```<code> var data = new[]
            {
              new { name = "Positive", y = positiveScore },
              new { name = "Negative", y = negativeScore },
              new { name = "Neutral" , y = neutralScore }

            };

        return Json(data, JsonRequestBehavior.AllowGet);
</code>```

In this way I got the exact structure I was looking for in the first place. Also, I eliminated the .toString() from the y, since Highchart expects a numeric value, not a string. If you omit this part, you'll get the following error:

String value sent to series.data, expected Number his happens if you
  pass in a string as a data point

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to construct an Highchart with a JSON returned from my .NET controller. The data is formatted in the following way (in the controller):

var data = new
        {
             sentiment = new[]
             {
              new { value = "Positive", data = positiveScore.ToString() },
              new { value = "Negative", data = negativeScore.ToString() },
              new { value = "Neutral", data = neutralScore.ToString() }
            }
        };

        return Json(data, JsonRequestBehavior.AllowGet);

The data I'm receiving is the following:

My Highchart is constructed in the following way:

function sentimentAnalysisData(data)
//$(document).ready(function ()
{
var chart = new Highcharts.Chart({
    chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie',
        renderTo: 'highchart'
    },
    title: {
        text: 'Sentiment Analysis'
    },
    tooltip: {
        pointFormat: '{series.name}: {point.percentage:.1f}%'
    },
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: true,
                format: '{point.name}: {point.percentage:.1f} %',
                style: {
                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                }
            }
        }
    },
    series: [{data}]

    //});
})
};

The data parameter passed to my function is actually the data you can see in the image I provided. I had a GET request via an ajax call, where I retrieved the data, then, in the "on success" callback I'm calling this function which will construct the chart.

My problem is the following: the Highchart is generated, I can see it on my front end, but since my data is passed in a wrong way to the series field, the chart body is actually empty, with no data to show. I've tried to generate it on the way, I also tried to loop through the object, parse it in two arrays and use those arrays (one for the description string and one for value) but I'm missing something. Any helpful thoughts?

Body:
I was able to solve my problem in the following way:

I changed the way I constructed my JSON in order to match the pie chart structure in which I had a name and a value part (the name part must be noted as "name", and the value as "y")

 var data = new[]
            {
              new { name = "Positive", y = positiveScore },
              new { name = "Negative", y = negativeScore },
              new { name = "Neutral" , y = neutralScore }

            };

        return Json(data, JsonRequestBehavior.AllowGet);

In this way I got the exact structure I was looking for in the first place. Also, I eliminated the .toString() from the y, since Highchart expects a numeric value, not a string. If you omit this part, you'll get the following error:

String value sent to series.data, expected Number his happens if you
  pass in a string as a data point


问:
Flexslider image galleries on two different tabs
I'm using Bootstrap 2.3.2 and Flexslider 2.6.3 together. I have a set of nav-pills with two tabs. Each tab has a separate Flexslider gallery with thumbnail navigation. The problem is that the thumbnails on the second tab aren't visible until you resize the window. How can I fix this?

Example

答:
The issue seems to be that each of the

 tags on the second slider have a width of 0px.

```<code>  <div id="carousel2" class="flexslider carousel">
   <div class="flex-viewport" style="overflow: hidden; position: relative;">
    <ul class="slides" style="width: 600%; transition-duration: 0s;">
     <li class="flex-active-slide" style="width: 0px; margin-right: 3px; float: left; display: block;"><img src="images/tn-space1.jpg" draggable="false" /></li>
     <li style="width: 0px; margin-right: 3px; float: left; display: block;"><img src="images/tn-space2.jpg" draggable="false" /></li>
     <li style="width: 0px; margin-right: 3px; float: left; display: block;"><img src="images/tn-space3.jpg" draggable="false" /></li>
    </ul>
   </div>
   <ul class="flex-direction-nav">
    <li class="flex-nav-prev"><a class="flex-prev flex-disabled" href="#" tabindex="-1">Previous</a></li>
    <li class="flex-nav-next"><a class="flex-next" href="#">Next</a></li>
   </ul>
  </div>
</code>```

Set the width to auto and the images show as they should immediately on my system without resizing

It's difficult to properly determine as those inline styles could be outputted by a JS file and we can't tell by looking at a site. If this doesn't work, create a code snippet and supply the base HTML, CSS and JS code

Body:
The issue seems to be that each of the <li></li> tags on the second slider have a width of 0px.

  <div id="carousel2" class="flexslider carousel">
   <div class="flex-viewport" style="overflow: hidden; position: relative;">
    <ul class="slides" style="width: 600%; transition-duration: 0s;">
     <li class="flex-active-slide" style="width: 0px; margin-right: 3px; float: left; display: block;"><img src="images/tn-space1.jpg" draggable="false" /></li>
     <li style="width: 0px; margin-right: 3px; float: left; display: block;"><img src="images/tn-space2.jpg" draggable="false" /></li>
     <li style="width: 0px; margin-right: 3px; float: left; display: block;"><img src="images/tn-space3.jpg" draggable="false" /></li>
    </ul>
   </div>
   <ul class="flex-direction-nav">
    <li class="flex-nav-prev"><a class="flex-prev flex-disabled" href="#" tabindex="-1">Previous</a></li>
    <li class="flex-nav-next"><a class="flex-next" href="#">Next</a></li>
   </ul>
  </div>

Set the width to auto and the images show as they should immediately on my system without resizing

It's difficult to properly determine as those inline styles could be outputted by a JS file and we can't tell by looking at a site. If this doesn't work, create a code snippet and supply the base HTML, CSS and JS code


问:
Return two screens back in dynpro sequence
I want to develop the following logic:

The box "DISPLAY ALV" corresponds to the function module REUSE_ALV_GRID_DISPLAY.

With LEAVE TO SCREEN 0 I can't pass directly to DISPLAY ALV. Is it possible?

Thank you.

答:
No, you cannot return to FM, as you intend to do, 'cause FM is a special callable unit and LEAVE TO SCREEN statement works only for screens. However, you can return to screen 100 which shows that ALV.

Consider following coding, for which you should have screens 100 and 300 with custom containers 100_CONT and 300_CONT on them.

Screen 100 PBO

```<code>MODULE pbo_100 OUTPUT.
  SET PF-STATUS 'YOUR_PF_STATUS'.
  IF custom_container1 IS INITIAL.

    SELECT *
      FROM mara AS m
      INTO TABLE gt_mara
      WHERE EXISTS ( SELECT * FROM vbrp WHERE matnr = m~matnr ).

    CREATE OBJECT custom_container1
      EXPORTING
        container_name = cont_on_main.

    CREATE OBJECT grid1
      EXPORTING
        i_parent = custom_container1.

    CALL METHOD grid1->set_table_for_first_display
      EXPORTING
        i_structure_name = 'mara'
        is_layout        = gs_layout
      CHANGING
        it_outtab        = gt_mara.

    CREATE OBJECT event_receiver.
    SET HANDLER event_receiver->handle_double_click FOR grid1.

  ENDIF.
ENDMODULE.                             " PBO_100  OUTPUT
</code>```

Screen 300 PBO

```<code>MODULE pbo_0300 OUTPUT.
  IF custom_container2 IS INITIAL.
    CREATE OBJECT custom_container2
      EXPORTING
        container_name = cont_on_dialog.

    CREATE OBJECT grid2
      EXPORTING
        i_parent = custom_container2.

    gs_layout-grid_title = 'Orders'.

    CALL METHOD grid2->set_table_for_first_display
      EXPORTING
        i_structure_name = 'VBRP'
        is_layout        = gs_layout
      CHANGING
        it_outtab        = gt_vbrp.

  ELSE.
    CALL METHOD grid2->refresh_table_display.
  ENDIF.

ENDMODULE.                             " PBO_0300  OUTPUT
</code>```

Screen 300 PAI

```<code>MODULE pai_0300 INPUT.
  CASE ok_code.
    WHEN 'RETURN'.
      DATA: ans.
      CALL FUNCTION 'POPUP_TO_CONFIRM'
        EXPORTING
          titlebar              = 'SO sample'
          text_question         = 'Select next action'
          text_button_1         = 'Yes'
          icon_button_1         = 'ICON_CHECKED'
          text_button_2         = 'No'
          icon_button_2         = 'ICON_CANCEL'
          display_cancel_button = ' '
        IMPORTING
          answer                = ans.

      CASE ans.
        WHEN 1.
          LEAVE TO SCREEN 0.
        WHEN 2.
          LEAVE PROGRAM.
        WHEN OTHERS.
      ENDCASE.

  ENDCASE.
  CLEAR ok_code.
ENDMODULE.
</code>```

Main program

```<code>CLASS lcl_event_receiver DEFINITION DEFERRED.

DATA: ok_code           LIKE sy-ucomm,
      gt_mara           TYPE TABLE OF mara,
      gt_vbrp           TYPE TABLE OF vbrp,
      grid1             TYPE REF TO cl_gui_alv_grid,
      grid2             TYPE REF TO cl_gui_alv_grid,
      cont_on_main      TYPE scrfname VALUE '100_CONT',
      cont_on_dialog    TYPE scrfname VALUE '300_CONT',
      custom_container1 TYPE REF TO cl_gui_custom_container,
      custom_container2 TYPE REF TO cl_gui_custom_container,
      event_receiver    TYPE REF TO lcl_event_receiver.

START-OF-SELECTION.

  CALL SCREEN 100.

CLASS lcl_event_receiver DEFINITION.
  PUBLIC SECTION.
    METHODS: handle_double_click FOR EVENT double_click OF cl_gui_alv_grid
      IMPORTING e_row e_column.
ENDCLASS.

CLASS lcl_event_receiver IMPLEMENTATION.
  METHOD handle_double_click.
    READ TABLE gt_mara INDEX e_row-index ASSIGNING FIELD-SYMBOL(<fs_mara>).

    SELECT *
      INTO TABLE gt_vbrp
      FROM vbrp
      WHERE matnr = <fs_mara>-matnr.

    CALL SCREEN 300 STARTING AT 10 5.
  ENDMETHOD.

ENDCLASS.
</code>```

Here at program start we fetch material list with sales orders in the system, and then on double click on screen 100 these orders are showed in screen 300.

By special button with function code RETURN (you should place it on screen 300) we call popup window for interaction with user. By pressing Yes it returns to the initial screen 100, by pressing No the program is interrupted completely.

Here you should pay attention to statement LEAVE TO SCREEN 0 which terminates current dynpro sequence (i.e. 300) and thus returns to 100.

Body:
No, you cannot return to FM, as you intend to do, 'cause FM is a special callable unit and LEAVE TO SCREEN statement works only for screens. However, you can return to screen 100 which shows that ALV.

Consider following coding, for which you should have screens 100 and 300 with custom containers 100_CONT and 300_CONT on them.

Screen 100 PBO

MODULE pbo_100 OUTPUT.
  SET PF-STATUS 'YOUR_PF_STATUS'.
  IF custom_container1 IS INITIAL.

    SELECT *
      FROM mara AS m
      INTO TABLE gt_mara
      WHERE EXISTS ( SELECT * FROM vbrp WHERE matnr = m~matnr ).

    CREATE OBJECT custom_container1
      EXPORTING
        container_name = cont_on_main.

    CREATE OBJECT grid1
      EXPORTING
        i_parent = custom_container1.

    CALL METHOD grid1->set_table_for_first_display
      EXPORTING
        i_structure_name = 'mara'
        is_layout        = gs_layout
      CHANGING
        it_outtab        = gt_mara.

    CREATE OBJECT event_receiver.
    SET HANDLER event_receiver->handle_double_click FOR grid1.

  ENDIF.
ENDMODULE.                             " PBO_100  OUTPUT

Screen 300 PBO

MODULE pbo_0300 OUTPUT.
  IF custom_container2 IS INITIAL.
    CREATE OBJECT custom_container2
      EXPORTING
        container_name = cont_on_dialog.

    CREATE OBJECT grid2
      EXPORTING
        i_parent = custom_container2.

    gs_layout-grid_title = 'Orders'.

    CALL METHOD grid2->set_table_for_first_display
      EXPORTING
        i_structure_name = 'VBRP'
        is_layout        = gs_layout
      CHANGING
        it_outtab        = gt_vbrp.

  ELSE.
    CALL METHOD grid2->refresh_table_display.
  ENDIF.

ENDMODULE.                             " PBO_0300  OUTPUT

Screen 300 PAI

MODULE pai_0300 INPUT.
  CASE ok_code.
    WHEN 'RETURN'.
      DATA: ans.
      CALL FUNCTION 'POPUP_TO_CONFIRM'
        EXPORTING
          titlebar              = 'SO sample'
          text_question         = 'Select next action'
          text_button_1         = 'Yes'
          icon_button_1         = 'ICON_CHECKED'
          text_button_2         = 'No'
          icon_button_2         = 'ICON_CANCEL'
          display_cancel_button = ' '
        IMPORTING
          answer                = ans.

      CASE ans.
        WHEN 1.
          LEAVE TO SCREEN 0.
        WHEN 2.
          LEAVE PROGRAM.
        WHEN OTHERS.
      ENDCASE.

  ENDCASE.
  CLEAR ok_code.
ENDMODULE.

Main program

CLASS lcl_event_receiver DEFINITION DEFERRED.

DATA: ok_code           LIKE sy-ucomm,
      gt_mara           TYPE TABLE OF mara,
      gt_vbrp           TYPE TABLE OF vbrp,
      grid1             TYPE REF TO cl_gui_alv_grid,
      grid2             TYPE REF TO cl_gui_alv_grid,
      cont_on_main      TYPE scrfname VALUE '100_CONT',
      cont_on_dialog    TYPE scrfname VALUE '300_CONT',
      custom_container1 TYPE REF TO cl_gui_custom_container,
      custom_container2 TYPE REF TO cl_gui_custom_container,
      event_receiver    TYPE REF TO lcl_event_receiver.

START-OF-SELECTION.

  CALL SCREEN 100.

CLASS lcl_event_receiver DEFINITION.
  PUBLIC SECTION.
    METHODS: handle_double_click FOR EVENT double_click OF cl_gui_alv_grid
      IMPORTING e_row e_column.
ENDCLASS.

CLASS lcl_event_receiver IMPLEMENTATION.
  METHOD handle_double_click.
    READ TABLE gt_mara INDEX e_row-index ASSIGNING FIELD-SYMBOL(<fs_mara>).

    SELECT *
      INTO TABLE gt_vbrp
      FROM vbrp
      WHERE matnr = <fs_mara>-matnr.

    CALL SCREEN 300 STARTING AT 10 5.
  ENDMETHOD.

ENDCLASS.

Here at program start we fetch material list with sales orders in the system, and then on double click on screen 100 these orders are showed in screen 300.

By special button with function code RETURN (you should place it on screen 300) we call popup window for interaction with user. By pressing Yes it returns to the initial screen 100, by pressing No the program is interrupted completely.

Here you should pay attention to statement LEAVE TO SCREEN 0 which terminates current dynpro sequence (i.e. 300) and thus returns to 100.


问:
Prevent hardcoded values in Winform designer file while using User Controls
I am trying to include a calendar like custom user control that picks month and year. In the user control code I am setting two properties, Month and Year to current month and year.

```<code>public MonthPicker()
    {
        InitializeComponent();
        m_MonthLabels = new Label[]
        {
        lblJanuary,
        lblFebruary,
        lblMarch,
        lblApril,
        lblMay,
        lblJune,
        lblJuly,
        lblAugust,
        lblSeptember,
        lblOctober,
        lblNovember,
        lblDecember
        };

        m_NotSelected = new Font("Sans Serif", 8.25F, FontStyle.Regular);
        m_Selected = new Font("Sans Serif", 8.25F, FontStyle.Bold);
        Month = DateTime.Now.Month;
        Year = DateTime.Now.Year;
        lblYear.Text = Year.ToString();
        groupBox2.Visible = false;
        groupBox1.Height = 20;
        CalendarIsDisplayed = false;
        CalendarIsNotChanged = false;
        SetMonthLabelSelected(Month);
    }
</code>```

However, when I include it in my Application form, the designer takes hard coded values for Month and Year. Consequently, when the month changes it still shows me older month.

```<code>        // tsMonthPicker
        //
        this.tsMonthPicker.BackColor = System.Drawing.SystemColors.Control;
        this.tsMonthPicker.CalendarIsDisplayed = false;
        this.tsMonthPicker.CalendarIsNotChanged = false;
        this.tsMonthPicker.Location = new System.Drawing.Point(104, 14);
        this.tsMonthPicker.Margin = new System.Windows.Forms.Padding(0);
        this.tsMonthPicker.Month = 1;
        this.tsMonthPicker.Name = "tsMonthPicker";
        this.tsMonthPicker.Size = new System.Drawing.Size(215, 20);
        this.tsMonthPicker.TabIndex = 6;
        this.tsMonthPicker.Value = new System.DateTime(2017, 1, 1, 0, 0, 0, 0);
        this.tsMonthPicker.Year = 2017;
        this.tsMonthPicker.Change += new Time_and_Billing_System.MonthPicker.MonthPickerChangeHandler(this.tsMonthPicker_Changed);
        this.tsMonthPicker.Load += new System.EventHandler(this.tsMonthPicker_Load);
</code>```

How do I change my code in user control so that the form designer file automatically takes -

```<code>this.tsMonthPicker.Month = System.DateTime.Now.Month;
this.tsMonthPicker.Year = System.DateTime.Now.Year;
</code>```

答:
You could use the DesignMode property for this. You don't state if you need a default value of Now each time the app is launched. If that is the case then you don't need the DesignMode.

```<code>public MonthPicker()
{
    if (this.DesignMode)
    {
        //These values are only set when the control is created in design mode
        this.tsMonthPicker.Month = System.DateTime.Now.Month;
        this.tsMonthPicker.Year = System.DateTime.Now.Year;
    }
}
</code>```

Body:
I am trying to include a calendar like custom user control that picks month and year. In the user control code I am setting two properties, Month and Year to current month and year.

public MonthPicker()
    {
        InitializeComponent();
        m_MonthLabels = new Label[]
        {
        lblJanuary,
        lblFebruary,
        lblMarch,
        lblApril,
        lblMay,
        lblJune,
        lblJuly,
        lblAugust,
        lblSeptember,
        lblOctober,
        lblNovember,
        lblDecember
        };

        m_NotSelected = new Font("Sans Serif", 8.25F, FontStyle.Regular);
        m_Selected = new Font("Sans Serif", 8.25F, FontStyle.Bold);
        Month = DateTime.Now.Month;
        Year = DateTime.Now.Year;
        lblYear.Text = Year.ToString();
        groupBox2.Visible = false;
        groupBox1.Height = 20;
        CalendarIsDisplayed = false;
        CalendarIsNotChanged = false;
        SetMonthLabelSelected(Month);
    }

However, when I include it in my Application form, the designer takes hard coded values for Month and Year. Consequently, when the month changes it still shows me older month.

        // tsMonthPicker
        //
        this.tsMonthPicker.BackColor = System.Drawing.SystemColors.Control;
        this.tsMonthPicker.CalendarIsDisplayed = false;
        this.tsMonthPicker.CalendarIsNotChanged = false;
        this.tsMonthPicker.Location = new System.Drawing.Point(104, 14);
        this.tsMonthPicker.Margin = new System.Windows.Forms.Padding(0);
        this.tsMonthPicker.Month = 1;
        this.tsMonthPicker.Name = "tsMonthPicker";
        this.tsMonthPicker.Size = new System.Drawing.Size(215, 20);
        this.tsMonthPicker.TabIndex = 6;
        this.tsMonthPicker.Value = new System.DateTime(2017, 1, 1, 0, 0, 0, 0);
        this.tsMonthPicker.Year = 2017;
        this.tsMonthPicker.Change += new Time_and_Billing_System.MonthPicker.MonthPickerChangeHandler(this.tsMonthPicker_Changed);
        this.tsMonthPicker.Load += new System.EventHandler(this.tsMonthPicker_Load);

How do I change my code in user control so that the form designer file automatically takes -

this.tsMonthPicker.Month = System.DateTime.Now.Month;
this.tsMonthPicker.Year = System.DateTime.Now.Year;

Body:
You could use the DesignMode property for this. You don't state if you need a default value of Now each time the app is launched. If that is the case then you don't need the DesignMode.

public MonthPicker()
{
    if (this.DesignMode)
    {
        //These values are only set when the control is created in design mode
        this.tsMonthPicker.Month = System.DateTime.Now.Month;
        this.tsMonthPicker.Year = System.DateTime.Now.Year;
    }
}


答:
Try

```<code>var z = x.map( (s,i) => ({ x : x[i], y : y[i], w : w[i] }) );
</code>```

Explanation

iterate x using map

for each index of x, return an object having keys as x, y and z with values from their respective index.

Demo

var x = ['a', 'b', 'c', 'd'];
var y = ['e', 'f', 'g', 'h'];
var w = ['i', 'j', 'k', 'l'];

var z = x.map((s, i) => ({
  x: x[i],
  y: y[i],
  w: w[i]
}));

console.log(z);```

Title: How to convert multiple arrays into one array of multiple objects?

Body:
Try

var z = x.map( (s,i) => ({ x : x[i], y : y[i], w : w[i] }) );

Explanation

iterate x using map

for each index of x, return an object having keys as x, y and z with values from their respective index.

Demo

var x = ['a', 'b', 'c', 'd'];
var y = ['e', 'f', 'g', 'h'];
var w = ['i', 'j', 'k', 'l'];

var z = x.map((s, i) => ({
  x: x[i],
  y: y[i],
  w: w[i]
}));

console.log(z);


问:
memory leak in osgearth

My goal is using library OSGEarth to make a MFC project that can display the model "openstreetmap.earth". I finished this and can see the the earth.But every time when i close the project, the output window in vs2015 say there are memory leaks in the program.

Here is the window output:

```<code>Detected memory leaks!
Dumping objects ->
{306240} normal block at 0x00000000076902F0, 16 bytes long.
Data: <0,i             > 30 2C 69 07 00 00 00 00 00 00 00 00 00 00 00 00
{306239} normal block at 0x0000000007692C30, 9 bytes long.
Data: <Pragma:  > 50 72 61 67 6D 61 3A 20 00
{303648} normal block at 0x0000000007693040, 16 bytes long.
Data: < 5i             > 90 35 69 07 00 00 00 00 00 00 00 00 00 00 00 00
{303647} normal block at 0x0000000007693590, 9 bytes long.
Data: <Pragma:  > 50 72 61 67 6D 61 3A 20 00
{301180} normal block at 0x00000000076938B0, 16 bytes long.
 Data: <`8i             > 60 38 69 07 00 00 00 00 00 00 00 00 00 00 00 00
{301179} normal block at 0x0000000007693860, 9 bytes long.
 Data: <Pragma:  > 50 72 61 67 6D 61 3A 20 00
{297799} normal block at 0x0000000007691060, 16 bytes long.
 Data: <  i             > 10 10 69 07 00 00 00 00 00 00 00 00 00 00 00 00
</code>```

I examined the program and found that when I delete this code m_Model = osgDB::readNodeFile(m_strModelName); there is no more memory leaks.

```<code>void COSGEarth::InitSceneGraph(void)
{
    // Init the main Root Node/Group
    m_Root = new osg::Group;
    // Load the Model from the model name,
    //delete below line, no memory leak
    m_Model = osgDB::readNodeFile(m_strModelName);
    if (!m_Model) return;

    // Optimize the model
    osgUtil::Optimizer optimizer;
    optimizer.optimize(m_Model.get());
    optimizer.reset();

    // Add the model to the scene
    m_Root->addChild(m_Model.get());
</code>```

}

I defined m_Model as osg::ref_ptr<osg::Node> m_Model. This is Intelligent pointer.

Why there are memory leaks and how I can solve this issue?

Here is source code :http://bbs.osgchina.org/forum.php?mod=attachment&aid=NzIwNnwzZWYxZDIyZjlhOGY1MWFjZjhiNGFiMWYwMTc5YmJlNXwxNTEyMzc5ODE2&request=yes&_f=.zip

答:
I believe these reported "leaks" are false positives. Refer to this thread that explains why:

http://forum.openscenegraph.org/viewtopic.php?t=1475

Title: memory leak in osgearth

Body:
My goal is using library OSGEarth to make a MFC project that can display the model "openstreetmap.earth". I finished this and can see the the earth.But every time when i close the project, the output window in vs2015 say there are memory leaks in the program.

Here is the window output:

Detected memory leaks!
Dumping objects ->
{306240} normal block at 0x00000000076902F0, 16 bytes long.
Data: <0,i             > 30 2C 69 07 00 00 00 00 00 00 00 00 00 00 00 00
{306239} normal block at 0x0000000007692C30, 9 bytes long.
Data: <Pragma:  > 50 72 61 67 6D 61 3A 20 00
{303648} normal block at 0x0000000007693040, 16 bytes long.
Data: < 5i             > 90 35 69 07 00 00 00 00 00 00 00 00 00 00 00 00
{303647} normal block at 0x0000000007693590, 9 bytes long.
Data: <Pragma:  > 50 72 61 67 6D 61 3A 20 00
{301180} normal block at 0x00000000076938B0, 16 bytes long.
 Data: <`8i             > 60 38 69 07 00 00 00 00 00 00 00 00 00 00 00 00
{301179} normal block at 0x0000000007693860, 9 bytes long.
 Data: <Pragma:  > 50 72 61 67 6D 61 3A 20 00
{297799} normal block at 0x0000000007691060, 16 bytes long.
 Data:  10 10 69 07 00 00 00 00 00 00 00 00 00 00 00 00

I examined the program and found that when I delete this code m_Model = osgDB::readNodeFile(m_strModelName); there is no more memory leaks.

void COSGEarth::InitSceneGraph(void)
{
    // Init the main Root Node/Group
    m_Root = new osg::Group;
    // Load the Model from the model name,
    //delete below line, no memory leak
    m_Model = osgDB::readNodeFile(m_strModelName);
    if (!m_Model) return;

    // Optimize the model
    osgUtil::Optimizer optimizer;
    optimizer.optimize(m_Model.get());
    optimizer.reset();

    // Add the model to the scene
    m_Root->addChild(m_Model.get());

}

I defined m_Model as osg::ref_ptr<osg::Node> m_Model. This is Intelligent pointer.

Why there are memory leaks and how I can solve this issue?

Here is source code :http://bbs.osgchina.org/forum.php?mod=attachment&aid=NzIwNnwzZWYxZDIyZjlhOGY1MWFjZjhiNGFiMWYwMTc5YmJlNXwxNTEyMzc5ODE2&request=yes&_f=.zip


问:
Unstable Office(Powerpoint) Automation
I am working on an app that will allow the user to upload a presentation, edit it, and then download the final output as another PowerPoint presentation.

I have very unstable behavior for different presentations that I upload:

Sometimes the changed images are blurred (Not sure why?)

Sometimes incorrect shape ids are returned, and therefore I can not merge the changed work with the existing PowerPoint shape.

```<code>var shape = (PowerPoint.Shape)item;
var shapeid=shape.ID; //this is different from what interop has returned on first presentation read.
</code>```

Animations are not getting copied properly(sometimes they do sometimes they do not).

```<code>      newshape.AnimationSettings.EntryEffect = oldshape.AnimationSettings.EntryEffect;
      newshape.AnimationSettings.AdvanceMode=oldshape.AnimationSettings.AdvanceMode;
      newshape.AnimationSettings.AdvanceTime=oldshape.AnimationSettings.AdvanceTime;
      newshape.AnimationSettings.AfterEffect=oldshape.AnimationSettings.AfterEffect;
      newshape.AnimationSettings.Animate=oldshape.AnimationSettings.Animate;
      newshape.AnimationSettings.AnimateBackground = oldshape.AnimationSettings.AnimateBackground;
      newshape.AnimationSettings.TextLevelEffect = PowerPoint.PpTextLevelEffect.ppAnimateByAllLevels;
      newshape.AnimationSettings.AnimateTextInReverse=oldshape.AnimationSettings.AnimateTextInReverse;
</code>```

I am aware of the fact that server side automation may have unstable behavior or deadlock. However nothing documents exactly what is unstable about the behavior.

Are these behaviors (above two) in same category or am I missing something here? How can I fix these issues?

答:
If you still need to use Interop then try to release the COM objects and ocasionally kill the PowerPoint instances as mentioned below:</p>

```<code>public static class PowerPointInterOp
{
    static PowerPoint.Application powerPointApp = null;
    static Object oMissing = System.Reflection.Missing.Value;
    static Object oTrue = true;
    static Object oFalse = false;
    static Object oCopies = 1;

    public static void InitializeInstance()
    {
        if (powerPointApp == null)
        {
            powerPointApp = new PowerPoint.ApplicationClass();

        }
    }

    public static void KillInstances()
    {
        try
        {
            Process[] processes = Process.GetProcessesByName("POWERPNT");
            foreach(Process process in processes)
            {
                process.Kill();
            }
        }
        catch(Exception)
        {

        }
    }

    public static void CloseInstance()
    {
        if (powerPointApp != null)
        {
            powerPointApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(powerPointApp);
            powerPointApp = null;
        }
    }

    public static PowerPoint.Presentation OpenDocument(string documentPath)
    {
        InitializeInstance();

        PowerPoint.Presentation powerPointDoc = powerPointApp.Presentations.Open(documentPath, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);

        return powerPointDoc;
    }

    public static void CloseDocument(PowerPoint.Presentation powerPointDoc)
    {
        if (powerPointDoc != null)
        {
            powerPointDoc.Close();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(powerPointDoc);
            powerPointDoc = null;
        }
    }

}
</code>```

Title: Unstable Office(Powerpoint) Automation

Body:
I am working on an app that will allow the user to upload a presentation, edit it, and then download the final output as another PowerPoint presentation.

I have very unstable behavior for different presentations that I upload:

Sometimes the changed images are blurred (Not sure why?)

Sometimes incorrect shape ids are returned, and therefore I can not merge the changed work with the existing PowerPoint shape.

var shape = (PowerPoint.Shape)item;
var shapeid=shape.ID; //this is different from what interop has returned on first presentation read.

Animations are not getting copied properly(sometimes they do sometimes they do not).

      newshape.AnimationSettings.EntryEffect = oldshape.AnimationSettings.EntryEffect;
      newshape.AnimationSettings.AdvanceMode=oldshape.AnimationSettings.AdvanceMode;
      newshape.AnimationSettings.AdvanceTime=oldshape.AnimationSettings.AdvanceTime;
      newshape.AnimationSettings.AfterEffect=oldshape.AnimationSettings.AfterEffect;
      newshape.AnimationSettings.Animate=oldshape.AnimationSettings.Animate;
      newshape.AnimationSettings.AnimateBackground = oldshape.AnimationSettings.AnimateBackground;
      newshape.AnimationSettings.TextLevelEffect = PowerPoint.PpTextLevelEffect.ppAnimateByAllLevels;
      newshape.AnimationSettings.AnimateTextInReverse=oldshape.AnimationSettings.AnimateTextInReverse;

I am aware of the fact that server side automation may have unstable behavior or deadlock. However nothing documents exactly what is unstable about the behavior.

Are these behaviors (above two) in same category or am I missing something here? How can I fix these issues?

Body:
If you still need to use Interop then try to release the COM objects and ocasionally kill the PowerPoint instances as mentioned below:

public static class PowerPointInterOp
{
    static PowerPoint.Application powerPointApp = null;
    static Object oMissing = System.Reflection.Missing.Value;
    static Object oTrue = true;
    static Object oFalse = false;
    static Object oCopies = 1;

    public static void InitializeInstance()
    {
        if (powerPointApp == null)
        {
            powerPointApp = new PowerPoint.ApplicationClass();

        }
    }

    public static void KillInstances()
    {
        try
        {
            Process[] processes = Process.GetProcessesByName("POWERPNT");
            foreach(Process process in processes)
            {
                process.Kill();
            }
        }
        catch(Exception)
        {

        }
    }

    public static void CloseInstance()
    {
        if (powerPointApp != null)
        {
            powerPointApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(powerPointApp);
            powerPointApp = null;
        }
    }

    public static PowerPoint.Presentation OpenDocument(string documentPath)
    {
        InitializeInstance();

        PowerPoint.Presentation powerPointDoc = powerPointApp.Presentations.Open(documentPath, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);

        return powerPointDoc;
    }

    public static void CloseDocument(PowerPoint.Presentation powerPointDoc)
    {
        if (powerPointDoc != null)
        {
            powerPointDoc.Close();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(powerPointDoc);
            powerPointDoc = null;
        }
    }

}