问:
regex look around on either side (two words are nearby each other within certain distance, regardless of order)
My goal is to use grepl and pattern to find words matches in sentences. The pattern would be to match two words that are nearby each other (say, up to 2 words between them, regardless of order). See the example data and my expected results in the code chunk below.

Problem
My test function (code bellow) was reported an error, it says invalid regular expression. The problem seems to be in the second part (i.e., pat2), or specifically here (?<=(?:resource.?\\b|basic service|property))\\s(?:\\w+\\s){0,2}(?=(?:access to|\\brights to)). I wonder what the issue is, as I did not see much difference between pat2 and pat1 in my function. If there are more elegant ways to achieve this, that would be much appreciated too!

```<code>## my function

condition1 <- "\\s"                 ## a space after the 1st word
condition2 <- "(?:\\w+\\s)"         ## a word character with a space after it

lookaround_nearby_n <- function(word1, word2, n){
  pat1 <- paste0("(?<=", word1, ")",
              condition1,
              condition2,            ## other strings after the space (`condition2`)
              "{0,", n, "}",         ## Matches `condition2` at most n times
              "(?=", word2, ")")     ## the 2nd word

  pat2 <- paste0("(?<=", word2, ")",
                condition1,
                condition2,            ## other strings after the space (`condition2`)
                "{0,", n, "}",         ## Matches `condition2` at most n times
                "(?=", word1, ")")     ##
  pat <- paste(pat1, pat2, sep = "|");
  return(pat)
}

w1 <- "(?:access to|\\brights to)"
w2 <- "(?:resource.?\\b|basic service|property)"

pat <- lookaround_nearby_n(word1 = w1, word2 = w2, n = 2)
pat

## test data
dataframe <- data_frame(mytext = c('SD is access to property',
                                   'SD is access to x1 property',
                                   'SD is access to x1 x2 property',
                                   'SD is access to x1 x2 x3 property',
                                   'SD property access to sth',
                                   'SD property x1 access to sth',
                                   'SD property x1 x2 access to sb',
                                   'SD property x1 x2 x3 access to sb'))

grepl(pattern = pat, x = dataframe$mytext, ignore.case = T, perl = T)

## I expect to get "T, T, T, F, T, T, T, F" from the above example.
</code>```

答:
A simpler version of your function, without look behind should work:

```<code>lookaround_nearby_n <- function(word1, word2, n){
  condition = paste0("\\s(?:\\w+\\s){0,",n,"}")
  paste0("(",word1,condition,word2,")","|",
         "(",word2,condition,word1,")")
}

w1 <- "(access to|rights to)"
w2 <- "(resource|basic service|property)"

pat=lookaround_nearby_n(w1,w2,2)

grepl(pattern = pat, x = dataframe$mytext, ignore.case = T, perl = T)
</code>```

Output

```<code>[1]  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE
</code>```

Body:
My goal is to use grepl and pattern to find words matches in sentences. The pattern would be to match two words that are nearby each other (say, up to 2 words between them, regardless of order). See the example data and my expected results in the code chunk below.

Problem
My test function (code bellow) was reported an error, it says invalid regular expression. The problem seems to be in the second part (i.e., pat2), or specifically here (?<=(?:resource.?\\b|basic service|property))\\s(?:\\w+\\s){0,2}(?=(?:access to|\\brights to)). I wonder what the issue is, as I did not see much difference between pat2 and pat1 in my function. If there are more elegant ways to achieve this, that would be much appreciated too!

## my function

condition1 <- "\\s"                 ## a space after the 1st word
condition2 <- "(?:\\w+\\s)"         ## a word character with a space after it

lookaround_nearby_n <- function(word1, word2, n){
  pat1 <- paste0("(?<=", word1, ")",
              condition1,
              condition2,            ## other strings after the space (`condition2`)
              "{0,", n, "}",         ## Matches `condition2` at most n times
              "(?=", word2, ")")     ## the 2nd word

  pat2 <- paste0("(?<=", word2, ")",
                condition1,
                condition2,            ## other strings after the space (`condition2`)
                "{0,", n, "}",         ## Matches `condition2` at most n times
                "(?=", word1, ")")     ##
  pat <- paste(pat1, pat2, sep = "|");
  return(pat)
}

w1 <- "(?:access to|\\brights to)"
w2 <- "(?:resource.?\\b|basic service|property)"

pat <- lookaround_nearby_n(word1 = w1, word2 = w2, n = 2)
pat

## test data
dataframe <- data_frame(mytext = c('SD is access to property',
                                   'SD is access to x1 property',
                                   'SD is access to x1 x2 property',
                                   'SD is access to x1 x2 x3 property',
                                   'SD property access to sth',
                                   'SD property x1 access to sth',
                                   'SD property x1 x2 access to sb',
                                   'SD property x1 x2 x3 access to sb'))

grepl(pattern = pat, x = dataframe$mytext, ignore.case = T, perl = T)

## I expect to get "T, T, T, F, T, T, T, F" from the above example.

Body:
A simpler version of your function, without look behind should work:

lookaround_nearby_n <- function(word1, word2, n){
  condition = paste0("\\s(?:\\w+\\s){0,",n,"}")
  paste0("(",word1,condition,word2,")","|",
         "(",word2,condition,word1,")")
}

w1 <- "(access to|rights to)"
w2 <- "(resource|basic service|property)"

pat=lookaround_nearby_n(w1,w2,2)

grepl(pattern = pat, x = dataframe$mytext, ignore.case = T, perl = T)

Output

[1]  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE


来源: stackexchange

问:
Price history extraction from steam market
I am using following URL to extract the JSON file for the price history

https://steamcommunity.com/market/pricehistory/?appid=730&market_hash_name=P90%20|%20Blind%20Spot%20(Field-Tested)

The python code I am using:

```<code>    item = requests.get(URL, cookies={'steamLogin': steamid}); # get item data
    print(str(currRun),' out of ',str(len(allItemNames))+' code: '+str(item.status_code))
    item = item.content
    item = json.loads(item)
</code>```

Now I went to almost all the solutions that was posted in this community but I am still getting status code as 400 and Items as [].

When I copy paste the URL and open it in browser I am able to see the JSON file with required data but somehow the Jupyter notebook is unable to detect the content

I also tried Beautiful soup to read the content with the following code:

```<code>     r = requests.get(url)
     #below code extracts the whole HTML Code of above URL
     soup = BeautifulSoup(r.content, 'html5lib')
     table = soup.find_all('pre')
     print(table)
</code>```

Output: []

答:
So you are getting [] because you are not authorized, so you recieve empty json array. You can check it by opening link in incognito (Ctrl+Shift+N) mode.

To authorize you need to set Cookie header to your request, so your code will be as this:

```<code>import requests

url = "https://steamcommunity.com/market/pricehistory/?appid=730&market_hash_name=P90%20%7C%20Blind%20Spot%20(Field-Tested)"

headers = {
    "Cookie": "Your cookie"
}

json = requests.get(url, headers=headers).text
...
</code>```

How to find Cookie (Chrome)

Go to link with json

Press F12 to open Chrome Development Toolkit.

Open Network tab

Reload page.

Double click on first sent request

Open Headers subtab

Scroll to Request Headers

Find Cookie header

ContentLicense: CC BY-SA 4.0

Body:
I am using following URL to extract the JSON file for the price history

https://steamcommunity.com/market/pricehistory/?appid=730&market_hash_name=P90%20|%20Blind%20Spot%20(Field-Tested)

The python code I am using:

    item = requests.get(URL, cookies={'steamLogin': steamid}); # get item data
    print(str(currRun),' out of ',str(len(allItemNames))+' code: '+str(item.status_code))
    item = item.content
    item = json.loads(item)

Now I went to almost all the solutions that was posted in this community but I am still getting status code as 400 and Items as [].

When I copy paste the URL and open it in browser I am able to see the JSON file with required data but somehow the Jupyter notebook is unable to detect the content

I also tried Beautiful soup to read the content with the following code:

     r = requests.get(url)
     #below code extracts the whole HTML Code of above URL
     soup = BeautifulSoup(r.content, 'html5lib')
     table = soup.find_all('pre')
     print(table)

Output: []

Body:
So you are getting [] because you are not authorized, so you recieve empty json array. You can check it by opening link in incognito (Ctrl+Shift+N) mode.

To authorize you need to set Cookie header to your request, so your code will be as this:

import requests

url = "https://steamcommunity.com/market/pricehistory/?appid=730&market_hash_name=P90%20%7C%20Blind%20Spot%20(Field-Tested)"

headers = {
    "Cookie": "Your cookie"
}

json = requests.get(url, headers=headers).text
...

How to find Cookie (Chrome)

Go to link with json

Press F12 to open Chrome Development Toolkit.

Open Network tab

Reload page.

Double click on first sent request

Open Headers subtab

Scroll to Request Headers

Find Cookie header


问:
Brackets AEM extension timeout
I installed AEM extension to synchronize my repository with local instance of AEM, and it doesn't work, when I try to sync I have "timeout" response in console probably filter.xml is wrong but I don't know how to fix this.

<?xml version="1.0" encoding="UTF-8"?>
<workspaceFilter version="1.0">
    <filter root="etc/designs/zg/internship-project" mode="replace"/>
</workspaceFilter>

That's my settings in extension options

That's my project structure I want to synchronize everything in internship-project folder

答: Try to refresh file tree from left navigation and retry. If that is not working, try to close and reopen brackets</p>

Title: Brackets AEM extension timeout


问:
Searching PayPal subscriptions based on email
We have PayPal subscribers who have signed up for recurring monthly payments using a PayPal generated button on our site. We are thinking about placing a paywall of sorts around some of our content.

Is there a way to search our subscriber list based on a user's email? I would like for the user to input his email on our site. Then, I'll use PayPal's REST API to see if they are an active subscriber based on that.

I've looked on PayPal's API documentation, and I can only find the ability to search by the user's ID.  https://developer.paypal.com/api/subscriptions/v1/#subscriptions_get

Does PayPal have any other REST functionality to search by email? Thanks.

答:
There is no functionality to search by email.

Set up a webhook listener subscribed to PAYMENT.SALE.COMPLETED events, and keep your own record of the last time each subscription was paid for.


问:
How to obtain a closeness score bounded between 0 and 1
I would like to calculate the closeness of a network like e.g.

```<code>relations=structure(list(From = c("France", "Italy", "Malta", "Spain",
"Germany", "Austria", "Luxembourg", "Luxembourg", "Luxembourg",
"Greece", "Slovakia", "Belgium", "Luxembourg", "Estonia", "Germany",
"Netherlands", "Netherlands", "Cyprus", "Greece", "Lithuania",
"Estonia", "Greece", "Lithuania", "Slovakia", "Netherlands",
"Luxembourg", "Estonia", "Malta", "Belgium", "Cyprus", "Austria",
"Estonia", "Austria", "Germany", "Austria", "Netherlands", "Portugal",
"Portugal", "Estonia", "Italy", "Spain", "Finland", "Belgium",
"Spain", "Estonia", "Latvia", "Luxembourg", "Luxembourg", "Netherlands",
"Italy", "Lithuania", "Cyprus", "Ireland", "Luxembourg", "Ireland",
"Spain", "Belgium", "Latvia", "Netherlands", "Italy", "Slovenia",
"Netherlands", "Greece", "Spain", "Austria", "Finland", "Malta",
"Spain", "Austria", "Lithuania", "France", "Portugal", "Cyprus",
"Finland", "Spain", "Spain", "Belgium", "Germany", "Germany",
"Greece", "Netherlands", "Luxembourg", "Estonia", "Ireland",
"Italy", "Portugal", "Greece", "Estonia", "Belgium", "Germany",
"Slovenia", "Slovakia", "Lithuania", "Slovenia", "Portugal",
"Portugal", "Slovakia", "France", "Portugal", "Netherlands"),
    To = c("Slovakia", "Germany", "Portugal", "Austria", "Latvia",
    "Cyprus", "Portugal", "Greece", "Italy", "Slovenia", "Ireland",
    "Malta", "Ireland", "Germany", "Cyprus", "Portugal", "Slovenia",
    "Italy", "Luxembourg", "France", "Slovakia", "Netherlands",
    "Greece", "France", "Ireland", "Netherlands", "Cyprus", "Germany",
    "Portugal", "Austria", "Luxembourg", "Austria", "Spain",
    "Netherlands", "Belgium", "Cyprus", "Cyprus", "Luxembourg",
    "Finland", "Belgium", "Lithuania", "Austria", "Spain", "Slovenia",
    "Luxembourg", "Finland", "Slovenia", "Germany", "Austria",
    "Slovenia", "Slovenia", "Portugal", "Finland", "Lithuania",
    "Latvia", "France", "Netherlands", "Cyprus", "Spain", "Malta",
    "France", "Finland", "Belgium", "Latvia", "Slovenia", "Slovenia",
    "Cyprus", "Slovakia", "Slovakia", "Latvia", "Austria", "Ireland",
    "Luxembourg", "Belgium", "Italy", "Estonia", "Greece", "Slovakia",
    "Belgium", "Italy", "Latvia", "Malta", "Greece", "France",
    "Greece", "Netherlands", "France", "Slovenia", "Latvia",
    "Finland", "Austria", "Slovenia", "Belgium", "Cyprus", "Greece",
    "Slovenia", "Cyprus", "Finland", "Malta", "Germany"), weight = c(3.63689639539779e-09,
    2.36155345798604e-11, 1.90981717262912e-08, 1.27550515412245e-09,
    2.75032212941667e-09, 3.79663088493923e-08, 1.42368280746262e-08,
    1.51146811601353e-08, 1.75314892144034e-09, 2.07956027448449e-08,
    1.38623943876156e-07, 1.92893849444567e-08, 5.66419694274739e-08,
    5.8089561312222e-09, 1.95827364947702e-09, 6.7071674411728e-10,
    4.23667746162198e-09, 4.62966220873406e-08, 1.21403390886489e-07,
    1.26979107479853e-08, 5.59978765605208e-07, 3.14788992090851e-09,
    5.0058794053616e-07, 5.22186410794211e-09, 9.21607337940845e-10,
    2.51322812227745e-09, 3.04984607426863e-07, 3.20992561385791e-09,
    8.92180336424503e-10, 6.12766236972513e-08, 1.20231538847898e-08,
    1.34589665048046e-07, 8.84238627642763e-10, 2.63370671763944e-11,
    1.11903749128791e-09, 1.16731679208085e-08, 4.99654438989995e-08,
    2.90162442064053e-08, 2.55621731534268e-09, 1.58298464637584e-10,
    5.07475932446428e-08, 2.54927518867625e-09, 2.24427326793633e-10,
    4.49723284363684e-09, 2.43010060636845e-06, 1.90760030501003e-08,
    6.35902610582491e-08, 5.48833215255332e-10, 4.06612010446768e-10,
    5.32889353797193e-10, 1.23745070305762e-06, 8.89608483306497e-07,
    3.75876719292064e-09, 4.44758324449273e-07, 1.35536579831994e-07,
    5.42265922046125e-11, 4.8233448207134e-11, 3.4286615533894e-07,
    2.0214285544428e-10, 8.57988303618593e-10, 1.35631258148319e-09,
    7.97944858545598e-10, 4.2673026648725e-09, 9.28491399244895e-08,
    1.03420112425729e-09, 2.4972909387896e-08, 8.12118760999133e-07,
    1.31225365800221e-08, 1.77287287047586e-09, 6.53958727055997e-09,
    3.05841917976996e-10, 9.20687775127977e-09, 4.32323785012335e-07,
    8.40653865200987e-10, 1.23500809608508e-10, 6.59008808575339e-08,
    1.13962199159936e-09, 4.68300414991578e-10, 3.54758342726504e-11,
    6.55880483863129e-10, 1.17833628272869e-08, 5.08802989644665e-07,
    7.22191649442396e-07, 2.7028184600344e-10, 2.2810918951755e-10,
    8.10987753872438e-10, 1.50406384816011e-09, 5.46176491471454e-06,
    2.32716789835402e-08, 2.10873259303399e-10, 1.81735402994258e-09,
    9.71369590422109e-09, 2.01941765282435e-08, 1.8961914804496e-07,
    9.4461402995167e-09, 1.69816623519093e-07, 9.16774899583353e-08,
    8.54588845128718e-10, 4.79160495478785e-08, 2.31994460360924e-11
    )), row.names = c(NA, -100L), class = c("tbl_df", "tbl",
"data.frame"))
actors= c("Slovakia", "Germany", "Portugal", "Austria", "Latvia", "Cyprus",
"Greece", "Italy", "Slovenia", "Ireland", "Malta", "Luxembourg",
"France", "Netherlands", "Spain", "Belgium", "Finland", "Lithuania",
"Estonia")
g <- graph_from_data_frame(relations, directed=TRUE, vertices=actors)
</code>```

by using package igraph. Using function closeness I obtain:

```<code>closeness(g)
   Slovakia     Germany    Portugal     Austria      Latvia      Cyprus      Greece       Italy    Slovenia     Ireland
    4002492     7111002     6478738     6502665     2017834     1029940     6615891     7164685     5533119     6240785
      Malta  Luxembourg      France Netherlands       Spain     Belgium     Finland   Lithuania     Estonia
    5071100     7243749     6342911     7121291     7144000     7090895     6415382     3086085     7411727
</code>```

I would like to obtain a normalized closeness score bounded between 0 and 1. It is 0 if a node is an isolate, and 1 if a node is directly connected all others. What can I do

答:
In the function, you can call for "normalized = TRUE" because it is "FALSE" by default. Sidenote: It is helpful if you add the code you used to calculate closeness.</p>
```<code>closeness(
  graph,
  vids = V(graph),
  mode = c("out", "in", "all", "total"),
  weights = NULL,
  normalized = TRUE
)
</code>```

Body:
I would like to calculate the closeness of a network like e.g.

relations=structure(list(From = c("France", "Italy", "Malta", "Spain",
"Germany", "Austria", "Luxembourg", "Luxembourg", "Luxembourg",
"Greece", "Slovakia", "Belgium", "Luxembourg", "Estonia", "Germany",
"Netherlands", "Netherlands", "Cyprus", "Greece", "Lithuania",
"Estonia", "Greece", "Lithuania", "Slovakia", "Netherlands",
"Luxembourg", "Estonia", "Malta", "Belgium", "Cyprus", "Austria",
"Estonia", "Austria", "Germany", "Austria", "Netherlands", "Portugal",
"Portugal", "Estonia", "Italy", "Spain", "Finland", "Belgium",
"Spain", "Estonia", "Latvia", "Luxembourg", "Luxembourg", "Netherlands",
"Italy", "Lithuania", "Cyprus", "Ireland", "Luxembourg", "Ireland",
"Spain", "Belgium", "Latvia", "Netherlands", "Italy", "Slovenia",
"Netherlands", "Greece", "Spain", "Austria", "Finland", "Malta",
"Spain", "Austria", "Lithuania", "France", "Portugal", "Cyprus",
"Finland", "Spain", "Spain", "Belgium", "Germany", "Germany",
"Greece", "Netherlands", "Luxembourg", "Estonia", "Ireland",
"Italy", "Portugal", "Greece", "Estonia", "Belgium", "Germany",
"Slovenia", "Slovakia", "Lithuania", "Slovenia", "Portugal",
"Portugal", "Slovakia", "France", "Portugal", "Netherlands"),
    To = c("Slovakia", "Germany", "Portugal", "Austria", "Latvia",
    "Cyprus", "Portugal", "Greece", "Italy", "Slovenia", "Ireland",
    "Malta", "Ireland", "Germany", "Cyprus", "Portugal", "Slovenia",
    "Italy", "Luxembourg", "France", "Slovakia", "Netherlands",
    "Greece", "France", "Ireland", "Netherlands", "Cyprus", "Germany",
    "Portugal", "Austria", "Luxembourg", "Austria", "Spain",
    "Netherlands", "Belgium", "Cyprus", "Cyprus", "Luxembourg",
    "Finland", "Belgium", "Lithuania", "Austria", "Spain", "Slovenia",
    "Luxembourg", "Finland", "Slovenia", "Germany", "Austria",
    "Slovenia", "Slovenia", "Portugal", "Finland", "Lithuania",
    "Latvia", "France", "Netherlands", "Cyprus", "Spain", "Malta",
    "France", "Finland", "Belgium", "Latvia", "Slovenia", "Slovenia",
    "Cyprus", "Slovakia", "Slovakia", "Latvia", "Austria", "Ireland",
    "Luxembourg", "Belgium", "Italy", "Estonia", "Greece", "Slovakia",
    "Belgium", "Italy", "Latvia", "Malta", "Greece", "France",
    "Greece", "Netherlands", "France", "Slovenia", "Latvia",
    "Finland", "Austria", "Slovenia", "Belgium", "Cyprus", "Greece",
    "Slovenia", "Cyprus", "Finland", "Malta", "Germany"), weight = c(3.63689639539779e-09,
    2.36155345798604e-11, 1.90981717262912e-08, 1.27550515412245e-09,
    2.75032212941667e-09, 3.79663088493923e-08, 1.42368280746262e-08,
    1.51146811601353e-08, 1.75314892144034e-09, 2.07956027448449e-08,
    1.38623943876156e-07, 1.92893849444567e-08, 5.66419694274739e-08,
    5.8089561312222e-09, 1.95827364947702e-09, 6.7071674411728e-10,
    4.23667746162198e-09, 4.62966220873406e-08, 1.21403390886489e-07,
    1.26979107479853e-08, 5.59978765605208e-07, 3.14788992090851e-09,
    5.0058794053616e-07, 5.22186410794211e-09, 9.21607337940845e-10,
    2.51322812227745e-09, 3.04984607426863e-07, 3.20992561385791e-09,
    8.92180336424503e-10, 6.12766236972513e-08, 1.20231538847898e-08,
    1.34589665048046e-07, 8.84238627642763e-10, 2.63370671763944e-11,
    1.11903749128791e-09, 1.16731679208085e-08, 4.99654438989995e-08,
    2.90162442064053e-08, 2.55621731534268e-09, 1.58298464637584e-10,
    5.07475932446428e-08, 2.54927518867625e-09, 2.24427326793633e-10,
    4.49723284363684e-09, 2.43010060636845e-06, 1.90760030501003e-08,
    6.35902610582491e-08, 5.48833215255332e-10, 4.06612010446768e-10,
    5.32889353797193e-10, 1.23745070305762e-06, 8.89608483306497e-07,
    3.75876719292064e-09, 4.44758324449273e-07, 1.35536579831994e-07,
    5.42265922046125e-11, 4.8233448207134e-11, 3.4286615533894e-07,
    2.0214285544428e-10, 8.57988303618593e-10, 1.35631258148319e-09,
    7.97944858545598e-10, 4.2673026648725e-09, 9.28491399244895e-08,
    1.03420112425729e-09, 2.4972909387896e-08, 8.12118760999133e-07,
    1.31225365800221e-08, 1.77287287047586e-09, 6.53958727055997e-09,
    3.05841917976996e-10, 9.20687775127977e-09, 4.32323785012335e-07,
    8.40653865200987e-10, 1.23500809608508e-10, 6.59008808575339e-08,
    1.13962199159936e-09, 4.68300414991578e-10, 3.54758342726504e-11,
    6.55880483863129e-10, 1.17833628272869e-08, 5.08802989644665e-07,
    7.22191649442396e-07, 2.7028184600344e-10, 2.2810918951755e-10,
    8.10987753872438e-10, 1.50406384816011e-09, 5.46176491471454e-06,
    2.32716789835402e-08, 2.10873259303399e-10, 1.81735402994258e-09,
    9.71369590422109e-09, 2.01941765282435e-08, 1.8961914804496e-07,
    9.4461402995167e-09, 1.69816623519093e-07, 9.16774899583353e-08,
    8.54588845128718e-10, 4.79160495478785e-08, 2.31994460360924e-11
    )), row.names = c(NA, -100L), class = c("tbl_df", "tbl",
"data.frame"))
actors= c("Slovakia", "Germany", "Portugal", "Austria", "Latvia", "Cyprus",
"Greece", "Italy", "Slovenia", "Ireland", "Malta", "Luxembourg",
"France", "Netherlands", "Spain", "Belgium", "Finland", "Lithuania",
"Estonia")
g <- graph_from_data_frame(relations, directed=TRUE, vertices=actors)

by using package igraph. Using function closeness I obtain:

closeness(g)
   Slovakia     Germany    Portugal     Austria      Latvia      Cyprus      Greece       Italy    Slovenia     Ireland
    4002492     7111002     6478738     6502665     2017834     1029940     6615891     7164685     5533119     6240785
      Malta  Luxembourg      France Netherlands       Spain     Belgium     Finland   Lithuania     Estonia
    5071100     7243749     6342911     7121291     7144000     7090895     6415382     3086085     7411727

I would like to obtain a normalized closeness score bounded between 0 and 1. It is 0 if a node is an isolate, and 1 if a node is directly connected all others. What can I do

Body:
In the function, you can call for "normalized = TRUE" because it is "FALSE" by default. Sidenote: It is helpful if you add the code you used to calculate closeness.

closeness(
  graph,
  vids = V(graph),
  mode = c("out", "in", "all", "total"),
  weights = NULL,
  normalized = TRUE
)


问:
ModuleNotFoundError: no module named 'transformers'
this is my first post and I am very new to coding so please let me know if you need more information. I have been running some AI to generate artwork and it has been working but when I reloaded it the script won't work and it is now saying "No module named 'transformers'". Can anyone help me out? It was when I upgraded to google colab pro that I started to encounter issues although I am not sure why that would make a difference

ModuleNotFoundError

答:
Assuming you are referring to the module here https://pypi.org/project/transformers/
you need to install transformers with pip</p>
```<code>pip install transformers
</code>```

Body:
Assuming you are referring to the module here https://pypi.org/project/transformers/
you need to install transformers with pip

pip install transformers


问:
React state gets updated visually, but the state variable does not get updated when accessing through useContext
There are a lot of different posts about state not updating, but I haven't found any that apply to my case.

In my index.js file, I have 2 useState hooks and all the components are wrapped inside the <Context.Provider> tag with the state values and setters as shown below:

```<code>                <Context.Provider
                    value={{
                        state1,
                        setState1,
                        state2,
                        setState2,
                    }}
                >
                    <OtherComponent1 />
                    <OtherComponent2 />
                </Context.Provider>
</code>```

in another component, I've imported the values from the context like this:

```<code>    const {
        state1,
        setState2,
        state2,
        setState2,
    } = useContext(Context);
</code>```

I can use both the state and the state setters perfectly, except when I set the state, I can see the visual changes, except the variable value doesn't change.

state1 is an array, and when I do setState1(updatedArray), I can see visually that the state is updated, but when I console.log(state1), I still only see the original value of state1, not updatedArray. How can I fix this?

Also, when I do useEffect(() => console.log(state1), [state1]), I see the correct updated value of state1. This confuses me even more because this is the only place where I can see the correct value of state1, but I need the correct value elsewhere.

答: as Ivo mentioned you should use console log outside the function to check for the state of teamRankings. The function holds the previous data and by extension console log prints the previous state. Thats why useEffect works, because it checks that the state changed and re runs the effect</p>

Body:
There are a lot of different posts about state not updating, but I haven't found any that apply to my case.

In my index.js file, I have 2 useState hooks and all the components are wrapped inside the <Context.Provider> tag with the state values and setters as shown below:

                <Context.Provider
                    value={{
                        state1,
                        setState1,
                        state2,
                        setState2,
                    }}
                >
                    <OtherComponent1 />
                    <OtherComponent2 />
                </Context.Provider>

in another component, I've imported the values from the context like this:

    const {
        state1,
        setState2,
        state2,
        setState2,
    } = useContext(Context);

I can use both the state and the state setters perfectly, except when I set the state, I can see the visual changes, except the variable value doesn't change.

state1 is an array, and when I do setState1(updatedArray), I can see visually that the state is updated, but when I console.log(state1), I still only see the original value of state1, not updatedArray. How can I fix this?

Also, when I do useEffect(() => console.log(state1), [state1]), I see the correct updated value of state1. This confuses me even more because this is the only place where I can see the correct value of state1, but I need the correct value elsewhere.


问:
Basic firestore query in flutter returns empty snapshot
I tried to do a simple firestore query in flutter, however it always returns an empty snapshot. With the collection categories it already worked. The code for the products was actually only copy pasted.

```<code>import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:foodandfast/services/models.dart';

class FirestoreService {
  final FirebaseFirestore _db = FirebaseFirestore.instance;

  Future<List<Category>> getCategories() async {
    var ref = _db.collection("categories");
    var snapshot = await ref.orderBy("name", descending: false).get();
    var data = snapshot.docs.map((s) {
      var element = s.data();
      element\["id"\] = s.id;
      element\["imageName"\] += ".png";
      return element;
    });
    var categories = data.map((d) => Category.fromJson(d));
    return categories.toList();
  }

  Future<List<Product>> getProducts(String categoryId) async {
    var ref = FirebaseFirestore.instance.collection("products");
    var snapshot = await ref
        .orderBy("name", descending: false)
        .where('categoryId', isEqualTo: categoryId)
        .get();
    print(snapshot.docs.length);
    var data = snapshot.docs.map((s) {
      var element = s.data();
      element\["id"\] = s.id;
      element\["imageName"\] += ".png";
      return element;
    });
    var products = data.map((d) => Product.fromJson(d));
    return products.toList();
  }
}]
</code>```

Firestore database

答:
There is no categoryId field in Products collections, thats why getProducts() returns empty.

however, firebase is noSQL database, unlike SQL you can't apply the principle of foreign key in noSQL.

you need to learn more about data modeling in noSQL database.

Body:
I tried to do a simple firestore query in flutter, however it always returns an empty snapshot. With the collection categories it already worked. The code for the products was actually only copy pasted.

import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:foodandfast/services/models.dart';

class FirestoreService {
  final FirebaseFirestore _db = FirebaseFirestore.instance;

  Future<List<Category>> getCategories() async {
    var ref = _db.collection("categories");
    var snapshot = await ref.orderBy("name", descending: false).get();
    var data = snapshot.docs.map((s) {
      var element = s.data();
      element\["id"\] = s.id;
      element\["imageName"\] += ".png";
      return element;
    });
    var categories = data.map((d) => Category.fromJson(d));
    return categories.toList();
  }

  Future<List<Product>> getProducts(String categoryId) async {
    var ref = FirebaseFirestore.instance.collection("products");
    var snapshot = await ref
        .orderBy("name", descending: false)
        .where('categoryId', isEqualTo: categoryId)
        .get();
    print(snapshot.docs.length);
    var data = snapshot.docs.map((s) {
      var element = s.data();
      element\["id"\] = s.id;
      element\["imageName"\] += ".png";
      return element;
    });
    var products = data.map((d) => Product.fromJson(d));
    return products.toList();
  }
}]

Firestore database


问:
C++ different values in local function vs main function
I'm trying to write a function that parses a file including a 2d array size 2x2 (first line of file has the first row, second line has the second row) then an empty space, then values to be put in a vector, then an empty space, then an integer value.

I was able to read the values in and verify within the local function that the right data is coming in.. but when I try to print some of the values in my main function, the integer value is always showing up as 0, and the value from the vector I'm trying to print does not show up in the output stream at all and the program just terminates.. The 2d array value has no issues in the main function or in the local function, just the integer and vector values.

Here is an example of my input file:

```<code>-2.000 5.003
3.020 8.000

2.000
5.005
1.000
6.500
4.000
1.008
7.000
3.009

4
</code>```

And a copy of the code I am having issues with:

```<code>#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
#include <string.h>
using namespace std;

double arr_2x2[2][2];
vector<double> input_vector;
int input_int = 0;

void parse_input_file(string file_in, double arr_2x2[2][2], vector<double> input_vector, int input_int ){

  fstream infile;
  int empty_line = 0;
  infile.open (file_in, ios::in);
  if (infile.is_open()){   //checking whether the file is open
      string tp;
      for (int i = 0; i < 2; i++)
      {
        /* first two lines include the 2d array values */

          getline(infile, tp, ' ');
          //cout << tp << "\n";
          arr_2x2[i][0] = stod(tp);
          getline(infile, tp);
          //cout << tp << "\n";
          arr_2x2[i][1] = stod(tp);
      }
      //empty line.. throw it out
      getline(infile, tp);
      while(getline(infile, tp)){ //read data from file object and put it into string.
          if(!tp.size()){//if there is an empty line assert a flag
            empty_line = 1;
          }else{
            if(empty_line == 1){
              input_int = stoi(tp);//empty line asserted so int value
            }else{
              input_vector.push_back(stod(tp));
            }
          }

      }
      infile.close();
      printf("matrix value: %.3lf\n",arr_2x2[0][0]);
      printf("vector value: %.3lf\n",input_vector[1]);
      printf("integer value: %d\n",input_int);
  }

}

int main (int argc, char** argv) {
  string file_in  = string(argv[2]);
  parse_input_file(file_in, arr_2x2, input_vector, input_int);
  printf("matrix value: %.3lf\n",arr_2x2[0][0]);
  printf("integer value: %d\n",input_int);
  printf("vector value: %.3lf\n",input_vector[1]);

  return 0;
}
</code>```

答:
```<code>double arr_2x2[2][2];
vector<double> input_vector;
</code>```

The shown code first declares arr_2x2 and input_vectors in global scope. Global scope means that these objects are accessible in every function, without having to pass them as parameters.

```<code>void parse_input_file(string file_in, double arr_2x2[2][2], vector<double> input_vector, int input_int ){
</code>```

The shown code then declares a parse_input_file function. Two of its parameters have the exact same names as global objects. This always leads to confusion, and hard to identify bugs. If the intent is to pass the two global objects here as parameters to this function, this will accomplish absolutely nothing useful, whatsoever, except to create confusion. arr_2x2 and input_vector are already global. Every function can access them. Passing them as parameters is not needed.

```<code>parse_input_file(file_in, arr_2x2, input_vector, input_int);
</code>```

Predictably, main() calls this function and passes the two global objects by value, creating this confusion. input_vector gets passed by value, as I already mentioned. This means, effectively, that the function gets a duplicate copy of the global object (because that's what passing by value means). Any changes the function makes to what it knows as na input_vector will mysteriously disappear when the function returns, and won't appear in the global object.

As best practice: don't name parameters to functions with the same name as global objects. And when you do need to pass non-global objects to functions as parameters you need to fully understand the differences between passing them by value or by reference, see your C++ textbook for more information.

Body:
I'm trying to write a function that parses a file including a 2d array size 2x2 (first line of file has the first row, second line has the second row) then an empty space, then values to be put in a vector, then an empty space, then an integer value.

I was able to read the values in and verify within the local function that the right data is coming in.. but when I try to print some of the values in my main function, the integer value is always showing up as 0, and the value from the vector I'm trying to print does not show up in the output stream at all and the program just terminates.. The 2d array value has no issues in the main function or in the local function, just the integer and vector values.

Here is an example of my input file:

-2.000 5.003
3.020 8.000

2.000
5.005
1.000
6.500
4.000
1.008
7.000
3.009

4

And a copy of the code I am having issues with:

#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
#include <string.h>
using namespace std;

double arr_2x2[2][2];
vector<double> input_vector;
int input_int = 0;

void parse_input_file(string file_in, double arr_2x2[2][2], vector<double> input_vector, int input_int ){

  fstream infile;
  int empty_line = 0;
  infile.open (file_in, ios::in);
  if (infile.is_open()){   //checking whether the file is open
      string tp;
      for (int i = 0; i < 2; i++)
      {
        /* first two lines include the 2d array values */

          getline(infile, tp, ' ');
          //cout << tp << "\n";
          arr_2x2[i][0] = stod(tp);
          getline(infile, tp);
          //cout << tp << "\n";
          arr_2x2[i][1] = stod(tp);
      }
      //empty line.. throw it out
      getline(infile, tp);
      while(getline(infile, tp)){ //read data from file object and put it into string.
          if(!tp.size()){//if there is an empty line assert a flag
            empty_line = 1;
          }else{
            if(empty_line == 1){
              input_int = stoi(tp);//empty line asserted so int value
            }else{
              input_vector.push_back(stod(tp));
            }
          }

      }
      infile.close();
      printf("matrix value: %.3lf\n",arr_2x2[0][0]);
      printf("vector value: %.3lf\n",input_vector[1]);
      printf("integer value: %d\n",input_int);
  }

}

int main (int argc, char** argv) {
  string file_in  = string(argv[2]);
  parse_input_file(file_in, arr_2x2, input_vector, input_int);
  printf("matrix value: %.3lf\n",arr_2x2[0][0]);
  printf("integer value: %d\n",input_int);
  printf("vector value: %.3lf\n",input_vector[1]);

  return 0;
}

Body:
double arr_2x2[2][2];
vector<double> input_vector;

The shown code first declares arr_2x2 and input_vectors in global scope. Global scope means that these objects are accessible in every function, without having to pass them as parameters.

void parse_input_file(string file_in, double arr_2x2[2][2], vector<double> input_vector, int input_int ){

The shown code then declares a parse_input_file function. Two of its parameters have the exact same names as global objects. This always leads to confusion, and hard to identify bugs. If the intent is to pass the two global objects here as parameters to this function, this will accomplish absolutely nothing useful, whatsoever, except to create confusion. arr_2x2 and input_vector are already global. Every function can access them. Passing them as parameters is not needed.

parse_input_file(file_in, arr_2x2, input_vector, input_int);

Predictably, main() calls this function and passes the two global objects by value, creating this confusion. input_vector gets passed by value, as I already mentioned. This means, effectively, that the function gets a duplicate copy of the global object (because that's what passing by value means). Any changes the function makes to what it knows as na input_vector will mysteriously disappear when the function returns, and won't appear in the global object.

As best practice: don't name parameters to functions with the same name as global objects. And when you do need to pass non-global objects to functions as parameters you need to fully understand the differences between passing them by value or by reference, see your C++ textbook for more information.


问:
reinit.pas translated to C++
I have semi-successfully translated reinit.pas to C++ to use it in my project. The part where int __fastcall LoadNewResourceModule(LCID locale); is called works fine, in fact I can even call it prior to Application->Initialize() and it will load the proper language at startup. However, the part that calls void __fastcall ReinitializeForms(void); does not work, and gives a runtime error:

Resource TControl not found

Here is the dirty version of .cpp, and .h, I've yet to clean it up and comment it properly, at this point the thing just has to work fully. Please help me sort this out.

//---------------------------------------------------------------------------

#include <System.Classes.hpp>
#include <SysInit.hpp>
#include <Vcl.Forms.hpp>
#pragma hdrstop

#include "reinit.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)

class TAsInheritedReader : public TReader
{
  public:
    void __fastcall ReadPrefix(TFilerFlags &_flags, int &_aChildPos);
    inline __fastcall TAsInheritedReader(TStream* Stream, int BufSize) : TReader(Stream, BufSize) {}
};

//---------------------------------------------------------------------------
void __fastcall TAsInheritedReader::ReadPrefix(TFilerFlags &_flags, int &_aChildPos)
{
  TReader::ReadPrefix(_flags, _aChildPos);
  _flags = _flags << ffInherited;
}

//---------------------------------------------------------------------------
int __fastcall SetResourceHInstance(int _newInstance)
{
  PLibModule CurModule = LibModuleList;

  while(CurModule != NULL) {
      if (reinterpret_cast<void*>(CurModule->Instance) == HInstance) {
          if (CurModule->ResInstance != CurModule->Instance) {
              FreeLibrary(reinterpret_cast<HMODULE>(CurModule->ResInstance));
              CurModule->ResInstance = _newInstance;
              return _newInstance;
          }

          CurModule = CurModule->Next;
      }
  }

  return 0;
}

//---------------------------------------------------------------------------
int __fastcall LoadNewResourceModule(LCID locale)
{
  wchar_t FileName[260];
  PChar P;
  wchar_t LocaleName[4];
  int NewInst = 0;

  GetModuleFileName(HInstance, FileName, sizeof(FileName));
  GetLocaleInfo(locale, LOCALE_SABBREVLANGNAME, LocaleName, sizeof(LocaleName));

  P = PChar(&FileName) + lstrlen(FileName);

  while((*P != L'.') && (P != reinterpret_cast<PChar>(&FileName))) {
      --P;
  }

  if (P != reinterpret_cast<PChar>(&FileName)) {
      ++P;

      if (LocaleName[0] != L'\0') {
          NewInst = reinterpret_cast<int>(LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE));

          if (NewInst == 0) {
              LocaleName[2] = L'\0';
              lstrcpy(P, LocaleName);
              NewInst = reinterpret_cast<int>(LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE));
          }
      }
  }

  if (NewInst != 0) {
      return SetResourceHInstance(NewInst);
  }

  return 0;
}

//---------------------------------------------------------------------------
bool __fastcall InternalReloadComponentRes(const String ResName, THandle HInst, TComponent* Instance)
{
  //TResourceStream* ResStream = new TResourceStream;
  //TAsInheritedReader* AsInheritedReader = new TAsInheritedReader;

  if (HInst == 0) {
      HInst = reinterpret_cast<THandle>(HInstance);
  }

  THandle HRsrc = reinterpret_cast<THandle>(FindResource((HMODULE)HInst, (LPCWSTR)ResName.w_str(), (LPCWSTR)RT_RCDATA));

  if(HRsrc != 0) {
      return false;
  }

  /* THIS IS THE OFFENDING LINE OF CODE THAT THROWS EXCEPTION
     I checked HInst, it is not 0...
     ResName = "TControl"
     and it throws exception here for some reason
     saying resource tcontrol not found
 */
  TResourceStream* ResStream = new TResourceStream(HInst, ResName, RT_RCDATA);

  try {
      TAsInheritedReader* AsInheritedReader = new TAsInheritedReader(ResStream, 4096);

      try {
          Instance = AsInheritedReader->ReadRootComponent(Instance);
      } __finally {
          delete AsInheritedReader;
      }
  }
  __finally {
      delete ResStream;
  }

  return true;
}

//---------------------------------------------------------------------------
bool __fastcall InitComponent(TClass ClassType)
{
  if ((ClassType->ClassName() == "TComponent") || (ClassType->ClassName() == "RootAncestor")) {
      return false;
  }

  InitComponent(ClassType->ClassParent());
  return InternalReloadComponentRes(ClassType->ClassName(), FindResourceHInstance(FindClassHInstance(ClassType)), (TComponent*)&ClassType);
}

//---------------------------------------------------------------------------
bool __fastcall ReloadInheritedComponent(TComponent* Instance)
{
  return InitComponent(Instance->ClassType());
}

//---------------------------------------------------------------------------
void __fastcall ReinitializeForms(void)
{
  for(int i=0; i<Screen->FormCount-1; i++) {
      ReloadInheritedComponent(Screen->Forms[i]);
  }

}

#ifndef _reinit_h
#define _reinit_h

#include <windows.h>

extern int __fastcall LoadNewResourceModule(LCID locale);
extern void __fastcall ReinitializeForms(void);

#endif
```

答:
You don't really need to translate the code at all.  You can use Delphi .pas units as-is in C++Builder projects.  Simply add the .pas file to your project and compile it, the IDE will generate a .hpp file that you can then #include in your C++ code.

In any case, your translation is not correct in many places.

For instance, the original code wasn't written with Unicode in mind, but you are using Unicode strings in your code. Expressions like sizeof(FileName) and sizeof(LocaleName) are the wrong buffer sizes to pass to the Win32 APIs being used, which can potentially allow buffer overflows.  The code was clearly expecting BYTE-sized narrow characters, not WORD-sized wide characters.

It also looks like the original code was not written with 64-bit in mind, either. It is using 32-bit integers in places where 64-bit integers would be needed (for resource handles, etc).

So, the original code needs some updating to support modern systems properly.

But also, your translation of InitComponent() is wrong. It is using strings where the original code is using metaclass references instead, and it is passing the wrong value in the last parameter of InternalReloadComponentRes(), which you have not even declared correctly.

And also, your loop in ReinitializeForms() is skipping the last TForm in the Screen->Forms[] array.

Now, that all being said, try something more like this:

ReInit.h

#ifndef REINIT_H
#define REINIT_H

void __fastcall ReinitializeForms();
NativeUInt __fastcall LoadNewResourceModule(unsigned long Locale);

#endif
```
<p>ReInit.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include "ReInit.h"

#include <Windows.hpp>
#include <SysInit.hpp>
#include <SysUtils.hpp>
#include <Classes.hpp>
#include <Forms.hpp>

#include <memory>

class TAsInheritedReader : public TReader
{
public:
    void __fastcall ReadPrefix(TFilerFlags &Flags, int &AChildPos) override;
};

void __fastcall TAsInheritedReader::ReadPrefix(TFilerFlags &Flags, int &AChildPos)
{
    TReader::ReadPrefix(Flags, AChildPos);
    Flags << ffInherited;
}

NativeUInt __fastcall SetResourceHInstance(NativeUInt NewInstance)
{
    PLibModule CurModule = LibModuleList;
    while (CurModule)
    {
        if (CurModule->Instance == HInstance)
        {
            if (CurModule->ResInstance != CurModule->Instance)
                ::FreeLibrary(reinterpret_cast<HMODULE>(CurModule->ResInstance));
            CurModule->ResInstance = NewInstance;
            return NewInstance;
        }
        CurModule = CurModule->Next;
    }
    return 0;
}

NativeUInt __fastcall LoadNewResourceModule(unsigned long Locale)
{
    WCHAR FileName[MAX_PATH+1] = {};
    ::GetModuleFileNameW(reinterpret_cast<HMODULE>(HInstance), FileName, MAX_PATH+1);

    WCHAR LocaleName[5] = {};
    ::GetLocaleInfoW(Locale, LOCALE_SABBREVLANGNAME, LocaleName, 5);

    LPWSTR P = &FileName[lstrlenW(FileName)];
    while ((*P != L'.') && (P != FileName)) --P;

    HMODULE NewInst = nullptr;
    if (P != FileName)
    {
        ++P;
        if (LocaleName[0] != L'\0')
        {
            // Then look for a potential language/country translation
            lstrcpyW(P, LocaleName);
            NewInst = LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE);
            if (!NewInst)
            {
                // Finally look for a language only translation
                LocaleName[2] = L'\0';
                lstrcpyW(P, LocaleName);
                NewInst = LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE);
            }
        }
    }
    if (NewInst)
        return SetResourceHInstance(reinterpret_cast<NativeUInt>(NewInst));
    return 0;
}

bool __fastcall InternalReloadComponentRes(const UnicodeString &ResName, NativeUInt HInst, TComponent* &Instance)
{
    // avoid possible EResNotFound exception
    if (HInst == 0) HInst = HInstance;
    HRSRC HRsrc = FindResourceW(reinterpret_cast<HMODULE>(HInst), ResName.c_str(), MAKEINTRESOURCEW(10)/*RT_RCDATA*/);
    if (!HRsrc) return false;

    auto ResStream = std::make_unique<TResourceStream>(HInst, ResName, MAKEINTRESOURCEW(10)/*RT_RCDATA*/);

    auto AsInheritedReader = std::make_unique<TAsInheritedReader>(ResStream.get(), 4096);
    Instance = AsInheritedReader->ReadRootComponent(Instance);

    return true;
}

bool __fastcall ReloadInheritedComponent(TComponent *Instance, TClass RootAncestor)
{
    const auto InitComponent = [&Instance,RootAncestor](TClass ClassType) -> bool
    {
        auto InitComponent_impl = [&Instance,RootAncestor](TClass ClassType, auto& InitComponent_ref) -> bool
        {
            if ((ClassType == __classid(TComponent)) || (ClassType == RootAncestor)) return false;
            bool Result = InitComponent_ref(ClassType->ClassParent(), InitComponent_ref);
            return InternalReloadComponentRes(ClassType->ClassName(), FindResourceHInstance(FindClassHInstance(ClassType)), Instance) || Result;
        }
        return InitComponent_impl(ClassType, InitComponent_impl);
    }

    return InitComponent(Instance->ClassType());
}

void __fastcall ReinitializeForms()
{
    int Count = Screen->FormCount;
    for(int i = 0; i < Count; ++i)
    {
        ReloadInheritedComponent(Screen->Forms[I], __classid(TForm));
    }
}
</code>```

Title: reinit.pas translated to C++

Body:
You don't really need to translate the code at all.  You can use Delphi .pas units as-is in C++Builder projects.  Simply add the .pas file to your project and compile it, the IDE will generate a .hpp file that you can then #include in your C++ code.

In any case, your translation is not correct in many places.

For instance, the original code wasn't written with Unicode in mind, but you are using Unicode strings in your code. Expressions like sizeof(FileName) and sizeof(LocaleName) are the wrong buffer sizes to pass to the Win32 APIs being used, which can potentially allow buffer overflows.  The code was clearly expecting BYTE-sized narrow characters, not WORD-sized wide characters.

It also looks like the original code was not written with 64-bit in mind, either. It is using 32-bit integers in places where 64-bit integers would be needed (for resource handles, etc).

So, the original code needs some updating to support modern systems properly.

But also, your translation of InitComponent() is wrong. It is using strings where the original code is using metaclass references instead, and it is passing the wrong value in the last parameter of InternalReloadComponentRes(), which you have not even declared correctly.

And also, your loop in ReinitializeForms() is skipping the last TForm in the Screen->Forms[] array.

Now, that all being said, try something more like this:

ReInit.h

#ifndef REINIT_H
#define REINIT_H

void __fastcall ReinitializeForms();
NativeUInt __fastcall LoadNewResourceModule(unsigned long Locale);

#endif

ReInit.cpp

#include "ReInit.h"

#include <Windows.hpp>
#include <SysInit.hpp>
#include <SysUtils.hpp>
#include <Classes.hpp>
#include <Forms.hpp>

#include <memory>

class TAsInheritedReader : public TReader
{
public:
    void __fastcall ReadPrefix(TFilerFlags &Flags, int &AChildPos) override;
};

void __fastcall TAsInheritedReader::ReadPrefix(TFilerFlags &Flags, int &AChildPos)
{
    TReader::ReadPrefix(Flags, AChildPos);
    Flags << ffInherited;
}

NativeUInt __fastcall SetResourceHInstance(NativeUInt NewInstance)
{
    PLibModule CurModule = LibModuleList;
    while (CurModule)
    {
        if (CurModule->Instance == HInstance)
        {
            if (CurModule->ResInstance != CurModule->Instance)
                ::FreeLibrary(reinterpret_cast<HMODULE>(CurModule->ResInstance));
            CurModule->ResInstance = NewInstance;
            return NewInstance;
        }
        CurModule = CurModule->Next;
    }
    return 0;
}

NativeUInt __fastcall LoadNewResourceModule(unsigned long Locale)
{
    WCHAR FileName[MAX_PATH+1] = {};
    ::GetModuleFileNameW(reinterpret_cast<HMODULE>(HInstance), FileName, MAX_PATH+1);

    WCHAR LocaleName[5] = {};
    ::GetLocaleInfoW(Locale, LOCALE_SABBREVLANGNAME, LocaleName, 5);

    LPWSTR P = &FileName[lstrlenW(FileName)];
    while ((*P != L'.') && (P != FileName)) --P;

    HMODULE NewInst = nullptr;
    if (P != FileName)
    {
        ++P;
        if (LocaleName[0] != L'\0')
        {
            // Then look for a potential language/country translation
            lstrcpyW(P, LocaleName);
            NewInst = LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE);
            if (!NewInst)
            {
                // Finally look for a language only translation
                LocaleName[2] = L'\0';
                lstrcpyW(P, LocaleName);
                NewInst = LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE);
            }
        }
    }
    if (NewInst)
        return SetResourceHInstance(reinterpret_cast<NativeUInt>(NewInst));
    return 0;
}

bool __fastcall InternalReloadComponentRes(const UnicodeString &ResName, NativeUInt HInst, TComponent* &Instance)
{
    // avoid possible EResNotFound exception
    if (HInst == 0) HInst = HInstance;
    HRSRC HRsrc = FindResourceW(reinterpret_cast<HMODULE>(HInst), ResName.c_str(), MAKEINTRESOURCEW(10)/*RT_RCDATA*/);
    if (!HRsrc) return false;

    auto ResStream = std::make_unique<TResourceStream>(HInst, ResName, MAKEINTRESOURCEW(10)/*RT_RCDATA*/);

    auto AsInheritedReader = std::make_unique<TAsInheritedReader>(ResStream.get(), 4096);
    Instance = AsInheritedReader->ReadRootComponent(Instance);

    return true;
}

bool __fastcall ReloadInheritedComponent(TComponent *Instance, TClass RootAncestor)
{
    const auto InitComponent = [&Instance,RootAncestor](TClass ClassType) -> bool
    {
        auto InitComponent_impl = [&Instance,RootAncestor](TClass ClassType, auto& InitComponent_ref) -> bool
        {
            if ((ClassType == __classid(TComponent)) || (ClassType == RootAncestor)) return false;
            bool Result = InitComponent_ref(ClassType->ClassParent(), InitComponent_ref);
            return InternalReloadComponentRes(ClassType->ClassName(), FindResourceHInstance(FindClassHInstance(ClassType)), Instance) || Result;
        }
        return InitComponent_impl(ClassType, InitComponent_impl);
    }

    return InitComponent(Instance->ClassType());
}

void __fastcall ReinitializeForms()
{
    int Count = Screen->FormCount;
    for(int i = 0; i < Count; ++i)
    {
        ReloadInheritedComponent(Screen->Forms[I], __classid(TForm));
    }
}


问:
For Loop printing an element from an array more than once
For this question, I'm trying to make a code which filters out items which have already been purchased from the list. But my for loop is printing all the element from the Item List more than once while also simultaneously ignoring the if condition.

The input for my scanner is this:

5 apples oranges bananas peaches grapes oranges peaches DONE

The integer in the beginning is the size of my itemList array. Items which are repeated are considered as purchased. So oranges and peaches are purchased in this situation.

Here is my code:

```<code>    Scanner in = new Scanner(System.in);
    // 5 apples oranges bananas peaches grapes oranges peaches DONE

    int n = in.nextInt();
    String[] itemList = new String[n];
    String bought;
    String[] itemPurchased = new String[0];

    for(int i = 0; i < itemList.length; i++) {
        String item = in.next();
        itemList[i] = item;
    }
    if(in.hasNext()) {
        bought = in.nextLine();
        itemPurchased = bought.split(" ");
    }
    for(int i = 0; i < itemList.length; i++) {
        for(int j = 0; j < itemPurchased.length; j++) {
            if(!itemList[i].equals(itemPurchased[j])) {
                System.out.println(itemList[i]);
            }
        }
    }
</code>```

This is the output:

apples
apples
apples
apples
oranges
oranges
oranges
bananas
bananas
bananas
bananas
peaches
peaches
peaches
grapes
grapes
grapes
grapes

As you can see the output repeats all the elements in my itemList array 4 times while also including the items repeated from the input. How do I make it print all the element once excluding the items that have already been purchased?

答:
In the loop

```<code>    for(int i = 0; i < itemList.length; i++) {
        for(int j = 0; j < itemPurchased.length; j++) {
            if(!itemList[i].equals(itemPurchased[j])) {
                System.out.println(itemList[i]);
            }
        }
    }
</code>```

You are testing whether a given element in itemList is also in itemPurchased, and then when they do not match, you are printing the element. This means that you are printing it out every time you don't match the element, e.g., if you have {"apple", "banana", "orange"}, and test for "apple", you print it once each for "banana" and "orange".

What I would recommend is to remove the duplicates from itemPurchased, or rather, create a third array (or better still, an ArrayList<String>) with the duplicates removed.

Body:
For this question, I'm trying to make a code which filters out items which have already been purchased from the list. But my for loop is printing all the element from the Item List more than once while also simultaneously ignoring the if condition.

The input for my scanner is this:

5 apples oranges bananas peaches grapes oranges peaches DONE

The integer in the beginning is the size of my itemList array. Items which are repeated are considered as purchased. So oranges and peaches are purchased in this situation.

Here is my code:

    Scanner in = new Scanner(System.in);
    // 5 apples oranges bananas peaches grapes oranges peaches DONE

    int n = in.nextInt();
    String[] itemList = new String[n];
    String bought;
    String[] itemPurchased = new String[0];

    for(int i = 0; i < itemList.length; i++) {
        String item = in.next();
        itemList[i] = item;
    }
    if(in.hasNext()) {
        bought = in.nextLine();
        itemPurchased = bought.split(" ");
    }
    for(int i = 0; i < itemList.length; i++) {
        for(int j = 0; j < itemPurchased.length; j++) {
            if(!itemList[i].equals(itemPurchased[j])) {
                System.out.println(itemList[i]);
            }
        }
    }

This is the output:

apples
apples
apples
apples
oranges
oranges
oranges
bananas
bananas
bananas
bananas
peaches
peaches
peaches
grapes
grapes
grapes
grapes

As you can see the output repeats all the elements in my itemList array 4 times while also including the items repeated from the input. How do I make it print all the element once excluding the items that have already been purchased?

Body:
In the loop

    for(int i = 0; i < itemList.length; i++) {
        for(int j = 0; j < itemPurchased.length; j++) {
            if(!itemList[i].equals(itemPurchased[j])) {
                System.out.println(itemList[i]);
            }
        }
    }

You are testing whether a given element in itemList is also in itemPurchased, and then when they do not match, you are printing the element. This means that you are printing it out every time you don't match the element, e.g., if you have {"apple", "banana", "orange"}, and test for "apple", you print it once each for "banana" and "orange".

What I would recommend is to remove the duplicates from itemPurchased, or rather, create a third array (or better still, an ArrayList<String>) with the duplicates removed.


答: Probably it is because you have not installed in your (new, since you've upgraded to colabs pro) session the library transformers. Try to run as first cell the following: !pip install transformers (the "!" at the beginning of the instruction is needed to go into "terminal mode" ). This will download the transformers package into the session's environment.

Title: ModuleNotFoundError: no module named 'transformers'

Body:
this is my first post and I am very new to coding so please let me know if you need more information. I have been running some AI to generate artwork and it has been working but when I reloaded it the script won't work and it is now saying "No module named 'transformers'". Can anyone help me out? It was when I upgraded to google colab pro that I started to encounter issues although I am not sure why that would make a difference

ModuleNotFoundError


问:
How to autosize and right-align GridViewColumn data in WPF?
How can I:

right-align the text in the ID column

make each of the columns auto size according to the text length of the cell with the longest visible data?

Here is the code:

```<code><ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Id}" Width="40"/>
            <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="100" />
            <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}"/>
        </GridView>
    </ListView.View>
</ListView>
</code>```

partial answer:

Thanks Kjetil, the GridViewColumn.CellTemplate works well and the Auto Width works of course but when the ObservativeCollection "Collection" is updated with longer-than-column-width data, the column sizes do not update themselves so that is only a solution for the initial display of data:

```<code><ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="ID" Width="Auto">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Id}" TextAlignment="Right" Width="40"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" />
            <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/>
        </GridView>
    </ListView.View>
</ListView>
</code>```

答:
Auto sizing a column to the longest text can be archived by disabling virtualisation and setting Width="Auto" on the GridViewColumn.

```<code><ListView ItemsSource="{Binding ...}" VirtualizingStackPanel.IsVirtualizing="False">
    <ListView.View>
        <GridView>
            <GridViewColumn Width="Auto"
                            DisplayMemberBinding="{Binding Name}"
                            Header="Name"/>
        </GridView>
    </ListView.View>
</ListView>
</code>```

Virtualization is enabled by default and means that only visible rows are rendered. This is good for performance. The downside is that only the currently visible rows are used to calculate the column width (Width="Auto"). Disabling Virtualization means that all rows are rendered even if a row is not visible at the moment. The result is that Auto width calculation considers the values of all rows.

OwnerDisplayName: Edward Tanguay

ContentLicense: CC BY-SA 2.5

Body:
How can I:

right-align the text in the ID column

make each of the columns auto size according to the text length of the cell with the longest visible data?

Here is the code:

<ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Id}" Width="40"/>
            <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="100" />
            <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}"/>
        </GridView>
    </ListView.View>
</ListView>

partial answer:

Thanks Kjetil, the GridViewColumn.CellTemplate works well and the Auto Width works of course but when the ObservativeCollection "Collection" is updated with longer-than-column-width data, the column sizes do not update themselves so that is only a solution for the initial display of data:

<ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="ID" Width="Auto">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Id}" TextAlignment="Right" Width="40"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" />
            <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/>
        </GridView>
    </ListView.View>
</ListView>

LastEditorDisplayName: Edward Tanguay

Body:
Auto sizing a column to the longest text can be archived by disabling virtualisation and setting Width="Auto" on the GridViewColumn.

<ListView ItemsSource="{Binding ...}" VirtualizingStackPanel.IsVirtualizing="False">
    <ListView.View>
        <GridView>
            <GridViewColumn Width="Auto"
                            DisplayMemberBinding="{Binding Name}"
                            Header="Name"/>
        </GridView>
    </ListView.View>
</ListView>

Virtualization is enabled by default and means that only visible rows are rendered. This is good for performance. The downside is that only the currently visible rows are used to calculate the column width (Width="Auto"). Disabling Virtualization means that all rows are rendered even if a row is not visible at the moment. The result is that Auto width calculation considers the values of all rows.


问:
How to retrieve Keycloak client roles in Spring Security
I am developing a Spring boot application which authenticates with Keycloak. I want to protect my REST endpoints, all are matching "/api/**". The rest is permitAll.
I can easily authorize requests by the below code snippet, but it only works with Keycloak's realm role, it does not work with client role.

```<code>private void configureMyRole(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers("/api/**").hasAnyRole("MyClientRole")
    .anyRequest().permitAll();
}
</code>```

Both the realm and client roles are available in the JWT token, but how should I handle it in Java? How can I retrieve it?

{
    "jti": "ae1043ca-db2b-4cbd-88dd-d6a7017db92f",
    "exp": 1633563788,
    "rest": "omitted",
    "realm_access": {
        "roles": [
            "MyRealmRole",
            "offline_access",
            "uma_authorization"
        ]
    },
    "resource_access": {
        "myproject": {
            "roles": [
                "MyClientRole"
            ]
        },
        "account": {
            "roles": [
                "manage-account",
                "manage-account-links",
                "view-profile"
            ]
        }
    },
    "rest": "omitted"
}
```

I am sure I could come up with some home made approach, parsing the token myself in some filter, but I better not ... :D

答:
Just recently i got the same issue, I've tried to convert it to an ObjectNode directly but, it seems that Claims can only be converted to a LinkedHashMap using Jackson.
In my case I needed to get a String[] of roles to be used later within my WebSecurityConfigurerAdapter.

```<code>Claims claims = Jwts.parser()
        .setSigningKey(publicKey)
        .parseClaimsJws(token)
        .getBody();

ObjectNode y = mapper.convertValue(mapper.convertValue(claims.get("resource_access")
        , LinkedHashMap.class)
        , ObjectNode.class);

return StreamSupport.stream(y.get("myproject").get("roles").spliterator(), false)
        .map(JsonNode::asText)
        .toArray(String[]::new);
</code>```

Body:
I am developing a Spring boot application which authenticates with Keycloak. I want to protect my REST endpoints, all are matching "/api/**". The rest is permitAll.
I can easily authorize requests by the below code snippet, but it only works with Keycloak's realm role, it does not work with client role.

private void configureMyRole(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers("/api/**").hasAnyRole("MyClientRole")
    .anyRequest().permitAll();
}

Both the realm and client roles are available in the JWT token, but how should I handle it in Java? How can I retrieve it?

{
    "jti": "ae1043ca-db2b-4cbd-88dd-d6a7017db92f",
    "exp": 1633563788,
    "rest": "omitted",
    "realm_access": {
        "roles": [
            "MyRealmRole",
            "offline_access",
            "uma_authorization"
        ]
    },
    "resource_access": {
        "myproject": {
            "roles": [
                "MyClientRole"
            ]
        },
        "account": {
            "roles": [
                "manage-account",
                "manage-account-links",
                "view-profile"
            ]
        }
    },
    "rest": "omitted"
}

I am sure I could come up with some home made approach, parsing the token myself in some filter, but I better not ... :D

Body:
Just recently i got the same issue, I've tried to convert it to an ObjectNode directly but, it seems that Claims can only be converted to a LinkedHashMap using Jackson.
In my case I needed to get a String[] of roles to be used later within my WebSecurityConfigurerAdapter.

Claims claims = Jwts.parser()
        .setSigningKey(publicKey)
        .parseClaimsJws(token)
        .getBody();

ObjectNode y = mapper.convertValue(mapper.convertValue(claims.get("resource_access")
        , LinkedHashMap.class)
        , ObjectNode.class);

return StreamSupport.stream(y.get("myproject").get("roles").spliterator(), false)
        .map(JsonNode::asText)
        .toArray(String[]::new);


问:
How do i make a form around a div box
I created a small box div containing an image and a text beside each other. But I don't know how I can add a form around it that when I hover on any part of the box it would click on submit.

.trust-box {
  width: 200px;
  height: 80px;
  margin: 20px;
  background: #fff;
  color: #000;
  border-radius: 5px;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="trust-box">
  <img src="https://images.pexels.com/photos/34299/herbs-flavoring-seasoning-cooking.jpg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="trust" width="50" height="50">
  <span>Portis Wallet</span>
</div></code>```

And again how do I make the image and the text align horizontally inside the box? The div box image.

答:
You should try making it a button

```<code><button type="button" class="trust-box">
  Portis Wallet
  <img src="images/Portis.png" alt="trust" width="50" height="50">
</button>
</code>```

Aligning the image you can try either margin-top or top

Title: How do i make a form around a div box

Body:
I created a small box div containing an image and a text beside each other. But I don't know how I can add a form around it that when I hover on any part of the box it would click on submit.

.trust-box {
  width: 200px;
  height: 80px;
  margin: 20px;
  background: #fff;
  color: #000;
  border-radius: 5px;
  text-align: center;
}

  Portis Wallet

And again how do I make the image and the text align horizontally inside the box? The div box image.

Body:
You should try making it a button

<button type="button" class="trust-box">
  Portis Wallet
  <img src="images/Portis.png" alt="trust" width="50" height="50">
</button>

Aligning the image you can try either margin-top or top


问:
Stack per two columns and two measures
I have data that looks something like this:

```<code>order_id     Product_A    Product_B    Price_Product_A    Price_Product_B
100          Pen          Notebook     1.5                3
101          Bag          Watch        10                 12
</code>```

I need it to look like this:

```<code>order_id    product    price
100         Pen        1.5
100         Notebook   3
101         Bag        10
101         Watch      12
</code>```

How can I use stack() and unstack() for this? I used it so fat only for one numeric measure.

答:
There is a convenient function for this, wide_to_long:

```<code>pd.wide_to_long(df, ['Product','Price_Product'], i='order_id', j='subtype', sep = '_', suffix = '\D+')
</code>```

output:

```<code>                     Product        Price_Product
order_id    subtype
100         A        Pen            1.5
101         A        Bag            10.0
100         B        Notebook       3.0
101         B        Watch          12.0
</code>```

The same can be achieved with melt and unstack, which could be of instructional value. A somewhat tricky bit is to split 'variable' into two parts, the root and the suffix, something wide_to_long helps you with. For your example case this can look like this:

```<code>df1 = df.melt(id_vars = 'order_id')
df1['cat'] = df1['variable'].str[:-2]     # you may have to tweak this for your actual data
df1['subtype'] = df1['variable'].str[-1:] # you may have to tweak this for your actual data
(df1.drop(columns = 'variable')
    .set_index(['order_id','subtype','cat'])
    .unstack()
    .droplevel(level=0, axis=1)
    .reset_index()
)
</code>```

Title: Stack per two columns and two measures

Body:
I have data that looks something like this:

order_id     Product_A    Product_B    Price_Product_A    Price_Product_B
100          Pen          Notebook     1.5                3
101          Bag          Watch        10                 12

I need it to look like this:

order_id    product    price
100         Pen        1.5
100         Notebook   3
101         Bag        10
101         Watch      12

How can I use stack() and unstack() for this? I used it so fat only for one numeric measure.

Body:
There is a convenient function for this, wide_to_long:

pd.wide_to_long(df, ['Product','Price_Product'], i='order_id', j='subtype', sep = '_', suffix = '\D+')

output:

                     Product        Price_Product
order_id    subtype
100         A        Pen            1.5
101         A        Bag            10.0
100         B        Notebook       3.0
101         B        Watch          12.0

The same can be achieved with melt and unstack, which could be of instructional value. A somewhat tricky bit is to split 'variable' into two parts, the root and the suffix, something wide_to_long helps you with. For your example case this can look like this:

df1 = df.melt(id_vars = 'order_id')
df1['cat'] = df1['variable'].str[:-2]     # you may have to tweak this for your actual data
df1['subtype'] = df1['variable'].str[-1:] # you may have to tweak this for your actual data
(df1.drop(columns = 'variable')
    .set_index(['order_id','subtype','cat'])
    .unstack()
    .droplevel(level=0, axis=1)
    .reset_index()
)


问:
manipulating lists in python
Take three integers as input.

N1=123

N2=456

N3=789

Generate 4 digit password i.e. WXYZ.

Where

W is maximum digit of all the input numbers

X is the minimum of 100th position of all input numbers

Y is the minimum of 10th position of all input numbers

Z is the minimum of 1st position of all input numbers

Example:

N1=123

N2=456

N3=789

Password=WXYZ

W=maximum of 1,2,3,4,5,6,7,8,9 is 9

X= minimum of 1,4,7 is 1

Y=minimum of 2,5,8 is 2

Z=minimum of 3,6,9 is 3

4 digit password generated from given numbers is 9123

```<code>def add(x):
    a = []
    i = 2
    while x > 0:
        a[i] = x % 10
        x /= 10
        i -= 1
    return a

def password(x1, x2, x3):
    i = 0
    p = 0
    n = []

    n.append(add(x1))
    n.append(add(x2))
    n.append(add(x3))
    p = max(n) * 1000

    m = []
    for j in range(0, 9, 3):
        m.append(n[j])
    p += min(m) * 100

    m = []
    for j in range(1, 9, 3):
        m.append(n[j])
    p += min(m) * 10

    m = []
    for j in range(2, 9, 3):
        m.append(n[j])
    p += min(m)

    return p

print("Enter three numbers: ")
n1 = int(input())
n2 = int(input())
n3 = int(input())
print("Generated password: ", password(n1, n2, n3))

</code>```

I initially wrote this code in Java and it worked perfectly. I am trying to write it in Python and am getting this error. I'm new to Pythons so I'm not sure what I'm doing wrong. Please advice on how to correct my code.

a[i] = x % 10

IndexError: list assignment index out of range

p = max(n) * 1000

'>' not supported between instances of 'list' and 'int'

答:
The problem is, that you can't change a value of an item at an index of a list in python, where there currently is no item in the list at that index. That is why

```<code>a[i] = x%10
</code>```

won't work, if there are not i items in the list currently.
Additionally, your while-loop in the add-function won't ever come to an end, because if you divide an integer in python it gives you an integer or a float, depending on the outcome. Therefore x/10 won't ever be zero or smaller.

Title: manipulating lists in python

Body:
Take three integers as input.

N1=123

N2=456

N3=789

Generate 4 digit password i.e. WXYZ.

Where

W is maximum digit of all the input numbers

X is the minimum of 100th position of all input numbers

Y is the minimum of 10th position of all input numbers

Z is the minimum of 1st position of all input numbers

Example:

N1=123

N2=456

N3=789

Password=WXYZ

W=maximum of 1,2,3,4,5,6,7,8,9 is 9

X= minimum of 1,4,7 is 1

Y=minimum of 2,5,8 is 2

Z=minimum of 3,6,9 is 3

4 digit password generated from given numbers is 9123

def add(x):
    a = []
    i = 2
    while x > 0:
        a[i] = x % 10
        x /= 10
        i -= 1
    return a

def password(x1, x2, x3):
    i = 0
    p = 0
    n = []

    n.append(add(x1))
    n.append(add(x2))
    n.append(add(x3))
    p = max(n) * 1000

    m = []
    for j in range(0, 9, 3):
        m.append(n[j])
    p += min(m) * 100

    m = []
    for j in range(1, 9, 3):
        m.append(n[j])
    p += min(m) * 10

    m = []
    for j in range(2, 9, 3):
        m.append(n[j])
    p += min(m)

    return p

print("Enter three numbers: ")
n1 = int(input())
n2 = int(input())
n3 = int(input())
print("Generated password: ", password(n1, n2, n3))

I initially wrote this code in Java and it worked perfectly. I am trying to write it in Python and am getting this error. I'm new to Pythons so I'm not sure what I'm doing wrong. Please advice on how to correct my code.

a[i] = x % 10

IndexError: list assignment index out of range

p = max(n) * 1000

'>' not supported between instances of 'list' and 'int'

Body:
The problem is, that you can't change a value of an item at an index of a list in python, where there currently is no item in the list at that index. That is why

a[i] = x%10

won't work, if there are not i items in the list currently.
Additionally, your while-loop in the add-function won't ever come to an end, because if you divide an integer in python it gives you an integer or a float, depending on the outcome. Therefore x/10 won't ever be zero or smaller.


问:
css td overflow
I have a table. I one of the td I have some longer text. When the text hits the right border, it goes to the line. Normal. What I would like is nevertheless a little different. When the first line hits the border I want the overflow to be hidden and have the last 3 visible characters be replaced by "...". Hope someone can help. Thank you in advance for your replies. Cheers Marc.

Here the example:

```<code>http://cssdesk.com/3HTnq
</code>```

答:
Here's a little tweak.

    td {
        max-width:1px;         /* makes all the difference! */
        white-space:nowrap;
        overflow:hidden;
    }
```

Try it: https://codepen.io/dkellner/pen/MWObPgY

Apparently, if you use max-width and give it any numeric value, the browser suddenly understands that you're trying to cut the contents, but since it's not an explicit width, it will let the content grow. So it's kind of autosize plus crop, which was never possible as far as I remember. Again, not sure why literally any max-width value does the trick, max-width:1px should make it one single pixel wide; but it seems to work in all major browsers AND Microsoft Edge. (Sorry Redmond, couldn't help this one.)

You can even give it text-overflow:ellipsis, it just works as expected.

ContentLicense: CC BY-SA 3.0

Title: css td overflow

Body:
I have a table. I one of the td I have some longer text. When the text hits the right border, it goes to the line. Normal. What I would like is nevertheless a little different. When the first line hits the border I want the overflow to be hidden and have the last 3 visible characters be replaced by "...". Hope someone can help. Thank you in advance for your replies. Cheers Marc.

Here the example:

http://cssdesk.com/3HTnq

Body:
Here's a little tweak.

    td {
        max-width:1px;         /* makes all the difference! */
        white-space:nowrap;
        overflow:hidden;
    }

Try it: https://codepen.io/dkellner/pen/MWObPgY

Apparently, if you use max-width and give it any numeric value, the browser suddenly understands that you're trying to cut the contents, but since it's not an explicit width, it will let the content grow. So it's kind of autosize plus crop, which was never possible as far as I remember. Again, not sure why literally any max-width value does the trick, max-width:1px should make it one single pixel wide; but it seems to work in all major browsers AND Microsoft Edge. (Sorry Redmond, couldn't help this one.)

You can even give it text-overflow:ellipsis, it just works as expected.


答:
The logic of your code is worng. Just replace the last part with:

```<code>for(int i = 0; i < itemList.length; i++) {
    boolean alreadyBought = false;
    for(int j = 0; j < itemPurchased.length; j++) {
        if(itemList[i].equals(itemPurchased[j])) {
           alreadyBought = true;
        }
    }
    if(!alreadyBought) {
        System.out.println(itemList[i]);
    }
}
</code>```

In your code, you check every element in itemList with all the elements in itemPurchased and in case it does not exist then print. This means if your itemPurchased contains n elements, then you will print n time non-bought elements

Title: For Loop printing an element from an array more than once

Body:
The logic of your code is worng. Just replace the last part with:

for(int i = 0; i < itemList.length; i++) {
    boolean alreadyBought = false;
    for(int j = 0; j < itemPurchased.length; j++) {
        if(itemList[i].equals(itemPurchased[j])) {
           alreadyBought = true;
        }
    }
    if(!alreadyBought) {
        System.out.println(itemList[i]);
    }
}

In your code, you check every element in itemList with all the elements in itemPurchased and in case it does not exist then print. This means if your itemPurchased contains n elements, then you will print n time non-bought elements


问:
jinja if statement is not working. I don't know how to fix it
I really need help!
The code does not display different values. if the code finds a join item it should display a link, if it does not find a join item it should display a form. Else: display some text.

html:

```<code>{%- if join -%}

        <br>
        <br>
        <br>
        <center>
        <a href="/clubs/{{ club.id }}/add_post" style="text-decoration:none; font-size:18px; color:white; padding:10px 20px 10px 20px; background:#134401;">Add Post +</a>
        </center>
{%- elif not join -%}
        <br>
        <br>
        <br>
                <form action="/clubs/{{ club.id }}" method="POST">
            <center>
            <input type="submit" value="Join" style="width:20%; padding: 10px 5px 10px 5px; background:#1d2d0d; color:white; font-size:20px">
            </center>
        </form>
{%- else -%}
<h1>nope</h1>
{%- endif -%}
</code>```

function:

```<code>@application.route('/clubs/<int:id>', methods=['GET', 'POST'])
@login_required
def viewClub(id):
    post = Post.query.filter_by(clubId=id)
    club = Club.query.get_or_404(id)
    join = Join.query.filter_by(clubId=id, userId=current_user.id)

    if request.method == 'POST':
        name = club.name
        user = current_user.username
        userId = current_user.id
        clubId = club.id
        createClub = Join(name=name, clubId=clubId, user=user, userId=userId)
        db.session.add(createClub)
        db.session.commit()
        return redirect('/')
    else:
        return render_template('viewClub.html', club=club, post=post, join=join)
</code>```

答:
Your database query doesn't return a result of the query, it returns the query itself. This is always true when checked.

You forgot to add a function like .first() or .all() to the query.

```<code>join = Join.query.filter_by(clubId=id, userId=current_user.id).first()
</code>```

Body:
I really need help!
The code does not display different values. if the code finds a join item it should display a link, if it does not find a join item it should display a form. Else: display some text.

html:

{%- if join -%}

        Add Post +

{%- elif not join -%}

                <form action="/clubs/{{ club.id }}" method="POST">

            <input type="submit" value="Join" style="width:20%; padding: 10px 5px 10px 5px; background:#1d2d0d; color:white; font-size:20px">

        </form>
{%- else -%}

nope

{%- endif -%}

function:

@application.route('/clubs/<int:id>', methods=['GET', 'POST'])
@login_required
def viewClub(id):
    post = Post.query.filter_by(clubId=id)
    club = Club.query.get_or_404(id)
    join = Join.query.filter_by(clubId=id, userId=current_user.id)

    if request.method == 'POST':
        name = club.name
        user = current_user.username
        userId = current_user.id
        clubId = club.id
        createClub = Join(name=name, clubId=clubId, user=user, userId=userId)
        db.session.add(createClub)
        db.session.commit()
        return redirect('/')
    else:
        return render_template('viewClub.html', club=club, post=post, join=join)

Body:
Your database query doesn't return a result of the query, it returns the query itself. This is always true when checked.

You forgot to add a function like .first() or .all() to the query.

join = Join.query.filter_by(clubId=id, userId=current_user.id).first()


问:
Some function for preparing string on Typescript There is a need for a more elegant solution
I have a function for preparing string for a search query. But it looks so difficult  There is a need for a more elegant solution. Maybe someone can take a look and provide something better?
It is original func.

```<code>export const transformedSortFunc = (sortingPath) => {
  let transformPath;
  if (sortingPath) {
    if (sortingPath[0] === '-') {
      const sortingValue = get(SORTING_PATH_MAP, sortingPath.slice(1));
      transformPath = sortingValue ? `-${sortingValue}` : undefined;
    } else {
      transformPath = get(SORTING_PATH_MAP, sortingPath);
    }
  }
  return transformPath || sortingPath;
};

const SORTING_PATH_MAP = {
    asset: 'asset.type'
}
</code>```

Input parameters can be

```<code>  const conditional = [
        'id', 'asset', 'conditional', '-id', '-asset', '-conditional' ,
    ]
</code>```

I am using lodash.

For some incoming lines, I need to add a continuation.
For some, no. Lines can be with a minus, so I added additional checks. It ends up looking very complicated

答:
Maybe a different organization:

const transformedSortFunc = (sortingPath) => {
  if (!sortingPath) return sortingPath;

  const negative = sortingPath[0] === '-' ? '-' : '';
  const sortingValue = negative ? sortingPath.slice(1) : sortingPath;

  const transformPath = get(SORTING_PATH_MAP, sortingValue);
  return transformPath ? `${negative}${transformPath}` : sortingPath;
};
```

Body:
I have a function for preparing string for a search query. But it looks so difficult  There is a need for a more elegant solution. Maybe someone can take a look and provide something better?
It is original func.

export const transformedSortFunc = (sortingPath) => {
  let transformPath;
  if (sortingPath) {
    if (sortingPath[0] === '-') {
      const sortingValue = get(SORTING_PATH_MAP, sortingPath.slice(1));
      transformPath = sortingValue ? `-${sortingValue}` : undefined;
    } else {
      transformPath = get(SORTING_PATH_MAP, sortingPath);
    }
  }
  return transformPath || sortingPath;
};

const SORTING_PATH_MAP = {
    asset: 'asset.type'
}

Input parameters can be

  const conditional = [
        'id', 'asset', 'conditional', '-id', '-asset', '-conditional' ,
    ]

I am using lodash.

For some incoming lines, I need to add a continuation.
For some, no. Lines can be with a minus, so I added additional checks. It ends up looking very complicated


问:
Issues using strlen() to save a five letter string
I made this little program to get all the five letter words from a large text file containing all English words. I was wondering why I have set strlen(word)==6 instead of 5, even after i strtok "\n". My friend said I might have an issue with EOL conversions. I was reading about them but I can't understand them very well.

Let me know if I'm missing anything you might need to help me. Any suggestions to improve my code would be welcome as well. This is my first post so please bear with me. Thank you.

```<code>#include <stdio.h>
#include <string.h>
#define SIZE 6

void manFile(char in_file[], char out_file[]);

int main(int argc, char **argv)
{
    manFile("words_alpha.txt", "fiveletterwords.txt");
}

void manFile(char in_file[], char out_file[])
{
    FILE*inFp= fopen(in_file, "r");
    FILE*outFp= fopen(out_file, "w");

    char word[20];

    if(!inFp)
    {
        printf("File not opened.");
    }

    else
    {
        while(fgets(word, sizeof(word), inFp))
        {
            strtok(word, "\n");

            if(strlen(word)==SIZE)
            {
                fprintf(outFp,"%s\n", word);
            }
        }

        printf("File saved...");

        fclose(inFp);
        fclose(outFp);
    }
}
</code>```

答:
If you are running on a windows-based system, line are terminated with both a newline ('\n') and a carriage-return ('\r'), so you probably want:</p>
```<code>strtok(word,"\n\r");
</code>```

Body:
I made this little program to get all the five letter words from a large text file containing all English words. I was wondering why I have set strlen(word)==6 instead of 5, even after i strtok "\n". My friend said I might have an issue with EOL conversions. I was reading about them but I can't understand them very well.

Let me know if I'm missing anything you might need to help me. Any suggestions to improve my code would be welcome as well. This is my first post so please bear with me. Thank you.

#include <stdio.h>
#include <string.h>
#define SIZE 6

void manFile(char in_file[], char out_file[]);

int main(int argc, char **argv)
{
    manFile("words_alpha.txt", "fiveletterwords.txt");
}

void manFile(char in_file[], char out_file[])
{
    FILE*inFp= fopen(in_file, "r");
    FILE*outFp= fopen(out_file, "w");

    char word[20];

    if(!inFp)
    {
        printf("File not opened.");
    }

    else
    {
        while(fgets(word, sizeof(word), inFp))
        {
            strtok(word, "\n");

            if(strlen(word)==SIZE)
            {
                fprintf(outFp,"%s\n", word);
            }
        }

        printf("File saved...");

        fclose(inFp);
        fclose(outFp);
    }
}

Body:
If you are running on a windows-based system, line are terminated with both a newline ('\n') and a carriage-return ('\r'), so you probably want:

strtok(word,"\n\r");


问:
Eslint suddenly stopped working, React plugin
My eslint config stopped linting my code, it doesn't show errors or anything, I'm confused is there something wrong with my config? Do I need to add some configs for eslint:recommend for it to work? I just followed the react plugin steps, I appreciate the answers.</p>
```<code> "extends": [
    "eslint:recommended",
    "plugin:react/recommended"
  ],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module",
    "ecmaFeatures": {
    "jsx": true
    }
  },
  "rules": {
    "indent": ["error", 2],
    "semi": ["error", "always"],
    "max-len": [2, { "code": 80, "tabWidth": 2, "ignoreUrls": true }],
    "react/jsx-max-props-per-line": ["error", { "maximum": { "single": 1, "multi": 2 } }],
    "react/jsx-first-prop-new-line":"always"
  },
    "plugins": [
      "react"
    ],
</code>```

答:
I found the problem...
"react/jsx-first-prop-new-line":"always"

the above line is expecting a number for it to work 0 1 2
"react/jsx-first-prop-new-line": 2

2 Meaning "On" is the correct way to write it

Body:
My eslint config stopped linting my code, it doesn't show errors or anything, I'm confused is there something wrong with my config? Do I need to add some configs for eslint:recommend for it to work? I just followed the react plugin steps, I appreciate the answers.

 "extends": [
    "eslint:recommended",
    "plugin:react/recommended"
  ],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module",
    "ecmaFeatures": {
    "jsx": true
    }
  },
  "rules": {
    "indent": ["error", 2],
    "semi": ["error", "always"],
    "max-len": [2, { "code": 80, "tabWidth": 2, "ignoreUrls": true }],
    "react/jsx-max-props-per-line": ["error", { "maximum": { "single": 1, "multi": 2 } }],
    "react/jsx-first-prop-new-line":"always"
  },
    "plugins": [
      "react"
    ],


问:
MSBuild: error MSB3073 The command 'setlocal VCEnd' exited with code 1
I am trying to build an opensource project on my machine using Visual Studio 2015 and CMake. I have followed all the steps and the prebuild checks were running properly. But when I am building the INSTALL to install the software in the folder that I have specified in the CMAKE gui, I am getting the MSB3073 error. A full description of the error is as below.

```<code>Severity Code Description Project File Line Suppression State Error
MSB3073 The command "setlocal
"C:\Program Files (x86)\CMake\bin\cmake.exe" -DBUILD_TYPE=RelWithDebInfo -P    cmake_install.cmake
if %errorlevel% neq 0 goto :cmEnd
:cmEnd
endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone
:cmErrorLevel
exit /b %1
:cmDone
if %errorlevel% neq 0 goto :VCEnd
:VCEnd" exited with code 1.
INSTALL C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets  133
</code>```

I have searched for the same error and found that some people who tried to install the build in a directory without write privileges encountered this, but I have made sure that I have write access. I have even tried do this with admin rights and still not able to fix this issue.

Any help in this would be highly appreciated.

答:
While running Visual Studio 2022, trying to build VST plug-in with code generated by cmake.
For me it showed permission access denied when creating a symbolic link.

All I had to do was run Visual Studio "As Administrator" and it worked.

Of course, you have to have Admin privileges to your machine, or you belong to a group that is allowed to "Create symbolic links" in the Local Group Policy Editor (https://developer.steinberg.help/display/VST/Preparation+on+Windows)

Body:
I am trying to build an opensource project on my machine using Visual Studio 2015 and CMake. I have followed all the steps and the prebuild checks were running properly. But when I am building the INSTALL to install the software in the folder that I have specified in the CMAKE gui, I am getting the MSB3073 error. A full description of the error is as below.

Severity Code Description Project File Line Suppression State Error
MSB3073 The command "setlocal
"C:\Program Files (x86)\CMake\bin\cmake.exe" -DBUILD_TYPE=RelWithDebInfo -P    cmake_install.cmake
if %errorlevel% neq 0 goto :cmEnd
:cmEnd
endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone
:cmErrorLevel
exit /b %1
:cmDone
if %errorlevel% neq 0 goto :VCEnd
:VCEnd" exited with code 1.
INSTALL C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets  133

I have searched for the same error and found that some people who tried to install the build in a directory without write privileges encountered this, but I have made sure that I have write access. I have even tried do this with admin rights and still not able to fix this issue.

Any help in this would be highly appreciated.


问:
Huge number of objects, sharding and java EE
I'm new to java ee and I'm not sure how to implement a particular requirement.

I have need for a large set (millions) of objects that maintain a bunch of rules and state and present an API for clients.  Each of these objects is long lived.  Given that there're so many of these things, we'll likely need to shard them across many VMs and use RMI to access them.

My question is whether there's a Java EE approach to solve the problem of locating an instance of the object, allowing the clients to get a reference to the object without needing to be aware of which machine it is on.

I'm aware of JNDI, but I'm not sure that registering each of the objects in a JNDI directory is appropriate.  Do I need to write a "Locator" library that can make itself aware of the VM that each object belongs to?

答:
I may not directly answer you question, but I know that Oracle Coherence can not just distribute data, but can also distribute calculation against that data.

Simple example code here.
You write your calculation through a class that implements com.tangosol.uti.InvocableMap.EntryProcessor. This will enable calculation
to take place at the server where the data exists.
One restiction is that the data needs to be serializable because it
moves through the network.

```<code>public class CalcLogic implements EntryProcessor {
....
    //InvocableMap.Entry is the "data"
    //You write your calculation in this process methods.
    public Object process(InvocableMap.Entry entry {
        (YourObjectType) obj = (YourObjectType)entry.getValue();
        //do some calculation against obj here
        entry.setValue(obj);
        return null;
    }

....
}
</code>```

Body:
I may not directly answer you question, but I know that Oracle Coherence can not just distribute data, but can also distribute calculation against that data.

Simple example code here.
You write your calculation through a class that implements com.tangosol.uti.InvocableMap.EntryProcessor. This will enable calculation
to take place at the server where the data exists.
One restiction is that the data needs to be serializable because it
moves through the network.

public class CalcLogic implements EntryProcessor {
....
    //InvocableMap.Entry is the "data"
    //You write your calculation in this process methods.
    public Object process(InvocableMap.Entry entry {
        (YourObjectType) obj = (YourObjectType)entry.getValue();
        //do some calculation against obj here
        entry.setValue(obj);
        return null;
    }

....
}