问:
Assign an individual in a dataset to a particular state based on predetermined proportions in R
I have data which looks like this

```<code>df <- data.frame(
age_grp10 = rep(c("00-09", "10-19", "20-29", "30-39", "40-49", "50-59", "60-    69", "70-79", "80-89"), 2),
sex = c(rep("M", 9), rep("F", 9)),
prob_arr = round((runif(18, min = 0.11, max = 2.50)), digits = 2),
prob_dep = round((runif(18, min = 0.11, max = 2.50)), digits = 2)
)
</code>```

This dataset gives the proportion of people, by age and gender, who arrive or depart in a calendar year.

Then I have population level data, which looks like this

```<code>  pop_df <- data.frame(
  uniq_ID = c("AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
          "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234"),
  age_grp10 = c("50-59", "40-49", "20-29", "40-49", "00-09",  "50-59", "30-39", "70-79",  "60-69", "40-49",
            "80-89", "10-19", "30-39", "30-39", "50-59", "70-79", "00-09", "70-79", "20-29", "20-29"),
  sex = c("M", "M", "F", "M", "F", "F", "F", "M", "F", "M", "F", "F", "M", "M", "M", "M", "M", "F", "M", "F"))
</code>```

In this population dataset, each row is an individual, for about 5 million people. It shows their age and gender, and unique ID number.
Based on the proportions in the first dataframe (df), I would like to assign arrival and departure status to the individuals in the population dataframe (pop_df).

My desired output would look like

```<code>pop_df <- pop_df %>%
left_join(df) %>%
mutate(Arrived = c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0),
     Departed = c(1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
</code>```

In this last dataset, the values of Arrived and Departed are dependent on the proportions in the df dataframe. So XX% of males aged 0-9 years would be assigned arrival status, based on the value of prob_arr in the df dataframe.

Thanks for your help

答:
Assuming that (a) the probabilities are percentages, and (b) that they are independent, here's a simple method in dplyr:

```<code>library(dplyr)
pop_df %>% left_join(df) %>%
  mutate(Arrived = as.integer(runif(n()) * 100 < prob_arr),
         Departed = as.integer(runif(n()) * 100 < prob_dep))
</code>```

Though the same logic is just about as easy in base:

```<code>joined_df = merge(pop_df, df)
transform(
  joined_df,
  Arrived = as.integer(runif(nrow(joined_df)) * 100 < prob_arr),
  Departed = as.integer(runif(nrow(joined_df)) * 100 < prob_dep)
)
</code>```

Body:
I have data which looks like this

df <- data.frame(
age_grp10 = rep(c("00-09", "10-19", "20-29", "30-39", "40-49", "50-59", "60-    69", "70-79", "80-89"), 2),
sex = c(rep("M", 9), rep("F", 9)),
prob_arr = round((runif(18, min = 0.11, max = 2.50)), digits = 2),
prob_dep = round((runif(18, min = 0.11, max = 2.50)), digits = 2)
)

This dataset gives the proportion of people, by age and gender, who arrive or depart in a calendar year.

Then I have population level data, which looks like this

  pop_df <- data.frame(
  uniq_ID = c("AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
          "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234"),
  age_grp10 = c("50-59", "40-49", "20-29", "40-49", "00-09",  "50-59", "30-39", "70-79",  "60-69", "40-49",
            "80-89", "10-19", "30-39", "30-39", "50-59", "70-79", "00-09", "70-79", "20-29", "20-29"),
  sex = c("M", "M", "F", "M", "F", "F", "F", "M", "F", "M", "F", "F", "M", "M", "M", "M", "M", "F", "M", "F"))

In this population dataset, each row is an individual, for about 5 million people. It shows their age and gender, and unique ID number.
Based on the proportions in the first dataframe (df), I would like to assign arrival and departure status to the individuals in the population dataframe (pop_df).

My desired output would look like

pop_df <- pop_df %>%
left_join(df) %>%
mutate(Arrived = c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0),
     Departed = c(1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))

In this last dataset, the values of Arrived and Departed are dependent on the proportions in the df dataframe. So XX% of males aged 0-9 years would be assigned arrival status, based on the value of prob_arr in the df dataframe.

Thanks for your help

Body:
Assuming that (a) the probabilities are percentages, and (b) that they are independent, here's a simple method in dplyr:

library(dplyr)
pop_df %>% left_join(df) %>%
  mutate(Arrived = as.integer(runif(n()) * 100 < prob_arr),
         Departed = as.integer(runif(n()) * 100 < prob_dep))

Though the same logic is just about as easy in base:

joined_df = merge(pop_df, df)
transform(
  joined_df,
  Arrived = as.integer(runif(nrow(joined_df)) * 100 < prob_arr),
  Departed = as.integer(runif(nrow(joined_df)) * 100 < prob_dep)
)


来源: stackexchange

问:
How to make a live date display using Python and tkinter
I'm trying to make an info center and I need to add a live date display, so every day it adds another day to it, if a month passes it would add a month to it. How would I do it?

I've googled and still have no idea, I know how to display it but no clue how to make it automatically update. would it be possible to do it like this below?

```<code>def tick():
    time_string = time.strftime("%H:%M:%S")
    clock.config(text=time_string)
    clock.after(200, tick)

root = Tk()

clock = Label(root, font=("none", 50, "bold"), bg="#000000", fg="#910000", bd=5, relief="ridge")
clock.grid(row=0, column=0)

tick()

root.mainloop()
</code>```

答:
Your logic is fine. If you want to display months and days, you can use datetime module instead:

```<code>from datetime import datetime

def tick():
    now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    clock.config(text=now)
    clock.after(200, tick)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make an info center and I need to add a live date display, so every day it adds another day to it, if a month passes it would add a month to it. How would I do it?

I've googled and still have no idea, I know how to display it but no clue how to make it automatically update. would it be possible to do it like this below?

def tick():
    time_string = time.strftime("%H:%M:%S")
    clock.config(text=time_string)
    clock.after(200, tick)

root = Tk()

clock = Label(root, font=("none", 50, "bold"), bg="#000000", fg="#910000", bd=5, relief="ridge")
clock.grid(row=0, column=0)

tick()

root.mainloop()

Body:
Your logic is fine. If you want to display months and days, you can use datetime module instead:

from datetime import datetime

def tick():
    now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    clock.config(text=now)
    clock.after(200, tick)


问:
How to convert this string "Mon Jan 01 00:00:00 AEDT 1990" into "1990101"?
I have a string "Mon Jan 01 00:00:00 AEDT 1990" and I need to convert it into the format "yyyyMMdd" so in this case it would be "19900101".

I think it's possible to do this with Regular Expressions so that I could pull out the year, month(but would need to convert Jan to 01 and etc) and day from the string but I am not well versed in Regular Expressions. Anyone have any ideas?

答:
tl;dr

Regex is overkill.

Here is a one-liner solution using java.time classes built into Java.

```<code>ZonedDateTime                            // Represent a moment as seen through the wall-clock time used by the people of a certain region (a time zone).
.parse(                                  // Parse the input text.
    "Mon Jan 01 00:00:00 AEDT 1990" ,
    DateTimeFormatter.ofPattern(
        "EEE MMM dd HH:mm:ss z uuuu" ,   // Specify a custom formatting pattern to match our input.
        Locale.US                        // Specify a `Locale` for the human language to use in translating the name of month& day-of-week.
    )                                    // Returns a `DateTimeFormatter` object.
)                                        // Returns a `ZonedDateTime` object.
.toLocalDate()                           // Extract the date, without time-of-day and without time zone.
.format(                                 // Generate text to represent the value of our `LocalDate` object.
    DateTimeFormatter.BASIC_ISO_DATE     // Use the predefined formatting pattern YYYYMMDD.
)                                        // Returns a String.
</code>```

19900101

java.time

Regex is overkill for this.

The modern approach uses java.time classes.

Specify a custom formatting pattern to fit your input.

Specify a locale to facilitate translating the name of day-of-week and name of month.

ZonedDateTime

Parse as a ZonedDateTime, a moment as seen through the wall-clock time used by the people of a specific region (a time zone).

```<code>String input = "Mon Jan 01 00:00:00 AEDT 1990";
Locale locale = Locale.US;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , locale );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

System.out.println( "zdt: " + zdt );
</code>```

zdt: 1990-01-01T00:00+11:00[Australia/Sydney]

By the way, your input string is in a terrible format. It uses the 2-4 character pseudo-zones that are not actual time zones, not standardized, and are not unique! Another problem is depending on English. And it is difficult to parse. Educate the people publishing your data about the beauty of the ISO 8601 standard, created for exchanging date-time values as text.

LocalDate

You want only the date. So extract a LocalDate.

```<code>LocalDate ld = zdt.toLocalDate() ;  // Extract only the date, leaving behind the time-of-day and the time zone.
</code>```

Your desired output format has already been defined in the DateTimeFormatter class. The standard ISO 8601 format for a date is YYYY-MM-DD. A variation of that is known as "Basic" meaning it minimizes the use of delimiters: YYYYMMDD.

```<code>String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE ) ;
</code>```

19900101

Body:
tl;dr

Regex is overkill.

Here is a one-liner solution using java.time classes built into Java.

ZonedDateTime                            // Represent a moment as seen through the wall-clock time used by the people of a certain region (a time zone).
.parse(                                  // Parse the input text.
    "Mon Jan 01 00:00:00 AEDT 1990" ,
    DateTimeFormatter.ofPattern(
        "EEE MMM dd HH:mm:ss z uuuu" ,   // Specify a custom formatting pattern to match our input.
        Locale.US                        // Specify a `Locale` for the human language to use in translating the name of month& day-of-week.
    )                                    // Returns a `DateTimeFormatter` object.
)                                        // Returns a `ZonedDateTime` object.
.toLocalDate()                           // Extract the date, without time-of-day and without time zone.
.format(                                 // Generate text to represent the value of our `LocalDate` object.
    DateTimeFormatter.BASIC_ISO_DATE     // Use the predefined formatting pattern YYYYMMDD.
)                                        // Returns a String.

19900101

java.time

Regex is overkill for this.

The modern approach uses java.time classes.

Specify a custom formatting pattern to fit your input.

Specify a locale to facilitate translating the name of day-of-week and name of month.

ZonedDateTime

Parse as a ZonedDateTime, a moment as seen through the wall-clock time used by the people of a specific region (a time zone).

String input = "Mon Jan 01 00:00:00 AEDT 1990";
Locale locale = Locale.US;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , locale );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

System.out.println( "zdt: " + zdt );

zdt: 1990-01-01T00:00+11:00[Australia/Sydney]

By the way, your input string is in a terrible format. It uses the 2-4 character pseudo-zones that are not actual time zones, not standardized, and are not unique! Another problem is depending on English. And it is difficult to parse. Educate the people publishing your data about the beauty of the ISO 8601 standard, created for exchanging date-time values as text.

LocalDate

You want only the date. So extract a LocalDate.

LocalDate ld = zdt.toLocalDate() ;  // Extract only the date, leaving behind the time-of-day and the time zone.

Your desired output format has already been defined in the DateTimeFormatter class. The standard ISO 8601 format for a date is YYYY-MM-DD. A variation of that is known as "Basic" meaning it minimizes the use of delimiters: YYYYMMDD.

String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE ) ;

19900101


问:
Use Python to open PHP file that contains JSON Array
Needing some help on where to start. I have inherited a file called data.php which
consist of an array shaped as follows:

```<code><?php
error_reporting(0);
$items=array (
0 =>
array (
'name' => 'Ted',
'size' => 'Large',
'sleeve' => 'Short',
'color' => 'Red',
),

);
$unObiect->items = $items;
$json = json_encode($unObiect);
echo($json);
?>
</code>```

There are actually about one hundred arrays in the file. I am trying to open the file, search an element of the array
and replace a value. Not concerned about the replace part yet just trying to open the file and loop thru the array. I'm not sure how to actually open the file in Python and loop it. I have tried

```<code>with open("data.php") as raw:
    for items in raw:
        print(items)
</code>```

This opens the file but seems to be reading by line which I expected. How can it be opened and loop thru as an array,
something like

```<code>with open("data.php") as raw:
for items in raw['name']:
       print(items)
</code>```

Where I can get an element of the array without going thru every line and seeing if that line contains 'name' then splitting the line to get to the value after the '=>'.  I guess basically looking to open the file and loop the
array. I know there are other post similar to this but I guess I'm not sure if I'm actually opening a php file as a text file somebody named with php or an actual php file that has an actual json array. Hope this makes sense.

Edit:
From a comment I took suggestion to execute the php from the python. Using the following I was able to do this:

```<code>result = subprocess.run(
['php', 'data.php'],
stdout=subprocess.PIPE,
check=True
)
print(result.stdout)
</code>```

Not sure now what to do with the result.stdout, how to iterate thru it. This returns a byte-string.

答:
You can make the PHP to return the array as json above instead of echo. Then you can make a network request from python scripts to php script using request library like so:

```<code>r = requests.get('route_to_php_file')
    if r.status_code == 200:
        return r.json()
</code>```

You can learn more about python request library: https://2.python-requests.org/en/master/

Body:
Needing some help on where to start. I have inherited a file called data.php which
consist of an array shaped as follows:

<?php
error_reporting(0);
$items=array (
0 =>
array (
'name' => 'Ted',
'size' => 'Large',
'sleeve' => 'Short',
'color' => 'Red',
),

);
$unObiect->items = $items;
$json = json_encode($unObiect);
echo($json);
?>

There are actually about one hundred arrays in the file. I am trying to open the file, search an element of the array
and replace a value. Not concerned about the replace part yet just trying to open the file and loop thru the array. I'm not sure how to actually open the file in Python and loop it. I have tried

with open("data.php") as raw:
    for items in raw:
        print(items)

This opens the file but seems to be reading by line which I expected. How can it be opened and loop thru as an array,
something like

with open("data.php") as raw:
for items in raw['name']:
       print(items)

Where I can get an element of the array without going thru every line and seeing if that line contains 'name' then splitting the line to get to the value after the '=>'.  I guess basically looking to open the file and loop the
array. I know there are other post similar to this but I guess I'm not sure if I'm actually opening a php file as a text file somebody named with php or an actual php file that has an actual json array. Hope this makes sense.

Edit:
From a comment I took suggestion to execute the php from the python. Using the following I was able to do this:

result = subprocess.run(
['php', 'data.php'],
stdout=subprocess.PIPE,
check=True
)
print(result.stdout)

Not sure now what to do with the result.stdout, how to iterate thru it. This returns a byte-string.

Body:
You can make the PHP to return the array as json above instead of echo. Then you can make a network request from python scripts to php script using request library like so:

r = requests.get('route_to_php_file')
    if r.status_code == 200:
        return r.json()

You can learn more about python request library: https://2.python-requests.org/en/master/


问:
Laravel 5.5 - update or create bulk insert
i am trying to preform update or create action on many records using laravel model.
Normal insert with updateOrCreate works perfectly with foreach but i want to avoide it as it slowing things down.
I have something like 200k records.
Is there is any way to achive it?
I tried this answer below
https://stackoverflow.com/a/34815725/1239122
But it is not super elegant.
Any ideas?</p>

答:
You can try this library for batch insert and update.

https://github.com/mavinoo/laravelBatch


问:
Creating Azure storage authorization header using python
I am trying to create the Authorization header for using Azure storage REST APIs. What a nightmare. The reason I am trying to do this is because I am trying to use a workflow builder (Alteryx) to call the API so my only programmatic options are Alteryx, python, or command line.

I think I'm close, but I just don't understand these last three lines of code, following this article - https://learn.microsoft.com/en-us/azure/storage/common/storage-rest-api-auth?toc=%2fazure%2fstorage%2fblobs%2ftoc.json

// Now turn it into a byte array.
byte[] SignatureBytes = Encoding.UTF8.GetBytes(MessageSignature);

// Create the HMACSHA256 version of the storage key.
HMACSHA256 SHA256 = new HMACSHA256(Convert.FromBase64String(storageAccountKey));

// Compute the hash of the SignatureBytes and convert it to a base64 string.
string signature = Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));

So if I follow this correctly, I have to create a SHA256 version of the storage key but then I make a SHA256 hash of the SHA256 hash of the signaturebytes?

I'm current googling and not getting far, but basically trying to do the same thing above in .net using python.

答:
In python, you can just use this line of code:

```<code>signed_string = base64.b64encode(hmac.new(base64.b64decode(storage_account_key), msg=string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest()).decode()
</code>```

Here is the complete code of using List blobs api:

```<code>import requests
import datetime
import hmac
import hashlib
import base64

storage_account_name = 'xx'
storage_account_key = 'xxx'
container_name='aa1'
api_version = '2017-07-29'
request_time = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')

string_params = {
    'verb': 'GET',
    'Content-Encoding': '',
    'Content-Language': '',
    'Content-Length': '',
    'Content-MD5': '',
    'Content-Type': '',
    'Date': '',
    'If-Modified-Since': '',
    'If-Match': '',
    'If-None-Match': '',
    'If-Unmodified-Since': '',
    'Range': '',
    'CanonicalizedHeaders': 'x-ms-date:' + request_time + '\nx-ms-version:' + api_version + '\n',
    'CanonicalizedResource': '/' + storage_account_name +'/'+container_name+ '\ncomp:list\nrestype:container'
}

string_to_sign = (string_params['verb'] + '\n'
                  + string_params['Content-Encoding'] + '\n'
                  + string_params['Content-Language'] + '\n'
                  + string_params['Content-Length'] + '\n'
                  + string_params['Content-MD5'] + '\n'
                  + string_params['Content-Type'] + '\n'
                  + string_params['Date'] + '\n'
                  + string_params['If-Modified-Since'] + '\n'
                  + string_params['If-Match'] + '\n'
                  + string_params['If-None-Match'] + '\n'
                  + string_params['If-Unmodified-Since'] + '\n'
                  + string_params['Range'] + '\n'
                  + string_params['CanonicalizedHeaders']
                  + string_params['CanonicalizedResource'])

signed_string = base64.b64encode(hmac.new(base64.b64decode(storage_account_key), msg=string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest()).decode()

headers = {
    'x-ms-date' : request_time,
    'x-ms-version' : api_version,
    'Authorization' : ('SharedKey ' + storage_account_name + ':' + signed_string)
}

url = ('https://' + storage_account_name + '.blob.core.windows.net/'+container_name+'?restype=container&comp=list')

r = requests.get(url, headers = headers)
print(r.status_code)
print('\n\n'+r.text)
</code>```

Test result:

Body:
In python, you can just use this line of code:

signed_string = base64.b64encode(hmac.new(base64.b64decode(storage_account_key), msg=string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest()).decode()

Here is the complete code of using List blobs api:

import requests
import datetime
import hmac
import hashlib
import base64

storage_account_name = 'xx'
storage_account_key = 'xxx'
container_name='aa1'
api_version = '2017-07-29'
request_time = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')

string_params = {
    'verb': 'GET',
    'Content-Encoding': '',
    'Content-Language': '',
    'Content-Length': '',
    'Content-MD5': '',
    'Content-Type': '',
    'Date': '',
    'If-Modified-Since': '',
    'If-Match': '',
    'If-None-Match': '',
    'If-Unmodified-Since': '',
    'Range': '',
    'CanonicalizedHeaders': 'x-ms-date:' + request_time + '\nx-ms-version:' + api_version + '\n',
    'CanonicalizedResource': '/' + storage_account_name +'/'+container_name+ '\ncomp:list\nrestype:container'
}

string_to_sign = (string_params['verb'] + '\n'
                  + string_params['Content-Encoding'] + '\n'
                  + string_params['Content-Language'] + '\n'
                  + string_params['Content-Length'] + '\n'
                  + string_params['Content-MD5'] + '\n'
                  + string_params['Content-Type'] + '\n'
                  + string_params['Date'] + '\n'
                  + string_params['If-Modified-Since'] + '\n'
                  + string_params['If-Match'] + '\n'
                  + string_params['If-None-Match'] + '\n'
                  + string_params['If-Unmodified-Since'] + '\n'
                  + string_params['Range'] + '\n'
                  + string_params['CanonicalizedHeaders']
                  + string_params['CanonicalizedResource'])

signed_string = base64.b64encode(hmac.new(base64.b64decode(storage_account_key), msg=string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest()).decode()

headers = {
    'x-ms-date' : request_time,
    'x-ms-version' : api_version,
    'Authorization' : ('SharedKey ' + storage_account_name + ':' + signed_string)
}

url = ('https://' + storage_account_name + '.blob.core.windows.net/'+container_name+'?restype=container&comp=list')

r = requests.get(url, headers = headers)
print(r.status_code)
print('\n\n'+r.text)

Test result:


问:
Unknown xx req signal for NoC coding
I am having unknown xx for req[1:0] signal in a NoC verilog code implementation

Please advise.

答:
Problem solved.

https://gist.github.com/promach/cf3ae626a85badad6cd822d3107c86b7/revisions#diff-7d0a6c3024f080f56a53770135bf21ab

Just change

```<code>(.clk(clk), .reset(reset), .req(req[granted_port]), .grant(granted_vc));
</code>```

to

```<code>(.clk(clk), .reset(reset), .req(req[granted_port_index]), .grant(granted_vc));
</code>```

Title: Unknown xx req signal for NoC coding

Body:
Problem solved.

https://gist.github.com/promach/cf3ae626a85badad6cd822d3107c86b7/revisions#diff-7d0a6c3024f080f56a53770135bf21ab

Just change

(.clk(clk), .reset(reset), .req(req[granted_port]), .grant(granted_vc));

to

(.clk(clk), .reset(reset), .req(req[granted_port_index]), .grant(granted_vc));


问:
How to bind a variable at the start of URL on cURL, it is throwing error
```<code>curl \ -H "Content-Type: application/json" \ -X POST \ $REPOSITORY_URL/engine-rest
</code>```

http://10.195.177.141:31406 is bound to REPOSITORY_URL.

```<code>curl: no URL specified! curl: try 'curl --help' or 'curl --manual' for more information
</code>```

I tried giving double quotes as well

答:
TL;DR:  Remove \ and try again.

Try this:

```<code>curl  -H "Content-Type: application/json"  -X POST  $REPOSITORY_URL/engine-rest
</code>```

To me, it appears as if the \ characters in the command line are superfluous.  They are telling bash to treat the space as part of the parameter  value instead of a separator.  With that in mind, the first argument you are passing to curl is " -H" (that is, :space:-H).  Since this argument doesn't start with a -, the program assumes that it is the URL.  curl performs a DNS lookup on -H and cannot resolve that host name:

```<code>curl: (6) Could not resolve host:  -H
</code>```

I suspect the reason why I have a different error than you is because I am using curl on MacOS.

Body:
curl \ -H "Content-Type: application/json" \ -X POST \ $REPOSITORY_URL/engine-rest

http://10.195.177.141:31406 is bound to REPOSITORY_URL.

curl: no URL specified! curl: try 'curl --help' or 'curl --manual' for more information

I tried giving double quotes as well

Body:
TL;DR:  Remove \ and try again.

Try this:

curl  -H "Content-Type: application/json"  -X POST  $REPOSITORY_URL/engine-rest

To me, it appears as if the \ characters in the command line are superfluous.  They are telling bash to treat the space as part of the parameter  value instead of a separator.  With that in mind, the first argument you are passing to curl is " -H" (that is, :space:-H).  Since this argument doesn't start with a -, the program assumes that it is the URL.  curl performs a DNS lookup on -H and cannot resolve that host name:

curl: (6) Could not resolve host:  -H

I suspect the reason why I have a different error than you is because I am using curl on MacOS.


问:
How can I set drop down values from JSON file
I am new to selectize and I would like to set the drop down list options of the tag input from a JSON file, right now the drop down shows what is on the input value.    </p>

```<code>{"California":["Los Angeles","San Diego","San Jose","San Francisco","Fresno","Sacramento"]}

<input type="text" id="myCity" class="form-control mb-4" placeholder="City" value="San Diego, San Francisco">

<script class="show">
$('#myCity').selectize({
                        delimiter: ',',
                        persist: false,
                        maxItems: 5,
                        plugins: ['remove_button'],
    create: function(input) {
return {
value: input,
text: input
                            }
                        }
                    });
</script>
</code>```

答:
I finally found a way around this</p>

```<code>var data = ["Los Angeles", "San Diego", "San Jose", "San Francisco", "Fresno", "Sacramento"];
    var cities = data.map(function(x) { return { city: x }; });
                $('#input-tags').selectize({
                    delimiter: ',',
                    persist: false,
                    maxItems: 5,
                    plugins: ['remove_button'],
                     valueField: 'city',
            labelField: 'city',
            searchField: 'city',
            options: cities,
            create:true,
            render: {
                option: function(item, escape) {

                    return '<div>' +
                            '<span class="name">' + escape(item.city) + '</span>' +
'</div>';

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

Body:
I am new to selectize and I would like to set the drop down list options of the tag input from a JSON file, right now the drop down shows what is on the input value.

{"California":["Los Angeles","San Diego","San Jose","San Francisco","Fresno","Sacramento"]}

<input type="text" id="myCity" class="form-control mb-4" placeholder="City" value="San Diego, San Francisco">

Body:
I finally found a way around this

var data = ["Los Angeles", "San Diego", "San Jose", "San Francisco", "Fresno", "Sacramento"];
    var cities = data.map(function(x) { return { city: x }; });
                $('#input-tags').selectize({
                    delimiter: ',',
                    persist: false,
                    maxItems: 5,
                    plugins: ['remove_button'],
                     valueField: 'city',
            labelField: 'city',
            searchField: 'city',
            options: cities,
            create:true,
            render: {
                option: function(item, escape) {

                    return '<div>' +
                            '<span class="name">' + escape(item.city) + '</span>' +
'</div>';

}
}
                    });


答:
Check if something like this helps

```<code>//date string
String soTime = "Mon Jan 04 12:30:23 AEDT 1990";

//Format
SimpleDateFormat so = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

SimpleDateFormat desiredFormat = new SimpleDateFormat("yyyyMMdd");
desiredFormat.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));

Date sodate = so.parse(soTime);
System.out.println("DAY : " + desiredFormat.format(sodate));
</code>```

Parse date with AEDT and AEST time zone in java

Title: How to convert this string "Mon Jan 01 00:00:00 AEDT 1990" into "1990101"?

Body:
I have a string "Mon Jan 01 00:00:00 AEDT 1990" and I need to convert it into the format "yyyyMMdd" so in this case it would be "19900101".

I think it's possible to do this with Regular Expressions so that I could pull out the year, month(but would need to convert Jan to 01 and etc) and day from the string but I am not well versed in Regular Expressions. Anyone have any ideas?

Body:
Check if something like this helps

//date string
String soTime = "Mon Jan 04 12:30:23 AEDT 1990";

//Format
SimpleDateFormat so = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

SimpleDateFormat desiredFormat = new SimpleDateFormat("yyyyMMdd");
desiredFormat.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));

Date sodate = so.parse(soTime);
System.out.println("DAY : " + desiredFormat.format(sodate));

Parse date with AEDT and AEST time zone in java


问:
Problem running PHP temperature converter
I've been trying to work a simple form-based temperature converter, but I'm currently getting a white screen, and I cannot see what is wrong with the code. In addition, any ideas / suggestions for best practice are most welcome!</p>

```<code><?php // convert.php

if (isset($_POST['temperature']))
    $temp = sanitize_string($_POST['temperature']);

if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah')
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    elseif ($_POST['scale'] == 'cel')
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    else
        $output = '';
}
?>

<html>

<head>
    <title>Temperature converter</title>
</head>

<body>
    <?php
    if (isset($_POST['submitted']) and isset($conv))
    {
        if ($conv == 'fah')
            print("$temp degrees Fahrenheit is $output degrees Celcius");
        elseif ($conv == 'cel')
            print("$temp degrees Celcius is $output degrees Fahrenheit");
    }
    ?>

<form method="post" action="convert.php">
    <label>Temperature <input type="text" name="temperature"></label>
    <label>Celcius <input type="radio" name="scale" value="cel"></label>
    <label>Fahrenheit <input type="radio" name="scale" value="fah"></label>
    <input type="hidden" name="submitted" value="yes">
    <input type="submit">
</form>
</body>

</html>

<?php
print_r($_POST);

function sanitize_string($var)
{
    $var = stripslashes($var);
    $var = htmlentities($var);
    $var = strip_tags($var);
    return $var;
}
?>
</code>```

答:
Your $conv variable is only visible inside those if-statements. Add its declaration right on top:

```<code><?php
$conv = null;
// your code
</code>```

And then check if (isset($_POST['submitted']) && $conv !== null)

Edit: As @halfdan said, you are missing curly braces since you want to execute more than one statement in the if-else-clauses.

ContentLicense: CC BY-SA 3.0

Body:
I've been trying to work a simple form-based temperature converter, but I'm currently getting a white screen, and I cannot see what is wrong with the code. In addition, any ideas / suggestions for best practice are most welcome!

<?php // convert.php

if (isset($_POST['temperature']))
    $temp = sanitize_string($_POST['temperature']);

if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah')
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    elseif ($_POST['scale'] == 'cel')
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    else
        $output = '';
}
?>

    <title>Temperature converter</title>

    <?php
    if (isset($_POST['submitted']) and isset($conv))
    {
        if ($conv == 'fah')
            print("$temp degrees Fahrenheit is $output degrees Celcius");
        elseif ($conv == 'cel')
            print("$temp degrees Celcius is $output degrees Fahrenheit");
    }
    ?>

<form method="post" action="convert.php">
    Temperature <input type="text" name="temperature">
    Celcius <input type="radio" name="scale" value="cel">
    Fahrenheit <input type="radio" name="scale" value="fah">
    <input type="hidden" name="submitted" value="yes">
    <input type="submit">
</form>

<?php
print_r($_POST);

function sanitize_string($var)
{
    $var = stripslashes($var);
    $var = htmlentities($var);
    $var = strip_tags($var);
    return $var;
}
?>

Body:
Your $conv variable is only visible inside those if-statements. Add its declaration right on top:

<?php
$conv = null;
// your code

And then check if (isset($_POST['submitted']) && $conv !== null)

Edit: As @halfdan said, you are missing curly braces since you want to execute more than one statement in the if-else-clauses.


问:
The score is not updating. Can you please tell me what is wrong with the code?
The score is not updating. Please help me make the score update.
When I click the button with the function for 'addScore', the displayed score will not change to a new one.

I have tried a lot of things. Non of which have worked

var score = 0;

function addScore(){ score ++ }

function drawScore() {
 var c = document.getElementById("myCanvas");
 var ctx = c.getContext("2d");
 ctx.font = "16px Arial";
 ctx.fillStyle = "red";
 ctx.fillText("Score: " +score, 8, 20);
}

drawScore();
```

I am expecting it to update the score, but it does not. It remains at 0.

The problem has been solved bu the text keeps increasing and over laps it.

答:
The canvas does not maintain a reference to your variable (or any values for that matter). Canvas is like an image, it does not have a DOM. You will need to call drawScore() again and maybe clear that portion of the canvas before drawing.

```<code>function addScore(){
    score++;
    drawScore();
}
</code>```

Demo

Body:
The score is not updating. Please help me make the score update.
When I click the button with the function for 'addScore', the displayed score will not change to a new one.

I have tried a lot of things. Non of which have worked

var score = 0;

function addScore(){ score ++ }

function drawScore() {
 var c = document.getElementById("myCanvas");
 var ctx = c.getContext("2d");
 ctx.font = "16px Arial";
 ctx.fillStyle = "red";
 ctx.fillText("Score: " +score, 8, 20);
}

drawScore();

I am expecting it to update the score, but it does not. It remains at 0.

The problem has been solved bu the text keeps increasing and over laps it.

Body:
The canvas does not maintain a reference to your variable (or any values for that matter). Canvas is like an image, it does not have a DOM. You will need to call drawScore() again and maybe clear that portion of the canvas before drawing.

function addScore(){
    score++;
    drawScore();
}

Demo


问:
Api Gateway and Regional Custom Domain as CloudFront Origin
I want to create an API Gateway with a Regional Custom Domain and use that as a CloudFront Distribution Origin. My main motivation is to control MinimumProtocolVersion/TLS1.2

My question is if the custom domain name for the regional custom domain must match the domain name of the CloudFront distribution,- or If I can separate domain names.

My team has experienced 403 errors from CF when there is a mismatch, I'm just double checking if this is doable at all

Example:

```<code>ApiGW:
  - Custom Domain Name (REGIONAL). For example www.sample.com (
  - matching ACM certificate in eu-west-1
  - No R53 records referencing this domain name

Cloudfront:
  -  ACM certificate in us-east-1
  -  Alias www.example.com
  -  Origin; www.sample.com
  -  R53 recrod for www.example.com, in hosted zone example.com mapped to the CF disitribution domain name
</code>```

答:
When CloudFront makes a connection to the origin, it always uses the Origin Domain Name to look up the origin's IP address... but when it negitiates TLS with the origin, it sets the SNI to the same value as the HTTP Host header it will be sending to the origin.

These two values may be the same, or they may differ, but Host/SNI are always the same as each other, and always one of two values:

it's the Origin Domain Name (potentially modified in the custom origin parameters by a Lambda@Edge Origin Request trigger), when the Cache Behavior settings do not include whitelisting the Host header (or all headers) for forwarding to the origin, or

it's the HTTP Host header sent to CloudFront by the browser (potentially modified in the request headers by a Lambda@Edge Request trigger), when the Cache Behavior settings do include whitelisting the Host header for forwarding to the origin.

So, in essence, the name needs to match if the Host header is forwarded, and must be different if it is not.

Additionally, if it is different, that hostname must actually be configured in DNS and pointing to the assigned regional API endpoint -- you can't just point to the assigned DNS alias target as Origin Domain Name.

Unfortunately, there are a few cases where CloudFront is somewhat confusing in its use of 403 errors.  Sometimes this code is used for errors that would more correctly be treated as 400 or 421 errors, so the response body is important when checking into certain problems with 403.  If you point a domain name to CloudFront without setting that domain as an Alternate Domain Name for the distribution, you'll get a 403 with a body that says "Bad Request" and the event won't be logged in your CloudFront logs because the missing Alternate Domain Name setting prevents CloudFront from mapping that request to your specific distribution.

Body:
I want to create an API Gateway with a Regional Custom Domain and use that as a CloudFront Distribution Origin. My main motivation is to control MinimumProtocolVersion/TLS1.2

My question is if the custom domain name for the regional custom domain must match the domain name of the CloudFront distribution,- or If I can separate domain names.

My team has experienced 403 errors from CF when there is a mismatch, I'm just double checking if this is doable at all

Example:

ApiGW:
  - Custom Domain Name (REGIONAL). For example www.sample.com (
  - matching ACM certificate in eu-west-1
  - No R53 records referencing this domain name

Cloudfront:
  -  ACM certificate in us-east-1
  -  Alias www.example.com
  -  Origin; www.sample.com
  -  R53 recrod for www.example.com, in hosted zone example.com mapped to the CF disitribution domain name


问:
What happens on the stack when one value shadows another in Rust?
I am reading Mastering Rust. There is an exercise at the end of the first chapter where sample code is provided, and the task is to fix it, iterating by using the generally quite helpful compiler error messages.

I was expecting that the following was an error but it is not:

for line in reader.lines() {
    let line = line.expect("Could not read line.");
```

<p>For complete context, I have the entire code in a gist. That's the code after I fixed things, and the relevant rows are 37 & 38. However it requires feeding a text file as an argument.</p>

<hr>

<p>I was expecting an error because <code>line</code> is on the stack (at least the pointer is). Is it right that it can still be <em>destroyed and replaced</em> with no complaint?</p>

<p>What happens under the hood regarding memory management and the stack? I <em>presume</em> that <code>line</code> is actually a reference to a string (a <code>&str</code> type). So, then, this is fine because in either case, the pointer itself - the object on the stack - is just a <code>usize</code>, so that both <code>line</code> objects are of the same size on the stack. </p>

<p>Can I do this with something of a different size? Could the second line have said:</p>

<pre class="lang-rust prettyprint-override"><code>let line: f64 = 3.42;
</code>```

In this case, the object itself is on the stack, and it is potentially larger than usize.

答:
Whenever a variable is declared with let, it's an entirely new variable, separate from anything before it. Even if a variable with the same name already exists, the original variable is shadowed while the new variable is in scope. If a variable is shadowed, it's normally inaccessible.

It's possible to access the value of the old variable in situations where the old variable is still in scope after the new variable falls out of scope, or if the old variable has a Drop implementation.

We can see this in action in the following example.

```<code>#[derive(Debug)]
struct DroppedU32(u32);

impl Drop for DroppedU32 {
    fn drop(&mut self) {
        eprintln!("Dropping u32: {}", self.0);
    }
}

fn main() {
    let x = 5;
    dbg!(&x); // the original value
    {
        let x = 7;
        dbg!(&x); // the new value
    }
    dbg!(&x); // the original value again

    let y = DroppedU32(5);
    dbg!(&y); // the original value
    let y = DroppedU32(7);
    dbg!(&y); // the new value

    // down here, when the variables are dropped in
    // reverse order of declaration,
    // the original value is accessed again in the `Drop` impl.
}
</code>```

(playground)

That's not to say that the original variable is guaranteed to still exist. Compiler optimizations can cause the original variable to be overwritten, especially if the original variable isn't accessed again.

The code

```<code>pub fn add_three(x: u32, y: u32, z: u32) -> u32 {
    let x = x + y;
    let x = x + z;
    x
}
</code>```

compiles to

```<code>example::add_three:
        lea     eax, [rdi + rsi]
        add     eax, edx
        ret
</code>```

If you're like me and aren't too familiar with assembler code, this basically

Adds x and y and puts the result in a variable (call it w).

Adds z to w and overwrites w with the result.

Returns w.

So (besides the input parameters), there's only one variable used, even though we used let x = ... twice. The intermediate result let x = x + y; gets overwritten.

Body:
I am reading Mastering Rust. There is an exercise at the end of the first chapter where sample code is provided, and the task is to fix it, iterating by using the generally quite helpful compiler error messages.

I was expecting that the following was an error but it is not:

for line in reader.lines() {
    let line = line.expect("Could not read line.");

For complete context, I have the entire code in a gist. That's the code after I fixed things, and the relevant rows are 37 & 38. However it requires feeding a text file as an argument.

I was expecting an error because line is on the stack (at least the pointer is). Is it right that it can still be destroyed and replaced with no complaint?

What happens under the hood regarding memory management and the stack? I presume that line is actually a reference to a string (a &str type). So, then, this is fine because in either case, the pointer itself - the object on the stack - is just a usize, so that both line objects are of the same size on the stack.

Can I do this with something of a different size? Could the second line have said:

let line: f64 = 3.42;

In this case, the object itself is on the stack, and it is potentially larger than usize.

Body:
Whenever a variable is declared with let, it's an entirely new variable, separate from anything before it. Even if a variable with the same name already exists, the original variable is shadowed while the new variable is in scope. If a variable is shadowed, it's normally inaccessible.

It's possible to access the value of the old variable in situations where the old variable is still in scope after the new variable falls out of scope, or if the old variable has a Drop implementation.

We can see this in action in the following example.

#[derive(Debug)]
struct DroppedU32(u32);

impl Drop for DroppedU32 {
    fn drop(&mut self) {
        eprintln!("Dropping u32: {}", self.0);
    }
}

fn main() {
    let x = 5;
    dbg!(&x); // the original value
    {
        let x = 7;
        dbg!(&x); // the new value
    }
    dbg!(&x); // the original value again

    let y = DroppedU32(5);
    dbg!(&y); // the original value
    let y = DroppedU32(7);
    dbg!(&y); // the new value

    // down here, when the variables are dropped in
    // reverse order of declaration,
    // the original value is accessed again in the `Drop` impl.
}

(playground)

That's not to say that the original variable is guaranteed to still exist. Compiler optimizations can cause the original variable to be overwritten, especially if the original variable isn't accessed again.

The code

pub fn add_three(x: u32, y: u32, z: u32) -> u32 {
    let x = x + y;
    let x = x + z;
    x
}

compiles to

example::add_three:
        lea     eax, [rdi + rsi]
        add     eax, edx
        ret

If you're like me and aren't too familiar with assembler code, this basically

Adds x and y and puts the result in a variable (call it w).

Adds z to w and overwrites w with the result.

Returns w.

So (besides the input parameters), there's only one variable used, even though we used let x = ... twice. The intermediate result let x = x + y; gets overwritten.


问:
QFont::setPointSize: Point size <= 0 (-1), must be greater than 0
I did a mainwindow.ui file converted into Ui_mainwindow.py (pyuic4).
Next I used the class from this .py file like this:

```<code>class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent = None):
        super(MainWindow,self).__init__(parent)
        self.setupUi(self)
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MainWindow()
    myapp.show()
    sys.exit(app.exec_())
</code>```

When I run the code in ipython, the following message appeared:
QFont::setPointSize: Point size <= 0 (-1), must be greater than 0

Here the .ui link:
mainwindow.ui
Here the .py from .ui link:
Ui_mainwindow.py

ipython terminal remain in bug state even if the app works.
When I quit app (No error or warnings), ipython is still in this state.

Here the link picture bug:ipython bug

Could someone explain me how to avoid it?

答:
You can remove the <pointsize>-1</pointsize> tag from the font tag in your .ui file to prevent this error.

Beware that this will make QT Creator/Designer not load the font attribute, so name the file without the pointsizes something different.

Body:
I did a mainwindow.ui file converted into Ui_mainwindow.py (pyuic4).
Next I used the class from this .py file like this:

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent = None):
        super(MainWindow,self).__init__(parent)
        self.setupUi(self)
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MainWindow()
    myapp.show()
    sys.exit(app.exec_())

When I run the code in ipython, the following message appeared:
QFont::setPointSize: Point size <= 0 (-1), must be greater than 0

Here the .ui link:
mainwindow.ui
Here the .py from .ui link:
Ui_mainwindow.py

ipython terminal remain in bug state even if the app works.
When I quit app (No error or warnings), ipython is still in this state.

Here the link picture bug:ipython bug

Could someone explain me how to avoid it?


问:
LinqDataSource DataContext Object Not Showing In Configure Data Source
I added a LinqToSQL Class to my project and put it in my App_code folder.

I then added a LinqDataSource to a new web page and tried to configure it to use this class, but it does not show up as an option in the DataContext drop down.

I moved the class to the root directory of my project and it is now available in the DataContext drop down box.

I created a new project with 1 page and tried it again and still the same thing.  If the class isn't in my root directory it isn't available.

I have searched the internet and everything I have found indicates that the class should be in my App_code folder, but it doesn't work if I put it there.

Does anyone know why the class isn't available if I put it in the App_code folder.

Thank You

答:
Open your .dbml file in VS2010 and make sure that it only has the tables in it that are related to what you are doing with the .dbml file.  I opened my to discover I had taken 3 tables when all I needed was one.

After you have done this, in solution explorer find your .dbml file, and expand it.

There should be two files inside the expansion:

<name-of-your-dbml-file>.dbml.layout, and

<name-of-your-dbml-file>.designer.cs

Double-click <name-of-your-dbml-file>.designer.cs to open it.

Take note of the namespace in this file.

Open the code-behind page of the web page (.aspx or .ascx file).

Click Source, and add using <the-name-space-from-step-four>

Go back to the web page's (not the code-behind) Design view.

Click your LinqDataSource

Click the little arrow to reveal the LINQDataSource Tasks, and click Configure Data Source...

Be sure that Show only DataContext objects is unchecked.

From the Choose your context object: dropdown look for the namespace we noted in step 4.

From there you should be able to select your DataContext class and click next.

ContentLicense: CC BY-SA 2.5


问:
Vectorizable FIND function with if statement MATLAB
I have a matrix u, I want to go across all rows and all columns and do the following. If the element is non zero, I return the value of the row index. If the element is zero, find the row index the next non zero element after this element. I can do this easily using two for loops with a find function. But I need to do this many many times (not because of the size of the matrix but because this is called many times). How can I do it faster?

here is the for loop code:

```<code>     for w=scenario_size:-1:1
            for t=1:time_size
                l = u(t,w) ;
                if l~=0
                    tprime = t ;
                else
                    tprime = t+ find(u(t:end,w),1,'first') -1 ;
                end
                i(t,w)       = tprime ;
                boo(t,w)     = number(tprime,w)/u(tprime,w) ;
            end
end
</code>```

Example if one column is [0,0,5,1,0,3], the i is [3,3,3,4,6,6]. The last element of any column of u is always non-zero (I forced this by artificially adding a row of ones at the end).

Then boo is the corresponding entry to tprime for some matrix number divided by the corresponding u (which is non zero by construction).

Body:
I have a matrix u, I want to go across all rows and all columns and do the following. If the element is non zero, I return the value of the row index. If the element is zero, find the row index the next non zero element after this element. I can do this easily using two for loops with a find function. But I need to do this many many times (not because of the size of the matrix but because this is called many times). How can I do it faster?

here is the for loop code:

     for w=scenario_size:-1:1
            for t=1:time_size
                l = u(t,w) ;
                if l~=0
                    tprime = t ;
                else
                    tprime = t+ find(u(t:end,w),1,'first') -1 ;
                end
                i(t,w)       = tprime ;
                boo(t,w)     = number(tprime,w)/u(tprime,w) ;
            end
end

Example if one column is [0,0,5,1,0,3], the i is [3,3,3,4,6,6]. The last element of any column of u is always non-zero (I forced this by artificially adding a row of ones at the end).

Then boo is the corresponding entry to tprime for some matrix number divided by the corresponding u (which is non zero by construction).

Body:
@gnovice answer is good, just to give an alternative to find function

First the u matrix

    >> u = randi([0 1], 10);
    u(end, :) = 1;
    >> u

    u =

         0     0     0     0     0     1     1     0     0     0
         0     1     1     1     0     1     0     1     1     1
         1     1     1     0     1     0     0     1     1     0
         1     1     1     1     1     0     1     1     0     1
         1     1     0     1     1     1     1     0     0     0
         0     0     1     0     1     1     1     0     0     1
         0     1     0     0     1     1     0     0     0     1
         0     1     0     1     1     1     0     1     1     0
         0     0     0     1     0     1     1     1     1     1
         1     1     1     1     1     1     1     1     1     1

Then the non-zeros row indices can be computed as follow

    >> t = 1:10*10;% All elements indices
    r = t(u ~= 0); % All non-zeros elements indices
    >> r

    r =

      Columns 1 through 18

         3     4     5    10    12    13    14    15    17    18    20    22    23    24    26    30    32    34

      Columns 19 through 36

        35    38    39    40    43    44    45    46    47    48    50    51    52    55    56    57    58    59

      Columns 37 through 54

        60    61    64    65    66    69    70    72    73    74    78    79    80    82    83    88    89    90

      Columns 55 through 60

        92    94    96    97    99   100


问:
TNS:could not resolve the connect identifier specified error
I am trying to connect to a database using cx_Oracle in Python.
this is the way I'm doing it :

```<code>connection = cx_Oracle.connect("user", "pass", "service")
</code>```

I am able to connect to the db using sql developer with the same credentials but when I try to connect from python it throws the error :

ORA-12154: TNS:could not resolve the connect identifier
  specified.

I tried the same thing from another system and I am able to connect to the database using cx_Oracle. The contents of TNSNames.ora file are exactly the same in both systems.

I removed everything and installed again hoping to get rid of mistakes I might have done the first time but I am still facing the same error.

Please let me know if there is any way to fix this.

Thank You.

答: You can try with EZ connect instead, or you can use cx_Oracle.makedsn() to build up the connect string. If you provide the contents of your tnsnames.ora file I can provide a more detailed answer.

Body:
I am trying to connect to a database using cx_Oracle in Python.
this is the way I'm doing it :

connection = cx_Oracle.connect("user", "pass", "service")

I am able to connect to the db using sql developer with the same credentials but when I try to connect from python it throws the error :

ORA-12154: TNS:could not resolve the connect identifier
  specified.

I tried the same thing from another system and I am able to connect to the database using cx_Oracle. The contents of TNSNames.ora file are exactly the same in both systems.

I removed everything and installed again hoping to get rid of mistakes I might have done the first time but I am still facing the same error.

Please let me know if there is any way to fix this.

Thank You.


问:
Is std::push_back relatively expensive to use?
I want to improve the performance of the following code. What aspect might affect the performance of the code when it's executed?

Also, considering that there is no limit to how many objects you can add to the container, what improvements could be made to “Object” or “addToContainer” to improve the performance of the program?

I was wondering if std::push_back in C++ affects performance of the code in any way? Especially if there is no limit to adding to list.

```<code>struct Object{
    string name;
    string description;
};

vector<Object> container;
void addToContainer(Object object) {
    container.push_back(object);
}

int main() {
    addToContainer({ "Fira", "+5 ATTACK" });
    addToContainer({ "Potion", "+10 HP" });
}
</code>```

答:
Before you do ANYTHING profile the code and get a benchmark. After you make a change profile the code and get a benchmark. Compare the benchmarks. If you do not do this, you're rolling dice. Is it faster? Who knows.

Profile profile profile.

With push_back you have two main concerns:

Resizing the vector when it fills up, and

Copying the object into the vector.

There are a number of improvements you can make to the resizing cost cost of push_back depending on how items are being added.

Strategic use of reserve to minimize the amount of resizing, for example. If you know how many items are about to be added, you can check the capacity and size to see if it's worth your time to reserve to avoid multiple resizes. Note this requires knowledge of vector's expansion strategy and that is implementation-specific. An optimization for one vector implementation could be a terribly bad mistake on another.

You can use insert to add multiple items at a time. Of course this is close to useless if you need to add another container into the code in order to bulk-insert.

If you have no idea how many items are incoming, you might as well let vector do its job and optimize HOW the items are added.

For example

```<code>void addToContainer(Object object) // pass by value. Possible copy
{
    container.push_back(object); // copy
}
</code>```

Those copies can be expensive. Get rid of them.

```<code>void addToContainer(Object && object) //no copy and can still handle temporaries
{
    container.push_back(std::move(object)); // moves rather than copies
}
</code>```

std::string is often very cheap to move.

This variant of addToContainer can be used with

```<code>addToContainer({ "Fira", "+5 ATTACK" });
addToContainer({ "Potion", "+10 HP" });
</code>```

and might just migrate a pointer and as few book-keeping variables per string. They are temporaries, so no one cares if it will rips their guts out and throws away the corpses.

As for existing Objects

```<code>Object o{"Pizza pop", "+5 food"};
addToContainer(std::move(o));
</code>```

If they are expendable, they get moved as well. If they aren't expendable...

```<code>void addToContainer(const Object & object) // no copy
{
    container.push_back(object); // copy
}
</code>```

You have an overload that does it the hard way.

Tossing this one out there

If you already have a number of items you know are going to be in the list, rather than appending them all one at a time, use an initialization list:

```<code>vector<Object> container{
    {"Vorpal Cheese Grater", "Many little pieces"},
    {"Holy Hand Grenade", "OMG Damage"}
};
</code>```

Body:
I want to improve the performance of the following code. What aspect might affect the performance of the code when it's executed?

Also, considering that there is no limit to how many objects you can add to the container, what improvements could be made to “Object” or “addToContainer” to improve the performance of the program?

I was wondering if std::push_back in C++ affects performance of the code in any way? Especially if there is no limit to adding to list.

struct Object{
    string name;
    string description;
};

vector<Object> container;
void addToContainer(Object object) {
    container.push_back(object);
}

int main() {
    addToContainer({ "Fira", "+5 ATTACK" });
    addToContainer({ "Potion", "+10 HP" });
}

Body:
Before you do ANYTHING profile the code and get a benchmark. After you make a change profile the code and get a benchmark. Compare the benchmarks. If you do not do this, you're rolling dice. Is it faster? Who knows.

Profile profile profile.

With push_back you have two main concerns:

Resizing the vector when it fills up, and

Copying the object into the vector.

There are a number of improvements you can make to the resizing cost cost of push_back depending on how items are being added.

Strategic use of reserve to minimize the amount of resizing, for example. If you know how many items are about to be added, you can check the capacity and size to see if it's worth your time to reserve to avoid multiple resizes. Note this requires knowledge of vector's expansion strategy and that is implementation-specific. An optimization for one vector implementation could be a terribly bad mistake on another.

You can use insert to add multiple items at a time. Of course this is close to useless if you need to add another container into the code in order to bulk-insert.

If you have no idea how many items are incoming, you might as well let vector do its job and optimize HOW the items are added.

For example

void addToContainer(Object object) // pass by value. Possible copy
{
    container.push_back(object); // copy
}

Those copies can be expensive. Get rid of them.

void addToContainer(Object && object) //no copy and can still handle temporaries
{
    container.push_back(std::move(object)); // moves rather than copies
}

std::string is often very cheap to move.

This variant of addToContainer can be used with

addToContainer({ "Fira", "+5 ATTACK" });
addToContainer({ "Potion", "+10 HP" });

and might just migrate a pointer and as few book-keeping variables per string. They are temporaries, so no one cares if it will rips their guts out and throws away the corpses.

As for existing Objects

Object o{"Pizza pop", "+5 food"};
addToContainer(std::move(o));

If they are expendable, they get moved as well. If they aren't expendable...

void addToContainer(const Object & object) // no copy
{
    container.push_back(object); // copy
}

You have an overload that does it the hard way.

Tossing this one out there

If you already have a number of items you know are going to be in the list, rather than appending them all one at a time, use an initialization list:

vector<Object> container{
    {"Vorpal Cheese Grater", "Many little pieces"},
    {"Holy Hand Grenade", "OMG Damage"}
};


问:
MPLABX Project stopped compiling when I changed of computer
I'm writing firmware for a PIC18F4550 using the MPLABX and the XC8 compiler. The project was compiling with some warnings, but I was able to compile and use the hexa file to simulate. So I decided to advance the work at home. I zipped the folder where the MPLABX project was and sent it by email. When I got home, I downloaded it. I installed the MPLABX and the XC8 compiler. The version is the same one I originally used, the most recent until now, 2.05.I opened the project without making any changes, I compiled it, however, it did not compile. Errors were found, the first listing was:

error: unknown type name 'far'

This error did not occur before. What could have happened? Does anyone have any ideas ?

答: I think in XC8 the far qualifier is controlled by the --ADDRQUAL option. It may have been added into properties on the first installation. If you don't need to place that variable in extended memory you can omit it.


问:
cv2.VideoWriter: Asks for a tuple as Size argument, then rejects it
I'm using OpenCV 4.0 and Python 3.7 to create a timelapse video.

When constructing a VideoWriter object, the documentation says the Size argument should be a tuple.

When I give it a tuple it rejects it. When I try to replace it with something else, it won't accept it because it says the argument isn't a tuple.

When Size not a tuple:

```<code>out = cv2.VideoWriter('project.avi', 1482049860, 30, height, width)
SystemError: new style getargs format but argument is not a tuple
</code>```

When I changed Size to a tuple:

```<code>out = cv2.VideoWriter('project.avi', 1482049860, 30, (height, width))
TypeError: must be real number, not tuple
</code>```

I just want to create a simple cv2.VideoWriter object.

答:
Try updating to opencv v4.1.0. Not seeing that issue there.

Else try:

```<code>out = cv2.VideoWriter('project.avi', 1482049860, 30, frameSize=(height, width))
</code>```

Body:
I'm using OpenCV 4.0 and Python 3.7 to create a timelapse video.

When constructing a VideoWriter object, the documentation says the Size argument should be a tuple.

When I give it a tuple it rejects it. When I try to replace it with something else, it won't accept it because it says the argument isn't a tuple.

When Size not a tuple:

out = cv2.VideoWriter('project.avi', 1482049860, 30, height, width)
SystemError: new style getargs format but argument is not a tuple

When I changed Size to a tuple:

out = cv2.VideoWriter('project.avi', 1482049860, 30, (height, width))
TypeError: must be real number, not tuple

I just want to create a simple cv2.VideoWriter object.

Body:
Try updating to opencv v4.1.0. Not seeing that issue there.

Else try:

out = cv2.VideoWriter('project.avi', 1482049860, 30, frameSize=(height, width))


问:
mkdir no such file or directory syntax error?
I'm trying to auto-create an auto folder that is unique. Therefore i'm trying to name the folder after a date time stamp.

the code below is what i have already tried.

```<code>#! /bin/bash
d_space=$(date)
d_nospace= echo ${d_space//[[:blanl:]]/}
echo $d_nospace
mkdir -p "$d_nospace"

WedMay2920:52:47EDT2019
mkdir: cannot create directory '': No such file or directory
</code>```

答:
```<code>d_nospace= echo ${d_space//[[:blanl:]]/}
...
mkdir -p "$d_nospace"
</code>```

You're trying to create a directory whose name is the empty string. The "No such file or directory" message is a little misleading. The real problem is that the name is invalid.

A variable assignment must have no spaces before or after the = character. You can have a variable assignment as part of another command, for example:

```<code>foo=bar some_command
</code>```

will execute some_command with $foo set to bar.

So your command invokes the echo command with the variable d_nospace set to nothing.

As John's answer points out, you don't need to use echo here -- and in fact it doesn't make sense to do so. If you wanted to delete spaces, you'd write:

```<code>d_nospace="${d_space//[[:blanl:]]/}"
</code>```

(I haven't checked that for accuracy; shouldn't that be [[:blank:]]?

Incidentally, I wouldn't use the output of date as a file or directory name. The spaces and colons can cause problems, the output can vary depending on your locale settings, and the result does not sort well.

Here's how I'd do it:

```<code>now="$(date +%F-%H%M%S)"
mkdir -p "$now"
</code>```

As I write this, the directory name would be 2019-05-29-191819, which is reasonably human-readable, sorts nicely, and avoids problematic characters.

Body:
I'm trying to auto-create an auto folder that is unique. Therefore i'm trying to name the folder after a date time stamp.

the code below is what i have already tried.

#! /bin/bash
d_space=$(date)
d_nospace= echo ${d_space//[[:blanl:]]/}
echo $d_nospace
mkdir -p "$d_nospace"

WedMay2920:52:47EDT2019
mkdir: cannot create directory '': No such file or directory

Body:
d_nospace= echo ${d_space//[[:blanl:]]/}
...
mkdir -p "$d_nospace"

You're trying to create a directory whose name is the empty string. The "No such file or directory" message is a little misleading. The real problem is that the name is invalid.

A variable assignment must have no spaces before or after the = character. You can have a variable assignment as part of another command, for example:

foo=bar some_command

will execute some_command with $foo set to bar.

So your command invokes the echo command with the variable d_nospace set to nothing.

As John's answer points out, you don't need to use echo here -- and in fact it doesn't make sense to do so. If you wanted to delete spaces, you'd write:

d_nospace="${d_space//[[:blanl:]]/}"

(I haven't checked that for accuracy; shouldn't that be [[:blank:]]?

Incidentally, I wouldn't use the output of date as a file or directory name. The spaces and colons can cause problems, the output can vary depending on your locale settings, and the result does not sort well.

Here's how I'd do it:

now="$(date +%F-%H%M%S)"
mkdir -p "$now"

As I write this, the directory name would be 2019-05-29-191819, which is reasonably human-readable, sorts nicely, and avoids problematic characters.


问:
Why does variadic macro fail with expected primary-expression before ‘)’ token unless preceded by a named argument?
I'm trying to create some trace macros that use variadic arguments. The macros only seem to function correctly when a named argument precedes the variadic ones.

A minimal code version of what I'm doing is shown below. Only TraceTest() without arguments fails. I have also tried to create an intermediate macro that passes a dummy first argument to TraceTest1, but that fails too.

```<code>template<typename ...Args>
inline void f(const char*, Args&&... args) { }

#define TraceTest1(a, args...) f("Trace Start ", ##args)
#define TraceTest(args...) f("Trace Start", ##args)

TraceTest();     // error: expected primary-expression before ‘)’ token
TraceTest("a");  // works
TraceTest1();    // works
TraceTest1("a"); // works
</code>```

I have read the gnu docs on variadic macros but could find nothing that would explain this.

I am using gcc 7.4.0 under Ubuntu 18.04 and compiling with

```<code>g++ -Wall -Wextra -std=c++17 src/event.cpp -obin/event
</code>```

答:
TraceTest() expands to f("Trace start",), which is obviously a syntax error.

Both named variadic macro parameters and token pasting of ',' and variadic macro parameters are not standard C++ (even though every compiler I can find implements the latter).  If you want them with GCC, use "-std=gnu++17" instead of "-std=c++17".

Note that C++20 is adding a new __VA_OPT__ preprocessor token that can be used to do this in a portable way:

```<code>#define TraceTest(...) f("Trace Start " __VA_OPT__(,) __VA_ARGS__)
</code>```

Live Demo

__VA_OPT__ is replaced with its parameters only if __VA_ARGS__ isn't empty, so TraceTest() will be replaced with f("Trace Start ").

Body:
I'm trying to create some trace macros that use variadic arguments. The macros only seem to function correctly when a named argument precedes the variadic ones.

A minimal code version of what I'm doing is shown below. Only TraceTest() without arguments fails. I have also tried to create an intermediate macro that passes a dummy first argument to TraceTest1, but that fails too.

template<typename ...Args>
inline void f(const char*, Args&&... args) { }

#define TraceTest1(a, args...) f("Trace Start ", ##args)
#define TraceTest(args...) f("Trace Start", ##args)

TraceTest();     // error: expected primary-expression before ‘)’ token
TraceTest("a");  // works
TraceTest1();    // works
TraceTest1("a"); // works

I have read the gnu docs on variadic macros but could find nothing that would explain this.

I am using gcc 7.4.0 under Ubuntu 18.04 and compiling with

g++ -Wall -Wextra -std=c++17 src/event.cpp -obin/event

Body:
TraceTest() expands to f("Trace start",), which is obviously a syntax error.

Both named variadic macro parameters and token pasting of ',' and variadic macro parameters are not standard C++ (even though every compiler I can find implements the latter).  If you want them with GCC, use "-std=gnu++17" instead of "-std=c++17".

Note that C++20 is adding a new __VA_OPT__ preprocessor token that can be used to do this in a portable way:

#define TraceTest(...) f("Trace Start " __VA_OPT__(,) __VA_ARGS__)

Live Demo

__VA_OPT__ is replaced with its parameters only if __VA_ARGS__ isn't empty, so TraceTest() will be replaced with f("Trace Start ").


问:
Python: Select and move file based on criteria in a directory
I have about 10 minutes of video and just extracted into every frame so I have more than 100,000 of images in my folder and renamed them from 1 to 100,000. Now I want to select 1 of every 30 from 1 to 100,000 images and move them to another folder. For example : 1, 31,61,91,121,151,181 and so on.

This is my code so far:

```<code>import os
import shutil

PATH = './Folder1/'
DEST = './Folder2/'

file = 1

for file in os.listdir(PATH):
    file = file + 30
    shutil.copyfile(PATH, DEST)
</code>```

But it gave me following error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-b08091703697> in <module>
      9 # Get a list of files in the current working directory
     10 for file in os.listdir(PATH):
---> 11     file = file + 30
     12     shutil.copyfile(PATH, DEST)

TypeError: can only concatenate str (not "int") to str
</code>```

Thanks in advance for any help!

答:
Your error said that you need to convert int to str before adding them together. You can use

```<code>file = file + str(30)
</code>```

then improve your original code later on.

Or you can use my idea below.

```<code>for idx in range(1, 100000, 30):
   shutil.copyfile(PATH + str(idx), DEST)
</code>```

Body:
I have about 10 minutes of video and just extracted into every frame so I have more than 100,000 of images in my folder and renamed them from 1 to 100,000. Now I want to select 1 of every 30 from 1 to 100,000 images and move them to another folder. For example : 1, 31,61,91,121,151,181 and so on.

This is my code so far:

import os
import shutil

PATH = './Folder1/'
DEST = './Folder2/'

file = 1

for file in os.listdir(PATH):
    file = file + 30
    shutil.copyfile(PATH, DEST)

But it gave me following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-b08091703697> in <module>
      9 # Get a list of files in the current working directory
     10 for file in os.listdir(PATH):
---> 11     file = file + 30
     12     shutil.copyfile(PATH, DEST)

TypeError: can only concatenate str (not "int") to str

Thanks in advance for any help!

Body:
Your error said that you need to convert int to str before adding them together. You can use

file = file + str(30)

then improve your original code later on.

Or you can use my idea below.

for idx in range(1, 100000, 30):
   shutil.copyfile(PATH + str(idx), DEST)


答:
Try the following code</p>

```<code>PATH = '/Folder1/'
DEST = './Folder2/'
l = os.listdir(PATH)
file = 1

for file in l[::30]:
    shutil.copyfile(PATH, DEST)
</code>```

Title: Python: Select and move file based on criteria in a directory

Body:
Try the following code

PATH = '/Folder1/'
DEST = './Folder2/'
l = os.listdir(PATH)
file = 1

for file in l[::30]:
    shutil.copyfile(PATH, DEST)


问:
How can I simulate SerialPort interactions for testing?
I'm about to start developing a small app (C#) that communicates with a PLC and a testing unit via Serial Ports - this is my first venture into this area.

In essence, I am going to send the PLC a signal to start an operation, and then I am going to wait for the result of that operation from the test unit (which will be independently communicating with the PLC) to return a ASCII string.

Depending on the content of that string, I may want to listen to a signal from the PLC...

It's all new to me, so at the moment, I'm just researching System.IO.Ports.SerialPort; digression: are there third part products out there than simplify interaction with the Serial Port, or are the built-in classes as good as you will get? I'm thinking of ease of use as opposed to better features.

However, it will be a few weeks before the hardware is available for development and testing, so I was wondering how I could simulate communication to/from the serial port so that I can start developing my app?

[I don't yet know how the PLC and the PC are due to communicate - I understand it will be binary rather than text, but at the moment, that is all I know.]

答:
There are two pieces of software that I have found invaluable while doing serial port work.

Free Serial Port Monitor

http://www.serial-port-monitor.com

Despite the cheesy name, it is actually quite useful.  Note that you should have it stop listening to your port if you go to unplug a USB-to-Serial converter.  Otherwise it can crash (well... wait indefinitely on exit, which is annoying).  It doesn't have to put itself in the middle of a serial connection to sniff data.  It monitors the IO using the Win32 API.

Franson Serial Port Tools

http://franson.com/serialtools/

Or.. any loopback software really.  There are lots out there.  This allows you to send data and receive it within software.  If you end up doing any GPS work, Franson also has a nice GPS simulator so you don't have to sit outside the whole time to debug code.

Finally, if you have had enough with the built-in serial class and its horrendous shortcomings, then you need a replacement, and going straight to the Win32 API will take forever.

CommStudio

I have found CommStudio to be absolutely rock solid.  Quite frankly, after spending 5 months researching and buying other options, it is the only one that works perfectly with removable USB adapters.  All of the other solutions have issues when the device is plugged back in.  You can download their free "Express" version here:  http://www.componentsource.com/products/commstudio/downloads.html?rv=42917


问:
How do I stub a function that is not directly passed to the calling function?
I have an express app with API endpoints secured using JWT token. I have a method that verifies a received token.

```<code>// authentication.js

import jwt from 'jsonwebtoken';
import Settings from '../settings';

const AuthenticationMiddleware = {
    verifyToken: (req, res, next) => {
        const token = req.headers['x-access-token'];
        if (!token) {
            const msg = 'Include a valid token in the x-access-token header';
            return res.status(422).json({
                error: 'No token provided',
                msg
            });
        }
        try {
            req.user = jwt.verify(token, Settings.jwtSecret);
            req.token = token;
            return next();
        }
        catch (e) {
            return res.status(422).json({ error: 'Invalid token' });
        }
    }
};

export default AuthenticationMiddleware;
</code>```

This works fine when I call the API endpoints from postman with the token header included.

Now I have a test such as shown below. There's about 40 of them, each requiring a token to be sent with each API request.

```<code>// should is not used directly in the file but is added as a mocha requirement

import supertest from 'supertest';
import app from '../app';

const server = supertest.agent(app);
const BASE_URL = '/api/v1';

describe('/loans: Get all loans', () => {
    it('should return a list of all loans', done => {
        server
            .get(`${BASE_URL}/loans`)
            .expect(200)
            .end((err, res) => {
                res.status.should.equal(200);
                res.body.data.should.be.an.instanceOf(Array);
                for (const each of res.body.data) {
                    each.should.have.property('id');
                    each.should.have.property('userid');
                }
                done();
            });
    });
});
</code>```

I've looked at sinon and tried stubbing the verifyToken function in mocha's before hook like so

```<code>import sinon from 'sinon';
import AuthenticationMiddleware from '../middleware/authentication';

before(() => {
    const stub = sinon.stub(AuthenticationMiddleware, 'verifyToken');
    stub.returnsThis()
});
</code>```

But I can already see a problem here. While the verifyToken stub may have been created, it is NOT used during the test. The verifyToken that is being called during the test is passed as middleware from the route like so

```<code>router.get('/loans', AuthenticationMiddleware.verifyToken, LoansController.get_all_loans);
</code>```

I want a way to stub verifyToken during the test so that I can just return next() immediately.

My question is, is it possible to stub AuthenticationMiddleware.verifyToken universally during the test so that all calls to the API endpoint call the stubbed version?

答:
According to these two posts, Sinon stub being skipped as node express middleware and How to mock middleware in Express to skip authentication for unit test?, the reason for my stub not being active was that the app was being imported and cached before the stub is even created, so the app uses the one it has cached.

So the solution was to alter the required function before the app gets a chance to cache it. What I did was that (I stumble upon it by trial and error) was to create a file in my test folder called stubs.js and here's the content.

```<code>import sinon from 'sinon';
import AuthenticationMiddleware from '../middleware/authentication';

sinon.stub(AuthenticationMiddleware, 'verifyToken').callsFake(
    (req, res, next) => next()
);
</code>```

Then I require this file in my test runner in package.json like so

```<code>    "scripts": {
        "test": "nyc --reporter=html --reporter=text --reporter=lcov mocha -r @babel/register -r should -r test/stubs.js"
    },
</code>```

Body:
I have an express app with API endpoints secured using JWT token. I have a method that verifies a received token.

// authentication.js

import jwt from 'jsonwebtoken';
import Settings from '../settings';

const AuthenticationMiddleware = {
    verifyToken: (req, res, next) => {
        const token = req.headers['x-access-token'];
        if (!token) {
            const msg = 'Include a valid token in the x-access-token header';
            return res.status(422).json({
                error: 'No token provided',
                msg
            });
        }
        try {
            req.user = jwt.verify(token, Settings.jwtSecret);
            req.token = token;
            return next();
        }
        catch (e) {
            return res.status(422).json({ error: 'Invalid token' });
        }
    }
};

export default AuthenticationMiddleware;

This works fine when I call the API endpoints from postman with the token header included.

Now I have a test such as shown below. There's about 40 of them, each requiring a token to be sent with each API request.

// should is not used directly in the file but is added as a mocha requirement

import supertest from 'supertest';
import app from '../app';

const server = supertest.agent(app);
const BASE_URL = '/api/v1';

describe('/loans: Get all loans', () => {
    it('should return a list of all loans', done => {
        server
            .get(`${BASE_URL}/loans`)
            .expect(200)
            .end((err, res) => {
                res.status.should.equal(200);
                res.body.data.should.be.an.instanceOf(Array);
                for (const each of res.body.data) {
                    each.should.have.property('id');
                    each.should.have.property('userid');
                }
                done();
            });
    });
});

I've looked at sinon and tried stubbing the verifyToken function in mocha's before hook like so

import sinon from 'sinon';
import AuthenticationMiddleware from '../middleware/authentication';

before(() => {
    const stub = sinon.stub(AuthenticationMiddleware, 'verifyToken');
    stub.returnsThis()
});

But I can already see a problem here. While the verifyToken stub may have been created, it is NOT used during the test. The verifyToken that is being called during the test is passed as middleware from the route like so

router.get('/loans', AuthenticationMiddleware.verifyToken, LoansController.get_all_loans);

I want a way to stub verifyToken during the test so that I can just return next() immediately.

My question is, is it possible to stub AuthenticationMiddleware.verifyToken universally during the test so that all calls to the API endpoint call the stubbed version?

Body:
According to these two posts, Sinon stub being skipped as node express middleware and How to mock middleware in Express to skip authentication for unit test?, the reason for my stub not being active was that the app was being imported and cached before the stub is even created, so the app uses the one it has cached.

So the solution was to alter the required function before the app gets a chance to cache it. What I did was that (I stumble upon it by trial and error) was to create a file in my test folder called stubs.js and here's the content.

import sinon from 'sinon';
import AuthenticationMiddleware from '../middleware/authentication';

sinon.stub(AuthenticationMiddleware, 'verifyToken').callsFake(
    (req, res, next) => next()
);

Then I require this file in my test runner in package.json like so

    "scripts": {
        "test": "nyc --reporter=html --reporter=text --reporter=lcov mocha -r @babel/register -r should -r test/stubs.js"
    },


问:
How to divide each element in a row by corresponding row value?
(I want to divide each element in a row by corresponding row value. Denominator should the value of "Ac" when row element is present.</p>

```<code>Ac    V1  V2  V3   V4  V5  V6  V7
6.6  NA  NA  NA   NA   0  5.6  5.2
8.4  NA  0   82.5 31   0  0    1.1

Output:

V1 V2    V3        V4       V5                            V6               V7
NA 0/8.4 82.5/8.4 31/8.4  (0*6.6+0*6.6)/(6.6+8.4) (5.6*6.6+0*8.4)/(6.6+8.4) (5.2*6.6+1.1*8.4)/(6.6+8.4)
</code>```

答:
try using the loop and convert output to dataframe or list</p>

```<code>for (i in 2:8){

    temp1 = df[1,i]/df[1,1]
    temp2 = df[2,i]/df[2,1]
    temp= ifelse(!is.na(temp1)&!is.na(temp2), temp1+temp2,
          ifelse(is.na(temp1) &!is.na(temp2), temp2,
          ifelse(!is.na(temp1) &is.na(temp2), temp1,NA)))
    assign(paste0("V", i-1), temp)
    rm(temp1, temp2, temp)
}
output <- c(V1, V2, V3, V4, V5, V6, V7)
output <- data.frame(output)

     output
1        NA
2 0.0000000
3 9.8214286
4 3.6904762
5 0.0000000
6 0.8484848
7 0.9188312
</code>```

Body:
(I want to divide each element in a row by corresponding row value. Denominator should the value of "Ac" when row element is present.

Ac    V1  V2  V3   V4  V5  V6  V7
6.6  NA  NA  NA   NA   0  5.6  5.2
8.4  NA  0   82.5 31   0  0    1.1

Output:

V1 V2    V3        V4       V5                            V6               V7
NA 0/8.4 82.5/8.4 31/8.4  (0*6.6+0*6.6)/(6.6+8.4) (5.6*6.6+0*8.4)/(6.6+8.4) (5.2*6.6+1.1*8.4)/(6.6+8.4)

Body:
try using the loop and convert output to dataframe or list

for (i in 2:8){

    temp1 = df[1,i]/df[1,1]
    temp2 = df[2,i]/df[2,1]
    temp= ifelse(!is.na(temp1)&!is.na(temp2), temp1+temp2,
          ifelse(is.na(temp1) &!is.na(temp2), temp2,
          ifelse(!is.na(temp1) &is.na(temp2), temp1,NA)))
    assign(paste0("V", i-1), temp)
    rm(temp1, temp2, temp)
}
output <- c(V1, V2, V3, V4, V5, V6, V7)
output <- data.frame(output)

     output
1        NA
2 0.0000000
3 9.8214286
4 3.6904762
5 0.0000000
6 0.8484848
7 0.9188312


问:
Handle onBackPressed in Android Navigation Component
I have implemented navigation Drawer with Navigation Components in Android. I have 5 fragments that I want to go back to my HomeFragment when I click on back pressed. For the moment they stay onBackStack and do not go to my desired fragment but go to whatever fragment was first.
This is my nav_graph :

```<code><?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            app:startDestination="@id/setupFragment"
            android:id="@+id/treasure_nav"
            android:label="Pick a country">
    <fragment android:id="@+id/homeFragment"
              android:name="com.stavro_xhardha.pockettreasure.ui.home.HomeFragment"
              android:label="Home"
              tools:layout="@layout/fragment_home">
        <action android:id="@+id/action_home_fragment_to_namesFragment2"
                app:popUpTo="@id/homeFragment"
                app:destination="@id/namesFragment"/>
        <action android:id="@+id/action_home_fragment_to_quranFragment"
                app:popUpTo="@id/homeFragment"
                app:destination="@id/quranFragment"/>
        <action android:id="@+id/action_homeFragment_to_tasbeehFragment"
                app:popUpTo="@id/homeFragment"
                app:destination="@id/tasbeehFragment"/>
        <action android:id="@+id/action_homeFragment_to_galleryFragment"
                app:popUpTo="@id/homeFragment"
                app:destination="@id/galleryFragment"/>
        <action android:id="@+id/action_homeFragment_to_newsFragment"
                app:popUpTo="@id/homeFragment"
                app:destination="@id/newsFragment"/>
        <action android:id="@+id/action_homeFragment_to_settingsFragment"
                app:popUpTo="@id/homeFragment"
                app:destination="@id/settingsFragment"/>
    </fragment>
    <fragment
            android:id="@+id/namesFragment"
            android:name="com.stavro_xhardha.pockettreasure.ui.names.NamesFragment"
            android:label="Names of Allah"
            tools:layout="@layout/fragment_names"/>
    <fragment
            android:id="@+id/quranFragment"
            android:name="com.stavro_xhardha.pockettreasure.ui.quran.QuranFragment"
            android:label="Quran"
            tools:layout="@layout/fragment_quran"/>
    <fragment android:id="@+id/tasbeehFragment"
              android:name="com.stavro_xhardha.pockettreasure.ui.tasbeeh.TasbeehFragment"
              android:label="Tasbeeh"
              tools:layout="@layout/fragment_tasbeeh"/>
    <fragment android:id="@+id/galleryFragment"
              android:name="com.stavro_xhardha.pockettreasure.ui.gallery.GalleryFragment"
              android:label="Gallery"
              tools:layout="@layout/fragment_gallery"/>
    <fragment android:id="@+id/newsFragment"
              android:name="com.stavro_xhardha.pockettreasure.ui.news.NewsFragment"
              android:label="News"
              tools:layout="@layout/fragment_news"/>
    <fragment android:id="@+id/settingsFragment"
              android:name="com.stavro_xhardha.pockettreasure.ui.settings.SettingsFragment"
              android:label="Settings"
              tools:layout="@layout/fragment_settings"/>
    <fragment android:id="@+id/setupFragment"
              android:name="com.stavro_xhardha.pockettreasure.ui.setup.SetupFragment"
              android:label="Pick country"
              tools:layout="@layout/fragment_setup">
        <action android:id="@+id/action_setupFragment_to_homeFragment3"
                app:destination="@+id/homeFragment"
                app:launchSingleTop="true"
                app:popUpTo="@+id/treasure_nav"
                app:popUpToInclusive="true"/>
    </fragment>
</navigation>
</code>```

And this is my onBackPressed in my MainActivity (and the only one) :

```<code>override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
                super.onBackPressed()
        }
    }
</code>```

Edit: When i remove the super.onBackPressed() and replace it with :
         findNavController(R.id.nav_host_fragment).popBackStack(R.id.homeFragment, false) I achieve what I want. The only problem is that when I am in the homeFragment I want to end the app but I can't.

答:
If my understanding is correct, you want to go back to HomeFragment wherever you are in the navigation flow. For this case you could try registering OnBackPressedCallback on your Fragments via addOnBackPressedCallback, and call popBackStack to navigate to your HomeFragment. Try adding this to Fragments' onViewCreated that need to go back to HomeFragment on backpress:</p>

```<code>@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        navController = Navigation.findNavController(view);

        requireActivity().addOnBackPressedCallback(getViewLifecycleOwner(), () -> {
               navController.popBackStack(R.id.homeFragment, false);
            });
            return true;
        });
</code>```

Body:
I have implemented navigation Drawer with Navigation Components in Android. I have 5 fragments that I want to go back to my HomeFragment when I click on back pressed. For the moment they stay onBackStack and do not go to my desired fragment but go to whatever fragment was first.
This is my nav_graph :

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            app:startDestination="@id/setupFragment"
            android:id="@+id/treasure_nav"
            android:label="Pick a country">
    <fragment android:id="@+id/homeFragment"
              android:name="com.stavro_xhardha.pockettreasure.ui.home.HomeFragment"
              android:label="Home"
              tools:layout="@layout/fragment_home">
        <action android:id="@+id/action_home_fragment_to_namesFragment2"
                app:popUpTo="@id/homeFragment"
                app:destination="@id/namesFragment"/>
        <action android:id="@+id/action_home_fragment_to_quranFragment"
                app:popUpTo="@id/homeFragment"
                app:destination="@id/quranFragment"/>
        <action android:id="@+id/action_homeFragment_to_tasbeehFragment"
                app:popUpTo="@id/homeFragment"
                app:destination="@id/tasbeehFragment"/>
        <action android:id="@+id/action_homeFragment_to_galleryFragment"
                app:popUpTo="@id/homeFragment"
                app:destination="@id/galleryFragment"/>
        <action android:id="@+id/action_homeFragment_to_newsFragment"
                app:popUpTo="@id/homeFragment"
                app:destination="@id/newsFragment"/>
        <action android:id="@+id/action_homeFragment_to_settingsFragment"
                app:popUpTo="@id/homeFragment"
                app:destination="@id/settingsFragment"/>
    </fragment>
    <fragment
            android:id="@+id/namesFragment"
            android:name="com.stavro_xhardha.pockettreasure.ui.names.NamesFragment"
            android:label="Names of Allah"
            tools:layout="@layout/fragment_names"/>
    <fragment
            android:id="@+id/quranFragment"
            android:name="com.stavro_xhardha.pockettreasure.ui.quran.QuranFragment"
            android:label="Quran"
            tools:layout="@layout/fragment_quran"/>
    <fragment android:id="@+id/tasbeehFragment"
              android:name="com.stavro_xhardha.pockettreasure.ui.tasbeeh.TasbeehFragment"
              android:label="Tasbeeh"
              tools:layout="@layout/fragment_tasbeeh"/>
    <fragment android:id="@+id/galleryFragment"
              android:name="com.stavro_xhardha.pockettreasure.ui.gallery.GalleryFragment"
              android:label="Gallery"
              tools:layout="@layout/fragment_gallery"/>
    <fragment android:id="@+id/newsFragment"
              android:name="com.stavro_xhardha.pockettreasure.ui.news.NewsFragment"
              android:label="News"
              tools:layout="@layout/fragment_news"/>
    <fragment android:id="@+id/settingsFragment"
              android:name="com.stavro_xhardha.pockettreasure.ui.settings.SettingsFragment"
              android:label="Settings"
              tools:layout="@layout/fragment_settings"/>
    <fragment android:id="@+id/setupFragment"
              android:name="com.stavro_xhardha.pockettreasure.ui.setup.SetupFragment"
              android:label="Pick country"
              tools:layout="@layout/fragment_setup">
        <action android:id="@+id/action_setupFragment_to_homeFragment3"
                app:destination="@+id/homeFragment"
                app:launchSingleTop="true"
                app:popUpTo="@+id/treasure_nav"
                app:popUpToInclusive="true"/>
    </fragment>
</navigation>

And this is my onBackPressed in my MainActivity (and the only one) :

override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
                super.onBackPressed()
        }
    }

Edit: When i remove the super.onBackPressed() and replace it with :
         findNavController(R.id.nav_host_fragment).popBackStack(R.id.homeFragment, false) I achieve what I want. The only problem is that when I am in the homeFragment I want to end the app but I can't.

Body:
If my understanding is correct, you want to go back to HomeFragment wherever you are in the navigation flow. For this case you could try registering OnBackPressedCallback on your Fragments via addOnBackPressedCallback, and call popBackStack to navigate to your HomeFragment. Try adding this to Fragments' onViewCreated that need to go back to HomeFragment on backpress:

@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        navController = Navigation.findNavController(view);

        requireActivity().addOnBackPressedCallback(getViewLifecycleOwner(), () -> {
               navController.popBackStack(R.id.homeFragment, false);
            });
            return true;
        });