问:
Is it possible to find the 0th index-position of a 2D numpy array (not) containing a given vaule?

Is it possible to find the 0th index-position of a 2D numpy array (not) containing a given vaule?

What I want, and expect

I have a 2D numpy array containing integers. My goal is to find the index of the array(s) that do not contain a given value (using numpy functions). Here is an example of such an array, named ortho_disc:

```<code>>>> ortho_disc
Out: [[1 1 1 0 0 0 0 0 0]
      [1 0 1 1 0 0 0 0 0]
      [0 0 0 0 0 0 2 2 0]]
</code>```

If I wish to find the arrays not containing 2, I would expect an output of [0, 1], as the first and second array of ortho_disc does not contain the value 2.

What I have tried

I have looked into np.argwhere, np.nonzero, np.isin and np.where without expected results. My best attempt using np.where was the following:

```<code>>>> np.where(2 not in ortho_disc, [True]*3, [False]*3)
Out: [False False False]
</code>```

But it does not return the expected [True, True, False]. This is especially weird after we look at the output ortho_disc's arrays evaluated by themselves:

```<code>>>> 2 not in ortho_disc[0]
Out: True

>>> 2 not in ortho_disc[1]
Out:True

>>> 2 not in ortho_disc[2]
Out: False
</code>```

Using argwhere

Using np.argwhere, all I get is an empty array (not the expected [0, 1]):

```<code>>>> np.argwhere(2 not in ortho_disc)
Out: []
</code>```

I suspect this is because numpy first flattens ortho_disc, then checks the truth-value of 2 not in ortho_disc?
The same empty array is returned using np.nonzero(2 not in ortho_disc).

My code

```<code>import numpy as np
ortho_disc = np.array([[1, 1, 1, 0, 0, 0, 0, 0, 0],
                       [1, 0, 1, 1, 0, 0, 0, 0, 0],
                       [0, 0, 0, 0, 0, 0, 2, 2, 0,]])
polymer = 2

print(f'>>> ortho_disc \nOut:\n{ortho_disc}\n')
print(f'>>> {polymer} not in {ortho_disc[0]} \nOut: {polymer not in ortho_disc[0]}\n')
print(f'>>> {polymer} not in {ortho_disc[1]} \nOut: {polymer not in ortho_disc[1]}\n')
print(f'>>> {polymer} not in {ortho_disc[2]} \nOut: {polymer not in ortho_disc[2]}\n\n')

breakpoint = np.argwhere(polymer not in ortho_disc)
print(f'>>>np.argwhere({polymer} not in ortho_disc) \nOut: {breakpoint}\n\n\n')
</code>```

Output:

```<code>>>> ortho_disc
Out:
[[1 1 1 0 0 0 0 0 0]
 [1 0 1 1 0 0 0 0 0]
 [0 0 0 0 0 0 2 2 0]]

>>> 2 not in [1 1 1 0 0 0 0 0 0]
Out: True

>>> 2 not in [1 0 1 1 0 0 0 0 0]
Out: True

>>> 2 not in [0 0 0 0 0 0 2 2 0]
Out: False

>>>np.argwhere(2 not in ortho_disc)
Out: []
</code>```

Expected output

From the bottom two lines:

```<code>breakpoint = np.argwhere(polymer not in ortho_disc)
print(f'>>>np.argwhere({polymer} not in ortho_disc) \nOut: {breakpoint}\n\n\n')
</code>```

I excpect the following output:

```<code>>>>np.argwhere(2 not in ortho_disc)
Out: [0, 1]
</code>```

Summary

I would really love feedback on how to solve this issue, as I have been scratching my head over what seems to be an easy problem for ages. And as I mentioned it is important to avoid the obvious 'easy-way-out' loop over ortho_disc, preferably using numpy.

Thanks in advance!

答:
```<code>In [13]: ortho_disc
Out[13]:
array([[1, 1, 1, 0, 0, 0, 0, 0, 0],
       [1, 0, 1, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 2, 2, 0]])

In [14]: polymer = 2

In [15]: (ortho_disc != polymer).all(axis=1).nonzero()[0]
Out[15]: array([0, 1])
</code>```

Breaking it down: ortho_disc != polymer is an array of bools:

```<code>In [16]: ortho_disc != polymer
Out[16]:
array([[ True,  True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True, False, False,  True]])
</code>```

We want the rows that are all True; for that, we can apply the all() method along axis 1 (i.e. along the rows):

```<code>In [17]: (ortho_disc != polymer).all(axis=1)
Out[17]: array([ True,  True, False])
</code>```

That's the boolean mask for the rows that do not contain polymer.

Use nonzero() to find the indices of the values that are not 0 (True is considered nonzero, False is 0):

```<code>In [19]: (ortho_disc != polymer).all(axis=1).nonzero()
Out[19]: (array([0, 1]),)
</code>```

Note that nonzero() returned a tuple with length 1; in general, it returns a tuple with the same length as the number of dimensions of the array.  Here the input array is 1-d.  Pull out the desired result from the tuple by indexing with [0]:

```<code>In [20]: (ortho_disc != polymer).all(axis=1).nonzero()[0]
Out[20]: array([0, 1])
</code>```

Body:
Is it possible to find the 0th index-position of a 2D numpy array (not) containing a given vaule?

What I want, and expect

I have a 2D numpy array containing integers. My goal is to find the index of the array(s) that do not contain a given value (using numpy functions). Here is an example of such an array, named ortho_disc:

>>> ortho_disc
Out: [[1 1 1 0 0 0 0 0 0]
      [1 0 1 1 0 0 0 0 0]
      [0 0 0 0 0 0 2 2 0]]

If I wish to find the arrays not containing 2, I would expect an output of [0, 1], as the first and second array of ortho_disc does not contain the value 2.

What I have tried

I have looked into np.argwhere, np.nonzero, np.isin and np.where without expected results. My best attempt using np.where was the following:

>>> np.where(2 not in ortho_disc, [True]*3, [False]*3)
Out: [False False False]

But it does not return the expected [True, True, False]. This is especially weird after we look at the output ortho_disc's arrays evaluated by themselves:

>>> 2 not in ortho_disc[0]
Out: True

>>> 2 not in ortho_disc[1]
Out:True

>>> 2 not in ortho_disc[2]
Out: False

Using argwhere

Using np.argwhere, all I get is an empty array (not the expected [0, 1]):

>>> np.argwhere(2 not in ortho_disc)
Out: []

I suspect this is because numpy first flattens ortho_disc, then checks the truth-value of 2 not in ortho_disc?
The same empty array is returned using np.nonzero(2 not in ortho_disc).

My code

import numpy as np
ortho_disc = np.array([[1, 1, 1, 0, 0, 0, 0, 0, 0],
                       [1, 0, 1, 1, 0, 0, 0, 0, 0],
                       [0, 0, 0, 0, 0, 0, 2, 2, 0,]])
polymer = 2

print(f'>>> ortho_disc \nOut:\n{ortho_disc}\n')
print(f'>>> {polymer} not in {ortho_disc[0]} \nOut: {polymer not in ortho_disc[0]}\n')
print(f'>>> {polymer} not in {ortho_disc[1]} \nOut: {polymer not in ortho_disc[1]}\n')
print(f'>>> {polymer} not in {ortho_disc[2]} \nOut: {polymer not in ortho_disc[2]}\n\n')

breakpoint = np.argwhere(polymer not in ortho_disc)
print(f'>>>np.argwhere({polymer} not in ortho_disc) \nOut: {breakpoint}\n\n\n')

Output:

>>> ortho_disc
Out:
[[1 1 1 0 0 0 0 0 0]
 [1 0 1 1 0 0 0 0 0]
 [0 0 0 0 0 0 2 2 0]]

>>> 2 not in [1 1 1 0 0 0 0 0 0]
Out: True

>>> 2 not in [1 0 1 1 0 0 0 0 0]
Out: True

>>> 2 not in [0 0 0 0 0 0 2 2 0]
Out: False

>>>np.argwhere(2 not in ortho_disc)
Out: []

Expected output

From the bottom two lines:

breakpoint = np.argwhere(polymer not in ortho_disc)
print(f'>>>np.argwhere({polymer} not in ortho_disc) \nOut: {breakpoint}\n\n\n')

I excpect the following output:

>>>np.argwhere(2 not in ortho_disc)
Out: [0, 1]

Summary

I would really love feedback on how to solve this issue, as I have been scratching my head over what seems to be an easy problem for ages. And as I mentioned it is important to avoid the obvious 'easy-way-out' loop over ortho_disc, preferably using numpy.

Thanks in advance!

Body:
In [13]: ortho_disc
Out[13]:
array([[1, 1, 1, 0, 0, 0, 0, 0, 0],
       [1, 0, 1, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 2, 2, 0]])

In [14]: polymer = 2

In [15]: (ortho_disc != polymer).all(axis=1).nonzero()[0]
Out[15]: array([0, 1])

Breaking it down: ortho_disc != polymer is an array of bools:

In [16]: ortho_disc != polymer
Out[16]:
array([[ True,  True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True, False, False,  True]])

We want the rows that are all True; for that, we can apply the all() method along axis 1 (i.e. along the rows):

In [17]: (ortho_disc != polymer).all(axis=1)
Out[17]: array([ True,  True, False])

That's the boolean mask for the rows that do not contain polymer.

Use nonzero() to find the indices of the values that are not 0 (True is considered nonzero, False is 0):

In [19]: (ortho_disc != polymer).all(axis=1).nonzero()
Out[19]: (array([0, 1]),)

Note that nonzero() returned a tuple with length 1; in general, it returns a tuple with the same length as the number of dimensions of the array.  Here the input array is 1-d.  Pull out the desired result from the tuple by indexing with [0]:

In [20]: (ortho_disc != polymer).all(axis=1).nonzero()[0]
Out[20]: array([0, 1])


来源: stackexchange

答:
You can use numpy broadcasting for this. ortho_disc == 2 will return a mask of the array where each value is True if that value in the array was not 2, False if it was 2. Then, use np.all with axis=1 to condense each row into a boolean indicating whether or not that row contained only True values (True value = no 2 there):

```<code>>>> np.all(ortho_disc != 2, axis=1)
array([ True,  True, False])
</code>```

If you want to get the indexes out that, just np.where with the above:

```<code>>>> np.where(np.all(ortho_disc != 2, axis=1))[0]
array([0, 1])
</code>```

ContentLicense: CC BY-SA 4.0

Title: Is it possible to find the 0th index-position of a 2D numpy array (not) containing a given vaule?

Body:
You can use numpy broadcasting for this. ortho_disc == 2 will return a mask of the array where each value is True if that value in the array was not 2, False if it was 2. Then, use np.all with axis=1 to condense each row into a boolean indicating whether or not that row contained only True values (True value = no 2 there):

>>> np.all(ortho_disc != 2, axis=1)
array([ True,  True, False])

If you want to get the indexes out that, just np.where with the above:

>>> np.where(np.all(ortho_disc != 2, axis=1))[0]
array([0, 1])


问:
Pipeline fill-mask error with custom Roberta tokenizer
I’m using boilerplate code to train a Roberta model on my text corpus.

Everything seems to be going okay until I try to load the pretrained tokenizer into the pipeline. I think it’s looking for a config.json file in the tokenizer folder but the BPE tokenizer is only outputting vocab.json and merges.txt files. what am I missing here?

link to notebook gist

答:
this may be helpful to someone else so I'll keep the post up.  The tokenizer needs to be re-saved as a Roberta tokenizer (not BPE) for fill-mask pipline to work.  this solution is given here.  Adding the suggested code lines fixed it:</p>
```<code>from transformers import RobertaTokenizerFast

tokenizer = RobertaTokenizerFast.from_pretrained(tokenizer_folder, return_special_tokens_mask=True, max_length=512)

tokenizer.save_pretrained(tokenizer_folder)
</code>```

Body:
this may be helpful to someone else so I'll keep the post up.  The tokenizer needs to be re-saved as a Roberta tokenizer (not BPE) for fill-mask pipline to work.  this solution is given here.  Adding the suggested code lines fixed it:

from transformers import RobertaTokenizerFast

tokenizer = RobertaTokenizerFast.from_pretrained(tokenizer_folder, return_special_tokens_mask=True, max_length=512)

tokenizer.save_pretrained(tokenizer_folder)


问:
Create a Dataframe of Difference scores between users for multiple variables
I have a large dataframe with users scores on a number of language dimensions, with a simplified version looking like the code below (I have included a dput replication data at the bottom of the post)

```<code>    user             Authentic   Analytic    Clout       Tone
2   Adams_Alma       0.05738848  0.7511374  0.3675847   0.95387755
3   Aguilar_Pete     0.24302974  0.7725205  0.3873588   0.79183673
4   Allred_Colin     0.11245353  0.7770701  0.7482345   0.58346939
5   Auchincloss_Jake 0.96119888  0.8020928  0.2673023   0.49765306
6   Axne_Cynthia     0.12500000  0.8644222  0.4918785   0.97112245
</code>```

Using this data, I want to create a dataframe in which each row is the difference score of between a pair of users in the dataset, as seen below (though the actual dataframe is much larger).

```<code>    from        to                 diff_Authentic   diff_Analytic  diff_Clout  diff_Tone
1   Adams_Alma  Aguilar_Pete       0.9802260        0.123456       0.123456    0.123456
2   Adams_Alma  Allred_Colin       0.6193503        0.123456       0.123456    0.123456
3   Adams_Alma  Auchincloss_Jake   0.8997175        0.123456       0.123456    0.123456
4   Adams_Alma  Axne_Cynthia       0.8757062        0.123456       0.123456    0.123456
5   Adams_Alma  Baldwin_Tammy      0.9406780        0.123456       0.123456    0.123456
6   Adams_Alma  Barragán_Nanette   0.8495763        0.123456       0.123456    0.123456
7   Adams_Alma  Bass_Karen         0.8234463        0.123456       0.123456    0.123456
8   Adams_Alma  Beatty_Joyce       0.9014831        0.123456       0.123456    0.123456
9   Adams_Alma  Bennet_Michael     0.5183616        0.123456       0.123456    0.123456
10  Adams_Alma  Bera_Ami           0.8223870        0.123456       0.123456    0.123456
</code>```

Using the code below, I am able to create a difference edgelist for one variable at a time, but my full dataframe has 90 variables I want differences for.

```<code>out <- with(norm_data, as.matrix(dist(setNames(norm_data$Authentic, norm_data$user))))
dif_g <- graph_from_adjacency_matrix (out, mode = 'undirected', weighted = TRUE)
dif_edge_list <- as_data_frame(dif_g, 'edges')
dif_edge_list$weight <- 1 - dif_edge_list$weight
</code>```

I would like to have a single dataframe that has the difference scores for each pair of users across all variables. I'm assuming a loop might be the solution, but I can't figure out how to do this. Any help would be greatly appreciated. Let me know if you need any more info.

Dput Data:

```<code>Show in New WindowClear OutputExpand/Collapse Output
structure(list(user = structure(1:50, .Label = c("Adams_Alma",
"Aguilar_Pete", "Allred_Colin", "Auchincloss_Jake", "Axne_Cynthia",
"Baldwin_Tammy", "Barragán_Nanette", "Bass_Karen", "Beatty_Joyce",
"Bennet_Michael", "Bera_Ami", "Beyer_Donald", "Bishop_Sanford",
"Blumenthal_Richard", "Blunt_Rochester_Lisa", "Bonamici_Suzanne",
"Booker_Cory", "Bourdeaux_Carolyn", "Bowman_Jamaal", "Boyle_Brendan",
"Brown_Anthony", "Brown_Sherrod", "Brownley_Julia", "Bush_Cori",
"Bustos_Cheri", "Butterfield_George", "Cantwell_Maria", "Carbajal_Salud",
"Cárdenas_Tony", "Cardin_Benjamin", "Carper_Thomas", "Carson_André",
"Cartwright_Matthew", "Case_Ed", "Casey_Robert", "Casten_Sean",
"Castor_Kathy", "Castro_Joaquin", "Chu_Judy", "Cicilline_David",
"Clark_Katherine", "Clarke_Yvette", "Cleaver_Emanuel", "Clyburn_James",
"Cohen_Steve", "Connolly_Gerald", "Coons_Christopher", "Cooper_Jim",
"Correa_J", "Cortez_Masto_Catherine", "Costa_Jim", "Courtney_Joe",
"Craig_Angie", "Crist_Charlie", "Crow_Jason", "Cuellar_Henry",
"Davids_Sharice", "Davis_Danny", "Dean_Madeleine", "DeFazio_Peter",
"DeGette_Diana", "DeLauro_Rosa", "DelBene_Suzan", "Delgado_Antonio",
"Demings_Val", "DeSaulnier_Mark", "Deutch_Theodore", "Dingell_Debbie",
"Doggett_Lloyd", "Doyle_Michael", "Duckworth_Tammy", "Durbin_Richard",
"Escobar_Veronica", "Eshoo_Anna", "Espaillat_Adriano", "Evans_Dwight",
"Feinstein_Dianne", "Fletcher_Lizzie", "Foster_Bill", "Frankel_Lois",
"Gallego_Ruben", "Garamendi_John", "García_Jesús", "Garcia_Sylvia",
"Golden_Jared", "Gomez_Jimmy", "Gonzalez_Vicente", "Gottheimer_Josh",
"Green_Al", "Grijalva_Raúl", "Harder_Josh", "Hassan_Margaret",
"Hayes_Jahana", "Heinrich_Martin", "Higgins_Brian", "Himes_James",
"Hirono_Mazie", "Horsford_Steven", "Houlahan_Chrissy", "Hoyer_Steny",
"Huffman_Jared", "Jackson_Lee_Sheila", "Jacobs_Sara", "Jayapal_Pramila",
"Jeffries_Hakeem", "Johnson_Eddie", "Johnson_Henry", "Kaptur_Marcy",
"Keating_William", "Kelly_Mark", "Kelly_Robin", "Khanna_Ro",
"Kildee_Daniel", "Kilmer_Derek", "Kim_Andy", "Kind_Ron", "Kirkpatrick_Ann",
"Klobuchar_Amy", "Krishnamoorthi_Raja", "Kuster_Ann", "Lamb_Conor",
"Langevin_James", "Larsen_Rick", "Larson_John", "Lawrence_Brenda",
"Lawson_Al", "Leahy_Patrick", "Lee_Barbara", "Lee_Susie", "Leger_Fernandez_Teresa",
"Levin_Andy", "Levin_Mike", "Lieu_Ted", "Lofgren_Zoe", "Lowenthal_Alan",
"Luján_Ben", "Luria_Elaine", "Lynch_Stephen", "Malinowski_Tom",
"Maloney_Carolyn", "Maloney_Sean", "Manchin_Joe", "Manning_Kathy",
"Markey_Edward", "Matsui_Doris", "McBath_Lucy", "McCollum_Betty",
"McEachin_A", "McGovern_James", "McNerney_Jerry", "Meeks_Gregory",
"Menendez_Robert", "Meng_Grace", "Merkley_Jeff", "Mfume_Kweisi",
"Moore_Gwen", "Morelle_Joseph", "Moulton_Seth", "Mrvan_Frank",
"Murphy_Stephanie", "Murray_Patty", "Nadler_Jerrold", "Napolitano_Grace",
"Neal_Richard", "Neguse_Joe", "Newman_Marie", "Norcross_Donald",
"Norton_Eleanor", "O_Halleran_Tom", "Ocasio_Cortez_Alexandria",
"Omar_Ilhan", "Ossoff_Jon", "Padilla_Alejandro", "Pallone_Frank",
"Panetta_Jimmy", "Pappas_Chris", "Pascrell_Bill", "Payne_Donald",
"Pelosi_Nancy", "Perlmutter_Ed", "Peters_Gary", "Peters_Scott",
"Phillips_Dean", "Pingree_Chellie", "Plaskett_Stacey", "Pocan_Mark",
"Porter_Katie", "Pressley_Ayanna", "Price_David", "Quigley_Mike",
"Raskin_Jamie", "Reed_John", "Rice_Kathleen", "Rosen_Jacky",
"Ross_Deborah", "Roybal_Allard_Lucille", "Ruiz_Raul", "Ruppersberger_C",
"Rush_Bobby", "Ryan_Tim", "Sablan_Gregorio", "Sánchez_Linda",
"Sarbanes_John", "Scanlon_Mary", "Schakowsky_Janice", "Schatz_Brian",
"Schiff_Adam", "Schneider_Bradley", "Schrader_Kurt", "Schrier_Kim",
"Schumer_Charles", "Scott_David", "Scott_Robert", "Sewell_Terri",
"Shaheen_Jeanne", "Shelby_Richard", "Sherman_Brad", "Sherrill_Mikie",
"Sinema_Kyrsten", "Sires_Albio", "Slotkin_Elissa", "Smith_Adam",
"Smith_Tina", "Soto_Darren", "Spanberger_Abigail", "Speier_Jackie",
"Stabenow_Debbie", "Stanton_Greg", "Stevens_Haley", "Strickland_Marilyn",
"Suozzi_Thomas", "Swalwell_Eric", "Takano_Mark", "Tester_Jon",
"Thompson_Bennie", "Thompson_Mike", "Titus_Dina", "Tlaib_Rashida",
"Tonko_Paul", "Torres_Norma", "Torres_Ritchie", "Trahan_Lori",
"Trone_David", "Underwood_Lauren", "user", "Van_Hollen_Chris",
"Vargas_Juan", "Veasey_Marc", "Vela_Filemon", "Velázquez_Nydia",
"Warner_Mark", "Warnock_Raphael", "Warren_Elizabeth", "Wasserman_Schultz_Debbie",
"Waters_Maxine", "Watson_Coleman_Bonnie", "Welch_Peter", "Wexton_Jennifer",
"Whitehouse_Sheldon", "Wild_Susan", "Williams_Nikema", "Wilson_Frederica",
"Wyden_Ron", "Yarmuth_John"), class = "factor"), Authentic = c(0.0573884758364312,
0.243029739776952, 0.112453531598513, 0.961198884758364, 0.125,
0.139869888475836, 0.131737918215613, 0.174024163568773, 0.115706319702602,
0.325046468401487, 0.223048327137546, 0.087592936802974, 0.133364312267658,
0.190985130111524, 0.21003717472119, 0.0422862453531598, 0.153113382899628,
0.263708178438662, 0.157295539033457, 0.328996282527881, 0.139637546468401,
0.48025092936803, 0.26974907063197, 0.378020446096654, 0.153113382899628,
0.454693308550186, 0.0820167286245353, 0.130576208178439, 0.33317843866171,
0.263243494423792, 0.197490706319703, 0.295074349442379, 0.251626394052045,
0.303671003717472, 0.180065055762082, 0.155204460966543, 0.10246282527881,
0.237453531598513, 0.132434944237918, 0.151022304832714, 0.10339219330855,
0.991635687732342, 0.185176579925651, 0.263475836431227, 0.0669144981412639,
0.143587360594796, 0.127788104089219, 0.212360594795539, 0.45817843866171,
0.054135687732342), Analytic = c(0.751137397634213, 0.772520473157416,
0.777070063694267, 0.802092811646951, 0.86442220200182, 0.75796178343949,
0.847133757961783, 0.873976342129208, 0.816196542311192, 0.801182893539581,
0.809827115559599, 0.695177434030937, 0.803457688808007, 0.726569608735214,
0.774795268425842, 0.843039126478617, 0.788898999090082, 0.773885350318471,
0.79936305732484, 0.78434940855323, 0.939945404913557, 0.772520473157416,
0.741128298453139, 0.736123748862602, 0.927206551410373, 0.673794358507734,
0.859872611464968, 0.763421292083712, 0.810282074613285, 0.871701546860782,
0.834849863512284, 0.786624203821656, 0.782984531392174, 1, 0.872611464968152,
0.748862602365787, 0.804367606915377, 0.79936305732484, 0.682893539581438,
0.761601455868971, 0.722929936305732, 0.767970882620564, 0.845313921747043,
0.79663330300273, 0.74294813466788, 0.840764331210191, 0.894904458598726,
0.787534121929026, 0.800272975432211, 0.883530482256597), Clout = c(0.367584745762712,
0.387358757062147, 0.748234463276836, 0.267302259887006, 0.491878531073446,
0.426906779661017, 0.518008474576271, 0.191031073446328, 0.466101694915254,
0.849223163841808, 0.545197740112994, 0.475988700564972, 0.548728813559322,
0.711511299435028, 0.538841807909604, 0.792372881355932, 0.49364406779661,
0.487641242937853, 0.64795197740113, 0.370409604519774, 0.771186440677966,
0.288488700564972, 0.211158192090395, 0.273658192090395, 0.420197740112994,
1, 0.531779661016949, 0.629237288135593, 0.646539548022599, 0.208686440677966,
0.189618644067797, 0.92090395480226, 0.632415254237288, 0.965042372881356,
0.34180790960452, 0.392302259887005, 0.604166666666666, 0.548375706214689,
0.401836158192091, 0.415254237288136, 0.364759887005649, 0.332980225988701,
0.354519774011299, 0.346398305084746, 0.52295197740113, 0.453389830508474,
0.777189265536723, 0.332980225988701, 0.436087570621469, 0.387358757062147
), Tone = c(0.953877551020408, 0.791836734693877, 0.583469387755102,
0.49765306122449, 0.971122448979592, 0.994183673469388, 0.626836734693878,
0.893061224489796, 0.34469387755102, 0.68530612244898, 0.970204081632653,
0.698265306122449, 0.959795918367347, 0.379183673469388, 0.988469387755102,
0.930408163265306, 0.0593877551020408, 0.744897959183674, 0.884387755102041,
0.803367346938776, 0.659285714285714, 0.422244897959184, 0.283571428571429,
0.252755102040816, 0.926530612244898, 0.988265306122449, 0.76469387755102,
0.525408163265306, 0.817040816326531, 0.891428571428571, 0.81265306122449,
0.451632653061224, 0.654285714285714, 0.727244897959184, 0.974591836734694,
0.467448979591837, 0.798775510204082, 0.501122448979592, 0.919795918367347,
0.744897959183674, 0.83234693877551, 0.931224489795918, 0.866326530612245,
0.448673469387755, 0.766530612244898, 0.326734693877551, 0.847959183673469,
0.685204081632653, 0.78765306122449, 0.847755102040816)), row.names = 2:51, class = "data.frame")
</code>```

答:
```<code># set as data.table
setDT(df)

# as.character (needed to rid permutation)
df[, user := as.character(user)]

# cross join
df_1 <- df[, as.list(df), names(df)]

# name change
x <- unlist(lapply(list('x.', 'i.'), \(i) paste0(i, names(df))))
names(df_1) <- x

# rid combo from replacement. Change to != for permutation
df_1 <- df_1[i.user < x.user]

# names net prefix
y <- gsub('x\\.|i\\.', '', x)

# construct formula
z <- lapply(2:5, \(i) paste0('diff_', y[i], '=', x[i], '-', x[i+5]))
a <- paste('.(' ,paste(unlist(z), collapse=','), ')')

# calculate diff
df_1[, eval(parse(text=a))]
</code>```

and my personal fav. Benchmarking :)

```<code># benchmark
library(tidyverse)
library(data.table)
library(microbenchmark)
library(ggplot2)

df <- data.table(user = 1:10000)
df[, `:=` (Authentic = user
           , Analytic = user
           , Clout = user
           , Tone = user
           )]
df[, user := as.character(user)]

xx <-
microbenchmark(sweepydodo = {
                              # cross join
                              df_1 <- df[, as.list(df), names(df)]

                              # name change
                              x <- unlist(lapply(list('x.', 'i.'), \(i) paste0(i, names(df))))
                              names(df_1) <- x

                              # rid combo from replacement. Change to != for permutation
                              df_1 <- df_1[i.user > x.user]

                              # names net prefix
                              y <- gsub('x\\.|i\\.', '', x)

                              # construct formula
                              z <- lapply(2:5, \(i) paste0('diff_', y[i], '=', x[i], '-', x[i+5]))
                              a <- paste('.(' ,paste(unlist(z), collapse=','), ')')

                              # calculate diff
                              df_1[, eval(parse(text=a))]
                              }
               , Onyambu = {
                            index <- which(lower.tri(diag(nrow(df))), T)
                            a <- data.frame(user1 = df[index[,2],1]
                                            , user2 = df[index[,1],1]
                                            , diff = df[index[,2],-1] - df[index[,1],-1]
                                            , row.names = NULL
                                            )
                            }
               , Onyambu_modified = {
                                      x <- 1:nrow(df)
                                      index <- CJ(a=x,b=x)[a>b]
                                      a <- data.table(user1 = df[index[[2]],1]
                                                      , user2 = df[index[[1]],1]
                                                      , diff = df[index[[2]],-1] - df[index[[1]],-1]
                                                      , row.names = NULL
                                                      )
                                      }
               , Iman = {
                          crossing(df, user2 = df$user) %>%
                            filter(user != user2) %>%
                            left_join(df, by = c("user2" = "user")) %>%
                            transmute(from = user,
                                        to = user2,
                                        Authentic_diff = Authentic.y - Authentic.x,
                                        Analytic_diff =  Analytic.y - Analytic.x,
                                        Clout_diff = Clout.y - Clout.x,
                                        Tone_diff = Tone.y - Tone.x
                                      )
                 }
               , times = 30
               )

# plot
autoplot(xx)
</code>```

Body:
I have a large dataframe with users scores on a number of language dimensions, with a simplified version looking like the code below (I have included a dput replication data at the bottom of the post)

    user             Authentic   Analytic    Clout       Tone
2   Adams_Alma       0.05738848  0.7511374  0.3675847   0.95387755
3   Aguilar_Pete     0.24302974  0.7725205  0.3873588   0.79183673
4   Allred_Colin     0.11245353  0.7770701  0.7482345   0.58346939
5   Auchincloss_Jake 0.96119888  0.8020928  0.2673023   0.49765306
6   Axne_Cynthia     0.12500000  0.8644222  0.4918785   0.97112245

Using this data, I want to create a dataframe in which each row is the difference score of between a pair of users in the dataset, as seen below (though the actual dataframe is much larger).

    from        to                 diff_Authentic   diff_Analytic  diff_Clout  diff_Tone
1   Adams_Alma  Aguilar_Pete       0.9802260        0.123456       0.123456    0.123456
2   Adams_Alma  Allred_Colin       0.6193503        0.123456       0.123456    0.123456
3   Adams_Alma  Auchincloss_Jake   0.8997175        0.123456       0.123456    0.123456
4   Adams_Alma  Axne_Cynthia       0.8757062        0.123456       0.123456    0.123456
5   Adams_Alma  Baldwin_Tammy      0.9406780        0.123456       0.123456    0.123456
6   Adams_Alma  Barragán_Nanette   0.8495763        0.123456       0.123456    0.123456
7   Adams_Alma  Bass_Karen         0.8234463        0.123456       0.123456    0.123456
8   Adams_Alma  Beatty_Joyce       0.9014831        0.123456       0.123456    0.123456
9   Adams_Alma  Bennet_Michael     0.5183616        0.123456       0.123456    0.123456
10  Adams_Alma  Bera_Ami           0.8223870        0.123456       0.123456    0.123456

Using the code below, I am able to create a difference edgelist for one variable at a time, but my full dataframe has 90 variables I want differences for.

out <- with(norm_data, as.matrix(dist(setNames(norm_data$Authentic, norm_data$user))))
dif_g <- graph_from_adjacency_matrix (out, mode = 'undirected', weighted = TRUE)
dif_edge_list <- as_data_frame(dif_g, 'edges')
dif_edge_list$weight <- 1 - dif_edge_list$weight

I would like to have a single dataframe that has the difference scores for each pair of users across all variables. I'm assuming a loop might be the solution, but I can't figure out how to do this. Any help would be greatly appreciated. Let me know if you need any more info.

Dput Data:

Show in New WindowClear OutputExpand/Collapse Output
structure(list(user = structure(1:50, .Label = c("Adams_Alma",
"Aguilar_Pete", "Allred_Colin", "Auchincloss_Jake", "Axne_Cynthia",
"Baldwin_Tammy", "Barragán_Nanette", "Bass_Karen", "Beatty_Joyce",
"Bennet_Michael", "Bera_Ami", "Beyer_Donald", "Bishop_Sanford",
"Blumenthal_Richard", "Blunt_Rochester_Lisa", "Bonamici_Suzanne",
"Booker_Cory", "Bourdeaux_Carolyn", "Bowman_Jamaal", "Boyle_Brendan",
"Brown_Anthony", "Brown_Sherrod", "Brownley_Julia", "Bush_Cori",
"Bustos_Cheri", "Butterfield_George", "Cantwell_Maria", "Carbajal_Salud",
"Cárdenas_Tony", "Cardin_Benjamin", "Carper_Thomas", "Carson_André",
"Cartwright_Matthew", "Case_Ed", "Casey_Robert", "Casten_Sean",
"Castor_Kathy", "Castro_Joaquin", "Chu_Judy", "Cicilline_David",
"Clark_Katherine", "Clarke_Yvette", "Cleaver_Emanuel", "Clyburn_James",
"Cohen_Steve", "Connolly_Gerald", "Coons_Christopher", "Cooper_Jim",
"Correa_J", "Cortez_Masto_Catherine", "Costa_Jim", "Courtney_Joe",
"Craig_Angie", "Crist_Charlie", "Crow_Jason", "Cuellar_Henry",
"Davids_Sharice", "Davis_Danny", "Dean_Madeleine", "DeFazio_Peter",
"DeGette_Diana", "DeLauro_Rosa", "DelBene_Suzan", "Delgado_Antonio",
"Demings_Val", "DeSaulnier_Mark", "Deutch_Theodore", "Dingell_Debbie",
"Doggett_Lloyd", "Doyle_Michael", "Duckworth_Tammy", "Durbin_Richard",
"Escobar_Veronica", "Eshoo_Anna", "Espaillat_Adriano", "Evans_Dwight",
"Feinstein_Dianne", "Fletcher_Lizzie", "Foster_Bill", "Frankel_Lois",
"Gallego_Ruben", "Garamendi_John", "García_Jesús", "Garcia_Sylvia",
"Golden_Jared", "Gomez_Jimmy", "Gonzalez_Vicente", "Gottheimer_Josh",
"Green_Al", "Grijalva_Raúl", "Harder_Josh", "Hassan_Margaret",
"Hayes_Jahana", "Heinrich_Martin", "Higgins_Brian", "Himes_James",
"Hirono_Mazie", "Horsford_Steven", "Houlahan_Chrissy", "Hoyer_Steny",
"Huffman_Jared", "Jackson_Lee_Sheila", "Jacobs_Sara", "Jayapal_Pramila",
"Jeffries_Hakeem", "Johnson_Eddie", "Johnson_Henry", "Kaptur_Marcy",
"Keating_William", "Kelly_Mark", "Kelly_Robin", "Khanna_Ro",
"Kildee_Daniel", "Kilmer_Derek", "Kim_Andy", "Kind_Ron", "Kirkpatrick_Ann",
"Klobuchar_Amy", "Krishnamoorthi_Raja", "Kuster_Ann", "Lamb_Conor",
"Langevin_James", "Larsen_Rick", "Larson_John", "Lawrence_Brenda",
"Lawson_Al", "Leahy_Patrick", "Lee_Barbara", "Lee_Susie", "Leger_Fernandez_Teresa",
"Levin_Andy", "Levin_Mike", "Lieu_Ted", "Lofgren_Zoe", "Lowenthal_Alan",
"Luján_Ben", "Luria_Elaine", "Lynch_Stephen", "Malinowski_Tom",
"Maloney_Carolyn", "Maloney_Sean", "Manchin_Joe", "Manning_Kathy",
"Markey_Edward", "Matsui_Doris", "McBath_Lucy", "McCollum_Betty",
"McEachin_A", "McGovern_James", "McNerney_Jerry", "Meeks_Gregory",
"Menendez_Robert", "Meng_Grace", "Merkley_Jeff", "Mfume_Kweisi",
"Moore_Gwen", "Morelle_Joseph", "Moulton_Seth", "Mrvan_Frank",
"Murphy_Stephanie", "Murray_Patty", "Nadler_Jerrold", "Napolitano_Grace",
"Neal_Richard", "Neguse_Joe", "Newman_Marie", "Norcross_Donald",
"Norton_Eleanor", "O_Halleran_Tom", "Ocasio_Cortez_Alexandria",
"Omar_Ilhan", "Ossoff_Jon", "Padilla_Alejandro", "Pallone_Frank",
"Panetta_Jimmy", "Pappas_Chris", "Pascrell_Bill", "Payne_Donald",
"Pelosi_Nancy", "Perlmutter_Ed", "Peters_Gary", "Peters_Scott",
"Phillips_Dean", "Pingree_Chellie", "Plaskett_Stacey", "Pocan_Mark",
"Porter_Katie", "Pressley_Ayanna", "Price_David", "Quigley_Mike",
"Raskin_Jamie", "Reed_John", "Rice_Kathleen", "Rosen_Jacky",
"Ross_Deborah", "Roybal_Allard_Lucille", "Ruiz_Raul", "Ruppersberger_C",
"Rush_Bobby", "Ryan_Tim", "Sablan_Gregorio", "Sánchez_Linda",
"Sarbanes_John", "Scanlon_Mary", "Schakowsky_Janice", "Schatz_Brian",
"Schiff_Adam", "Schneider_Bradley", "Schrader_Kurt", "Schrier_Kim",
"Schumer_Charles", "Scott_David", "Scott_Robert", "Sewell_Terri",
"Shaheen_Jeanne", "Shelby_Richard", "Sherman_Brad", "Sherrill_Mikie",
"Sinema_Kyrsten", "Sires_Albio", "Slotkin_Elissa", "Smith_Adam",
"Smith_Tina", "Soto_Darren", "Spanberger_Abigail", "Speier_Jackie",
"Stabenow_Debbie", "Stanton_Greg", "Stevens_Haley", "Strickland_Marilyn",
"Suozzi_Thomas", "Swalwell_Eric", "Takano_Mark", "Tester_Jon",
"Thompson_Bennie", "Thompson_Mike", "Titus_Dina", "Tlaib_Rashida",
"Tonko_Paul", "Torres_Norma", "Torres_Ritchie", "Trahan_Lori",
"Trone_David", "Underwood_Lauren", "user", "Van_Hollen_Chris",
"Vargas_Juan", "Veasey_Marc", "Vela_Filemon", "Velázquez_Nydia",
"Warner_Mark", "Warnock_Raphael", "Warren_Elizabeth", "Wasserman_Schultz_Debbie",
"Waters_Maxine", "Watson_Coleman_Bonnie", "Welch_Peter", "Wexton_Jennifer",
"Whitehouse_Sheldon", "Wild_Susan", "Williams_Nikema", "Wilson_Frederica",
"Wyden_Ron", "Yarmuth_John"), class = "factor"), Authentic = c(0.0573884758364312,
0.243029739776952, 0.112453531598513, 0.961198884758364, 0.125,
0.139869888475836, 0.131737918215613, 0.174024163568773, 0.115706319702602,
0.325046468401487, 0.223048327137546, 0.087592936802974, 0.133364312267658,
0.190985130111524, 0.21003717472119, 0.0422862453531598, 0.153113382899628,
0.263708178438662, 0.157295539033457, 0.328996282527881, 0.139637546468401,
0.48025092936803, 0.26974907063197, 0.378020446096654, 0.153113382899628,
0.454693308550186, 0.0820167286245353, 0.130576208178439, 0.33317843866171,
0.263243494423792, 0.197490706319703, 0.295074349442379, 0.251626394052045,
0.303671003717472, 0.180065055762082, 0.155204460966543, 0.10246282527881,
0.237453531598513, 0.132434944237918, 0.151022304832714, 0.10339219330855,
0.991635687732342, 0.185176579925651, 0.263475836431227, 0.0669144981412639,
0.143587360594796, 0.127788104089219, 0.212360594795539, 0.45817843866171,
0.054135687732342), Analytic = c(0.751137397634213, 0.772520473157416,
0.777070063694267, 0.802092811646951, 0.86442220200182, 0.75796178343949,
0.847133757961783, 0.873976342129208, 0.816196542311192, 0.801182893539581,
0.809827115559599, 0.695177434030937, 0.803457688808007, 0.726569608735214,
0.774795268425842, 0.843039126478617, 0.788898999090082, 0.773885350318471,
0.79936305732484, 0.78434940855323, 0.939945404913557, 0.772520473157416,
0.741128298453139, 0.736123748862602, 0.927206551410373, 0.673794358507734,
0.859872611464968, 0.763421292083712, 0.810282074613285, 0.871701546860782,
0.834849863512284, 0.786624203821656, 0.782984531392174, 1, 0.872611464968152,
0.748862602365787, 0.804367606915377, 0.79936305732484, 0.682893539581438,
0.761601455868971, 0.722929936305732, 0.767970882620564, 0.845313921747043,
0.79663330300273, 0.74294813466788, 0.840764331210191, 0.894904458598726,
0.787534121929026, 0.800272975432211, 0.883530482256597), Clout = c(0.367584745762712,
0.387358757062147, 0.748234463276836, 0.267302259887006, 0.491878531073446,
0.426906779661017, 0.518008474576271, 0.191031073446328, 0.466101694915254,
0.849223163841808, 0.545197740112994, 0.475988700564972, 0.548728813559322,
0.711511299435028, 0.538841807909604, 0.792372881355932, 0.49364406779661,
0.487641242937853, 0.64795197740113, 0.370409604519774, 0.771186440677966,
0.288488700564972, 0.211158192090395, 0.273658192090395, 0.420197740112994,
1, 0.531779661016949, 0.629237288135593, 0.646539548022599, 0.208686440677966,
0.189618644067797, 0.92090395480226, 0.632415254237288, 0.965042372881356,
0.34180790960452, 0.392302259887005, 0.604166666666666, 0.548375706214689,
0.401836158192091, 0.415254237288136, 0.364759887005649, 0.332980225988701,
0.354519774011299, 0.346398305084746, 0.52295197740113, 0.453389830508474,
0.777189265536723, 0.332980225988701, 0.436087570621469, 0.387358757062147
), Tone = c(0.953877551020408, 0.791836734693877, 0.583469387755102,
0.49765306122449, 0.971122448979592, 0.994183673469388, 0.626836734693878,
0.893061224489796, 0.34469387755102, 0.68530612244898, 0.970204081632653,
0.698265306122449, 0.959795918367347, 0.379183673469388, 0.988469387755102,
0.930408163265306, 0.0593877551020408, 0.744897959183674, 0.884387755102041,
0.803367346938776, 0.659285714285714, 0.422244897959184, 0.283571428571429,
0.252755102040816, 0.926530612244898, 0.988265306122449, 0.76469387755102,
0.525408163265306, 0.817040816326531, 0.891428571428571, 0.81265306122449,
0.451632653061224, 0.654285714285714, 0.727244897959184, 0.974591836734694,
0.467448979591837, 0.798775510204082, 0.501122448979592, 0.919795918367347,
0.744897959183674, 0.83234693877551, 0.931224489795918, 0.866326530612245,
0.448673469387755, 0.766530612244898, 0.326734693877551, 0.847959183673469,
0.685204081632653, 0.78765306122449, 0.847755102040816)), row.names = 2:51, class = "data.frame")

Body:
# set as data.table
setDT(df)

# as.character (needed to rid permutation)
df[, user := as.character(user)]

# cross join
df_1 <- df[, as.list(df), names(df)]

# name change
x <- unlist(lapply(list('x.', 'i.'), \(i) paste0(i, names(df))))
names(df_1) <- x

# rid combo from replacement. Change to != for permutation
df_1 <- df_1[i.user < x.user]

# names net prefix
y <- gsub('x\\.|i\\.', '', x)

# construct formula
z <- lapply(2:5, \(i) paste0('diff_', y[i], '=', x[i], '-', x[i+5]))
a <- paste('.(' ,paste(unlist(z), collapse=','), ')')

# calculate diff
df_1[, eval(parse(text=a))]

and my personal fav. Benchmarking :)

# benchmark
library(tidyverse)
library(data.table)
library(microbenchmark)
library(ggplot2)

df <- data.table(user = 1:10000)
df[, `:=` (Authentic = user
           , Analytic = user
           , Clout = user
           , Tone = user
           )]
df[, user := as.character(user)]

xx <-
microbenchmark(sweepydodo = {
                              # cross join
                              df_1 <- df[, as.list(df), names(df)]

                              # name change
                              x <- unlist(lapply(list('x.', 'i.'), \(i) paste0(i, names(df))))
                              names(df_1) <- x

                              # rid combo from replacement. Change to != for permutation
                              df_1 <- df_1[i.user > x.user]

                              # names net prefix
                              y <- gsub('x\\.|i\\.', '', x)

                              # construct formula
                              z <- lapply(2:5, \(i) paste0('diff_', y[i], '=', x[i], '-', x[i+5]))
                              a <- paste('.(' ,paste(unlist(z), collapse=','), ')')

                              # calculate diff
                              df_1[, eval(parse(text=a))]
                              }
               , Onyambu = {
                            index <- which(lower.tri(diag(nrow(df))), T)
                            a <- data.frame(user1 = df[index[,2],1]
                                            , user2 = df[index[,1],1]
                                            , diff = df[index[,2],-1] - df[index[,1],-1]
                                            , row.names = NULL
                                            )
                            }
               , Onyambu_modified = {
                                      x <- 1:nrow(df)
                                      index <- CJ(a=x,b=x)[a>b]
                                      a <- data.table(user1 = df[index[[2]],1]
                                                      , user2 = df[index[[1]],1]
                                                      , diff = df[index[[2]],-1] - df[index[[1]],-1]
                                                      , row.names = NULL
                                                      )
                                      }
               , Iman = {
                          crossing(df, user2 = df$user) %>%
                            filter(user != user2) %>%
                            left_join(df, by = c("user2" = "user")) %>%
                            transmute(from = user,
                                        to = user2,
                                        Authentic_diff = Authentic.y - Authentic.x,
                                        Analytic_diff =  Analytic.y - Analytic.x,
                                        Clout_diff = Clout.y - Clout.x,
                                        Tone_diff = Tone.y - Tone.x
                                      )
                 }
               , times = 30
               )

# plot
autoplot(xx)


问:
IndexError: list index out of range (Chatbot is not working)
I Was Coding a chatbot, but it doesn't work Every time I Run my program and start A conversation.
I get that error code, why is that so and what can I do ?

Error Code

It says that there is something in line 46

```<code>def get_response(intents_list, intents_json):
tag = intents_list[0]["intent"] #line 46
list_of_intents = intents["intents"]
for i in list_of_intents:
    if i ["tag"] == tag:
        result = random.choice(i["response"])
        break
return result
</code>```

and it also says that there is a problem in line 59

```<code>while True:
message = input("")
ints = predict_class(message)
res = get_response(ints, intents) #line 59
print(res)
</code>```

答: It indeed looks kike predict_class returns an empty list so intents_list[0] does not exist and throws an out of bound on line 46. Line 59 is just the call stack, aka that is where you call the function that contains the error, which you do on that line.

Body:
I Was Coding a chatbot, but it doesn't work Every time I Run my program and start A conversation.
I get that error code, why is that so and what can I do ?

Error Code

It says that there is something in line 46

def get_response(intents_list, intents_json):
tag = intents_list[0]["intent"] #line 46
list_of_intents = intents["intents"]
for i in list_of_intents:
    if i ["tag"] == tag:
        result = random.choice(i["response"])
        break
return result

and it also says that there is a problem in line 59

while True:
message = input("")
ints = predict_class(message)
res = get_response(ints, intents) #line 59
print(res)


问:
Invalid application of sizeof to incomplete type with a struct
I have a  struct where I put all the information about the players. That's my struct:

```<code>struct player{
   int startingCapital;
   int currentCapital;
   int startingPosition;
   int currentPosition;
   int activePlayer;
   int canPlay;
};
</code>```

And that's my main:

```<code>#include <stdio.h>
#include <stdlib.h>
#include "header.h"

int main(int argc, char *argv[])
{  int s,i,numOfPlayers;
   struct player *players;
    printf("Give the number of players: \n");
    scanf("%d",&numOfPlayers);

    players = (struct player *)calloc(numOfPlayers,sizeof(struct player));

   system("PAUSE");
  return 0;
}
</code>```

I'm asking the user to give the number of players and then I try to allocate the needed memory. But I'm getting this compiler error that I can't figure out:

```<code>invalid application of `sizeof' to incomplete type `player'
</code>```

答:
Really late to the party here, but a special case of the reasons for this error cited above would simply be to reference a structure with sizeof() above where the structure is defined:</p>
```<code>int numElements = sizeof(myArray)/sizeof(myArray[0]);
.
.
.
myArray[] =
{
    {Element1},
    {Element2},
    {Element3}
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a  struct where I put all the information about the players. That's my struct:

struct player{
   int startingCapital;
   int currentCapital;
   int startingPosition;
   int currentPosition;
   int activePlayer;
   int canPlay;
};

And that's my main:

#include <stdio.h>
#include <stdlib.h>
#include "header.h"

int main(int argc, char *argv[])
{  int s,i,numOfPlayers;
   struct player *players;
    printf("Give the number of players: \n");
    scanf("%d",&numOfPlayers);

    players = (struct player *)calloc(numOfPlayers,sizeof(struct player));

   system("PAUSE");
  return 0;
}

I'm asking the user to give the number of players and then I try to allocate the needed memory. But I'm getting this compiler error that I can't figure out:

invalid application of `sizeof' to incomplete type `player'

Body:
Really late to the party here, but a special case of the reasons for this error cited above would simply be to reference a structure with sizeof() above where the structure is defined:

int numElements = sizeof(myArray)/sizeof(myArray[0]);
.
.
.
myArray[] =
{
    {Element1},
    {Element2},
    {Element3}
};


问:
sum() to remove bracket in a double list
I just saw someone wrote this below and got confused why sum() could be used to remove the bracket from another list:

```<code>pwd = [['x'], ['y'], ['z']]

a = sum(pwd, [])
print(a)          // ['x', 'y', 'z']
</code>```

By looking up sum() definition…

sum(iterable, /, start=0)`

iterable can be anything, list, tuples or dictionaries, but most importantly it should be numeric.

start is added to the sum of numbers in the iterable.
If start is not given in the syntax, it is assumed to be 0.

How does an empty list as start argument of sum() remove the list from another list? This puzzles me…could anyone demystify this?

答:
Adding lists just concatenates them so:

```<code>sum(pwd,[]) = [] + ['x'] + ['y'] + ['z']
            = ['x', 'y', 'z']
</code>```

We need the empty list because sum(x) is the same as sum(x,0)

and sum(pwd,0) → 0 + ['x'] + ['y'] + ['z']

which gives an error as an int cannot be added to a list.

Body:
I just saw someone wrote this below and got confused why sum() could be used to remove the bracket from another list:

pwd = [['x'], ['y'], ['z']]

a = sum(pwd, [])
print(a)          // ['x', 'y', 'z']

By looking up sum() definition…

sum(iterable, /, start=0)`

iterable can be anything, list, tuples or dictionaries, but most importantly it should be numeric.

start is added to the sum of numbers in the iterable.
If start is not given in the syntax, it is assumed to be 0.

How does an empty list as start argument of sum() remove the list from another list? This puzzles me…could anyone demystify this?

Body:
Adding lists just concatenates them so:

sum(pwd,[]) = [] + ['x'] + ['y'] + ['z']
            = ['x', 'y', 'z']

We need the empty list because sum(x) is the same as sum(x,0)

and sum(pwd,0) → 0 + ['x'] + ['y'] + ['z']

which gives an error as an int cannot be added to a list.


问:
Visual Studio 2017 VB: How can I make two buttons interact
just started on VB, hope you can help me.

I'm doing a project about a game called TFT, where each item is made with two components. My project consists of 9 buttons, and by pressing two of them (could be the same one), I want to be able to get the specific item (as a msgbox).

Don't know if there's a better way to do it but I'm open to suggestions!

答:
Here's an example that changes the "Check" button to Green when Button3 is selected, followed by Button7 being selected, otherwise it changes the "Check" button to Red.

The buttons are arranged in a standard keypad grid:

```<code>Button1 Button2 Button3
Button4 Button5 Button6
Button7 Button8 Button9
</code>```

Code:

```<code>Public Class Form1

    Private FirstButton As Button = Nothing
    Private SecondButton As Button = Nothing

    Private Buttons As List(Of Button)
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Buttons = New List(Of Button)(
            {Button1, Button2, Button3,
            Button4, Button5, Button6,
            Button7, Button8, Button9})
        Buttons.ForEach(Sub(b) b.Text = "")
    End Sub

    Private Sub AllButtons_Click(sender As Object, e As EventArgs) _
        Handles Button1.Click, Button2.Click, Button3.Click,
        Button4.Click, Button5.Click, Button6.Click,
        Button7.Click, Button8.Click, Button9.Click

        Dim curButton As Button = DirectCast(sender, Button)
        If IsNothing(FirstButton) Then
            FirstButton = curButton
            FirstButton.Text = "1"
        ElseIf IsNothing(SecondButton) Then
            SecondButton = curButton
            If curButton Is FirstButton Then
                curButton.Text = "1, 2"
            Else
                SecondButton.Text = "2"
            End If
        Else
            FirstButton.Text = ""
            SecondButton.Text = ""
            FirstButton = curButton
            FirstButton.Text = "1"
            SecondButton = Nothing
        End If
    End Sub
    Private Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
        If FirstButton Is Button3 AndAlso SecondButton Is Button7 Then
            btnCheck.BackColor = Color.Green
        Else
            btnCheck.BackColor = Color.Red
        End If
    End Sub

End Class
</code>```

Running example:

Body:
Here's an example that changes the "Check" button to Green when Button3 is selected, followed by Button7 being selected, otherwise it changes the "Check" button to Red.

The buttons are arranged in a standard keypad grid:

Button1 Button2 Button3
Button4 Button5 Button6
Button7 Button8 Button9

Code:

Public Class Form1

    Private FirstButton As Button = Nothing
    Private SecondButton As Button = Nothing

    Private Buttons As List(Of Button)
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Buttons = New List(Of Button)(
            {Button1, Button2, Button3,
            Button4, Button5, Button6,
            Button7, Button8, Button9})
        Buttons.ForEach(Sub(b) b.Text = "")
    End Sub

    Private Sub AllButtons_Click(sender As Object, e As EventArgs) _
        Handles Button1.Click, Button2.Click, Button3.Click,
        Button4.Click, Button5.Click, Button6.Click,
        Button7.Click, Button8.Click, Button9.Click

        Dim curButton As Button = DirectCast(sender, Button)
        If IsNothing(FirstButton) Then
            FirstButton = curButton
            FirstButton.Text = "1"
        ElseIf IsNothing(SecondButton) Then
            SecondButton = curButton
            If curButton Is FirstButton Then
                curButton.Text = "1, 2"
            Else
                SecondButton.Text = "2"
            End If
        Else
            FirstButton.Text = ""
            SecondButton.Text = ""
            FirstButton = curButton
            FirstButton.Text = "1"
            SecondButton = Nothing
        End If
    End Sub
    Private Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
        If FirstButton Is Button3 AndAlso SecondButton Is Button7 Then
            btnCheck.BackColor = Color.Green
        Else
            btnCheck.BackColor = Color.Red
        End If
    End Sub

End Class

Running example:


问:
How can I do "find and replace" inside a GitHub repository?
In my GitHub repository, I have many files and I have to change one of the words to another one. The problem is that, as the occurrences of that word is more than 200, I cannot change it one by one manually. Is there any way to facilitate this?</p>

答: In edit mode, press Ctrl + Shift + F, the editor will ask you: Replace, type the search word, then press Enter, the editor will ask you: With:, type the replacement word and press Enter. Then follow the menu.


问:
Is my Java solution O(n) or am I missing something?
My solution for a certain problem is apparently slower than 95% of solutions and I wanted to make sure that I was correct on the time complexity.

It looks to me like this code is O(n). I use a couple of loops that are at most O(n) and they aren't nested so I don't believe the solution is n^2.

I use a HashMap as storage and use HashMap methods which are O(1) inside my while and for-loop for insertion and look ups respectively.

Am I correct in that this solution is O(n) or am I missing something?

```<code> public int pairSum(ListNode head) {

    HashMap<Integer, Integer> nodeVals = new HashMap<Integer, Integer>();

    int count = 0;

    ListNode current = head;
    nodeVals.put(count, current.val);
    count++;

    while (current.next != null) {
        current = current.next;
        nodeVals.put(count, current.val);
        count++;
    }

    int maxTwinSum = 0;
    for (int i = 0; i < nodeVals.size() / 2; i++) {
        int currTwinSum;
        currTwinSum = nodeVals.get(i) + nodeVals.get(nodeVals.size() - 1 - i);
        if (currTwinSum > maxTwinSum) maxTwinSum = currTwinSum;
    }

    return maxTwinSum;
}
</code>```

答:
First off: HashMap methods are amortized O(1), which basically means that you can treat them as if they were O(1) if you use them often enough because that's what they'll be on average. But building a hashmap is still a "relatively expensive" operation (a notion that can't be expressed in bit-O notation, because that one only cares about the asymptotic worst case).

Second: you construct a complete, inefficient copy of the list in a HashMap which is probably slower than most other approaches.

The first optimization is to replace your HashMap with a simple ArrayList: you only use numeric and strictly monotonically increasing keys anyway, so a list is a perfect match.

Body:
My solution for a certain problem is apparently slower than 95% of solutions and I wanted to make sure that I was correct on the time complexity.

It looks to me like this code is O(n). I use a couple of loops that are at most O(n) and they aren't nested so I don't believe the solution is n^2.

I use a HashMap as storage and use HashMap methods which are O(1) inside my while and for-loop for insertion and look ups respectively.

Am I correct in that this solution is O(n) or am I missing something?

 public int pairSum(ListNode head) {

    HashMap<Integer, Integer> nodeVals = new HashMap<Integer, Integer>();

    int count = 0;

    ListNode current = head;
    nodeVals.put(count, current.val);
    count++;

    while (current.next != null) {
        current = current.next;
        nodeVals.put(count, current.val);
        count++;
    }

    int maxTwinSum = 0;
    for (int i = 0; i < nodeVals.size() / 2; i++) {
        int currTwinSum;
        currTwinSum = nodeVals.get(i) + nodeVals.get(nodeVals.size() - 1 - i);
        if (currTwinSum > maxTwinSum) maxTwinSum = currTwinSum;
    }

    return maxTwinSum;
}


问:
Broken terminal output when running docker-compose with -T
I have a script that I use to start commands on some docker-compose containers.

The script runs docker-compose exec -T {container} {command}.

I have to use the -T (Disable pseudo-TTY allocation. By default docker compose exec allocates a TTY) option because otherwise my precommit hook, which also runs this script, errors with a panic: provided file is not a console.

However when I run the script on my own terminal I get a broken output that looks like this :

```<code>run v1.22.10
            $ vite build
                        vite v2.7.13 building for production...
                                                               transforming...
                                                                              ✓ 378 modules transformed.
                                                                                rendering chunks...
                                                                                public/front/assets/Inter-Thin.77d96c1c.woff2                   97.30 KiB
                                                                                public/front/assets/Inter-ExtraLight.b6cd094a.woff2             101.79 KiB
                                                                                public/front/assets/Inter-ThinItalic.d82beee8.woff2             104.00 KiB
                                  public/front/assets/Inter-ExtraLightItalic.db229bf3.woff2       108.78 KiB
                                                                                public/front/assets/Inter-Light.36b86832.woff2                  101.89 KiB
                                                                                public/front/assets/Inter-LightItalic.737ac201.woff2            108.72 KiB
                                                                                public/front/assets/Inter-Regular.d612f121.woff2                96.55 KiB
                   public/front/assets/Inter-Medium.1b498b95.woff2                 103.44 KiB
                                                                                public/front/assets/Inter-Italic.900058df.woff2                 104.37 KiB
                                                                                public/front/assets/Inter-MediumItalic.81600858.woff2           109.55 KiB
                                                                                public/front/assets/Inter-SemiBold.15226129.woff2               103.32 KiB
     public/front/assets/Inter-SemiBoldItalic.3b6df7d0.woff2         109.42 KiB
                                                                               public/front/assets/Inter-BoldItalic.3f211964.woff2             109.19 KiB
                                                                                public/front/assets/Inter-Bold.c63158ba.woff2                   103.65 KiB
                                                                                public/front/assets/Inter-ExtraBoldItalic.cf6b1d6c.woff2        109.09 KiB
                                                                                public/front/assets/Inter-ExtraBold.307d9809.woff2              103.62 KiB
                                                                 public/front/assets/Inter-Black.fc10113c.woff2                  100.46 KiB
                                                                                public/front/assets/Inter-BlackItalic.bc80081d.woff2            106.20 KiB
                                                                                public/front/assets/TRYVesterbro-Light.59d4e0df.woff2           134.08 KiB
                                                                                public/front/assets/TRYVesterbro-Regular.cf9a26a9.woff2         139.92 KiB
                                                   public/front/assets/TRYVesterbro-Medium.116a42a4.woff2          142.17 KiB
                                                                                public/front/assets/TRYVesterbro-Bold.ac6caaee.woff2            144.62 KiB
                                                                                public/front/assets/TRYVesterbro-ExtraBold.9be0564d.woff2       142.90 KiB

</code>```

Without -T the output is fine (every line is aligned correctly) but the hook will not work with the previously stated error.

If that's relevant I use zsh for my shell but I tried running in bash and it doesn't solve the issue either.

Is there any way to fix the terminal output while retaining -T in docker-compose ?

答:
So after investigating I found that the output only contained \n and not \n\r. The missing \r is the reason the output skips a line but doesn't go back to the start (carriage return).

I made a simple bash function that I added to my .zshrc (you can add it to your .bashrc too).

clout() {
  $@ | sed 's/$/\r/'
}
```

Use it like this

clout your_command args

This function pipes the output of your command and adds a \r when it sees a \n.

This is the best solution I found. I am still open to better solutions if someone has one.

Body:
I have a script that I use to start commands on some docker-compose containers.

The script runs docker-compose exec -T {container} {command}.

I have to use the -T (Disable pseudo-TTY allocation. By default docker compose exec allocates a TTY) option because otherwise my precommit hook, which also runs this script, errors with a panic: provided file is not a console.

However when I run the script on my own terminal I get a broken output that looks like this :

run v1.22.10
            $ vite build
                        vite v2.7.13 building for production...
                                                               transforming...
                                                                              ✓ 378 modules transformed.
                                                                                rendering chunks...
                                                                                public/front/assets/Inter-Thin.77d96c1c.woff2                   97.30 KiB
                                                                                public/front/assets/Inter-ExtraLight.b6cd094a.woff2             101.79 KiB
                                                                                public/front/assets/Inter-ThinItalic.d82beee8.woff2             104.00 KiB
                                  public/front/assets/Inter-ExtraLightItalic.db229bf3.woff2       108.78 KiB
                                                                                public/front/assets/Inter-Light.36b86832.woff2                  101.89 KiB
                                                                                public/front/assets/Inter-LightItalic.737ac201.woff2            108.72 KiB
                                                                                public/front/assets/Inter-Regular.d612f121.woff2                96.55 KiB
                   public/front/assets/Inter-Medium.1b498b95.woff2                 103.44 KiB
                                                                                public/front/assets/Inter-Italic.900058df.woff2                 104.37 KiB
                                                                                public/front/assets/Inter-MediumItalic.81600858.woff2           109.55 KiB
                                                                                public/front/assets/Inter-SemiBold.15226129.woff2               103.32 KiB
     public/front/assets/Inter-SemiBoldItalic.3b6df7d0.woff2         109.42 KiB
                                                                               public/front/assets/Inter-BoldItalic.3f211964.woff2             109.19 KiB
                                                                                public/front/assets/Inter-Bold.c63158ba.woff2                   103.65 KiB
                                                                                public/front/assets/Inter-ExtraBoldItalic.cf6b1d6c.woff2        109.09 KiB
                                                                                public/front/assets/Inter-ExtraBold.307d9809.woff2              103.62 KiB
                                                                 public/front/assets/Inter-Black.fc10113c.woff2                  100.46 KiB
                                                                                public/front/assets/Inter-BlackItalic.bc80081d.woff2            106.20 KiB
                                                                                public/front/assets/TRYVesterbro-Light.59d4e0df.woff2           134.08 KiB
                                                                                public/front/assets/TRYVesterbro-Regular.cf9a26a9.woff2         139.92 KiB
                                                   public/front/assets/TRYVesterbro-Medium.116a42a4.woff2          142.17 KiB
                                                                                public/front/assets/TRYVesterbro-Bold.ac6caaee.woff2            144.62 KiB
                                                                                public/front/assets/TRYVesterbro-ExtraBold.9be0564d.woff2       142.90 KiB

Without -T the output is fine (every line is aligned correctly) but the hook will not work with the previously stated error.

If that's relevant I use zsh for my shell but I tried running in bash and it doesn't solve the issue either.

Is there any way to fix the terminal output while retaining -T in docker-compose ?

Body:
So after investigating I found that the output only contained \n and not \n\r. The missing \r is the reason the output skips a line but doesn't go back to the start (carriage return).

I made a simple bash function that I added to my .zshrc (you can add it to your .bashrc too).

clout() {
  $@ | sed 's/$/\r/'
}

Use it like this

clout your_command args

This function pipes the output of your command and adds a \r when it sees a \n.

This is the best solution I found. I am still open to better solutions if someone has one.


问:
Removing decimal places after second number
I have some raw data exported from my ERP. Most of the data has two decimals, but there are a few lines contain numbers with three or more decimal places... When summing up all data with powershell I have a 0,01€ discrepancy between my ERP PDF report and sum of exported data. I tracked the discrepancy to a single number - 2.205. Powershell rounds this number to 2.2 not 2.21 as expected. If I try any other number - 2.215, 2.225 they all get rounded to 2.22, 2.23..

Why is 2.205 not treated the same???

答:
If I try any other number - 2.215, 2.225 they all get rounded to 2.22, 2.23

Are you sure about that 2.23 result? Here's my reslts when I run it:

```<code>PS H:\> [math]::Round(2.205,2)
2.2
PS H:\> [math]::Round(2.215,2)
2.22
PS H:\> [math]::Round(2.225,2)
2.22
PS H:\> [math]::Round(2.235,2)
2.24
PS H:\> [math]::Round(2.245,2)
2.24
</code>```

Taken from Scripting guy:

Notice that here the decimal, .25, rounded down to .2. This is because the number (2) is even. In the following example, the .35 rounds up because the number (3) is odd.

To fix it, define Midpoint Routing per Microsoft's documentation:

```<code>[math]::Round(2.205,2,1)
</code>```

Body:
If I try any other number - 2.215, 2.225 they all get rounded to 2.22, 2.23

Are you sure about that 2.23 result? Here's my reslts when I run it:

PS H:\> [math]::Round(2.205,2)
2.2
PS H:\> [math]::Round(2.215,2)
2.22
PS H:\> [math]::Round(2.225,2)
2.22
PS H:\> [math]::Round(2.235,2)
2.24
PS H:\> [math]::Round(2.245,2)
2.24

Taken from Scripting guy:

Notice that here the decimal, .25, rounded down to .2. This is because the number (2) is even. In the following example, the .35 rounds up because the number (3) is odd.

To fix it, define Midpoint Routing per Microsoft's documentation:

[math]::Round(2.205,2,1)


问:
calculate bmi and output other inputs in python
I am working on a python code to calculate bmi and to perform other user inputs as well.
I have the code below using the OOP approach, but I think I am still missing some parts and is not working as expected. The expectations are:

Prompt the user repeatedly to enter a patient identification number (an int), patient name (a string), patient height in inches (a positive float), and patient weight in pounds (a positive float) until the user enters a negative number for the patient ID (see Step 5 below for more information on the requirement to repeat the inputs).

Be sure to check for validity of the input values for the height and the weight using while loop.

For each patient’s information entered, your code should compute the BMI. You must write a function to do this calculation. The function must accept the patient’s height (in inches) and weight (in pounds) as parameters and return the calculated BMI.

For each patient’s information entered, output a well-formatted result listing the patient’s ID, name, calculated BMI (output with 1 digit of precision) and associated category (Underweight, Obese, etc.). The use of f-strings to produce the formatted output is recommended.

Continue the process of gathering patient data until the user enters a negative number for the patient ID. Remember, this is a type of sentinel control that will require the use of a while loop to control the input process. Most of your application’s logic will effectively be contained within a large while loop (other than the required BMI function and a few other statements). You will have other loops and decision logic nested inside this sentinel control while loop.

With some googling and sort of modifying it.

```<code>class BodyMassIndex:

    def __init__(self, pid, name, weight, height):
        self.patient_id = pid
        self.name = name
        self.weight = weight
        self.height = height

    @property
    def body_mass_index(self):
        return round((self.weight * 703) / self.height ** 2, 1)

    @property
    def score(self):
        if 18.5 < self.body_mass_index < 25:
            return 'normal weight'
        elif 25 < self.body_mass_index < 30:
            return 'overweight'
        elif self.body_mass_index > 30:
            return 'obese'
        else:
            return 'underweight'

    def print_score(self):
        ##print('For {}:{}'.format(self.patient_id, self.name))
        print('Your Body Mass Index score is: {}'.format(self.body_mass_index))
        print('You are {}'.format(self.score))

def _get_user_info():
    while True:
        try:
            pid = int(input("Please enter your 5-digit patient id: "))
            p_name = str(input("Please enter patient first name and last name: "))
            weight = float(input('Enter weight in pounds: '))
            height = float(input('Enter height in inches: '))

            if 0 < weight and 0 < height < 107:
                return weight, height
            else:
                raise ValueError('Invalid height or weight. Let us start over.')
        except ValueError:
            print('Invalid height or weight input')
            continue

def calculate_bmi():
    pid, name, weight, height = _get_user_info()
    return BodyMassIndex(weight, height)

if __name__ == '__main__':
    bmi = calculate_bmi()
    bmi.print_score()
</code>```

After entering the four values, I get a valuetype error: expecting 4 but got 2, or something sounds like that. I appreciate your help in making this work.

答:
The return statement was missing the pid and the p_name values at lines 39 and 49.

The new code looks like this:

```<code>class BodyMassIndex:

    def __init__(self, pid, name, weight, height):
        self.patient_id = pid
        self.name = name
        self.weight = weight
        self.height = height

    @property
    def body_mass_index(self):
        return round((self.weight * 703) / self.height ** 2, 1)

    @property
    def score(self):
        if 18.5 < self.body_mass_index < 25:
            return 'normal weight'
        elif 25 < self.body_mass_index < 30:
            return 'overweight'
        elif self.body_mass_index > 30:
            return 'obese'
        else:
            return 'underweight'

    def print_score(self):
        ##print('For {}:{}'.format(self.patient_id, self.name))
        print('Your Body Mass Index score is: {}'.format(self.body_mass_index))
        print('You are {}'.format(self.score))

def _get_user_info():
    while True:
        try:
            pid = int(input("Please enter your 5-digit patient id: "))
            p_name = str(input("Please enter patient first name and last name: "))
            weight = float(input('Enter weight in pounds: '))
            height = float(input('Enter height in inches: '))

            if 0 < weight and 0 < height < 107:
                return pid, p_name, weight, height
            else:
                raise ValueError('Invalid height or weight. Let us start over.')
        except ValueError:
            print('Invalid height or weight input')
            continue

def calculate_bmi():
    pid, name, weight, height = _get_user_info()
    return BodyMassIndex(pid, name, weight, height)

if __name__ == '__main__':
    bmi = calculate_bmi()
    bmi.print_score()
</code>```

Body:
I am working on a python code to calculate bmi and to perform other user inputs as well.
I have the code below using the OOP approach, but I think I am still missing some parts and is not working as expected. The expectations are:

Prompt the user repeatedly to enter a patient identification number (an int), patient name (a string), patient height in inches (a positive float), and patient weight in pounds (a positive float) until the user enters a negative number for the patient ID (see Step 5 below for more information on the requirement to repeat the inputs).

Be sure to check for validity of the input values for the height and the weight using while loop.

For each patient’s information entered, your code should compute the BMI. You must write a function to do this calculation. The function must accept the patient’s height (in inches) and weight (in pounds) as parameters and return the calculated BMI.

For each patient’s information entered, output a well-formatted result listing the patient’s ID, name, calculated BMI (output with 1 digit of precision) and associated category (Underweight, Obese, etc.). The use of f-strings to produce the formatted output is recommended.

Continue the process of gathering patient data until the user enters a negative number for the patient ID. Remember, this is a type of sentinel control that will require the use of a while loop to control the input process. Most of your application’s logic will effectively be contained within a large while loop (other than the required BMI function and a few other statements). You will have other loops and decision logic nested inside this sentinel control while loop.

With some googling and sort of modifying it.

class BodyMassIndex:

    def __init__(self, pid, name, weight, height):
        self.patient_id = pid
        self.name = name
        self.weight = weight
        self.height = height

    @property
    def body_mass_index(self):
        return round((self.weight * 703) / self.height ** 2, 1)

    @property
    def score(self):
        if 18.5 < self.body_mass_index < 25:
            return 'normal weight'
        elif 25 < self.body_mass_index < 30:
            return 'overweight'
        elif self.body_mass_index > 30:
            return 'obese'
        else:
            return 'underweight'

    def print_score(self):
        ##print('For {}:{}'.format(self.patient_id, self.name))
        print('Your Body Mass Index score is: {}'.format(self.body_mass_index))
        print('You are {}'.format(self.score))

def _get_user_info():
    while True:
        try:
            pid = int(input("Please enter your 5-digit patient id: "))
            p_name = str(input("Please enter patient first name and last name: "))
            weight = float(input('Enter weight in pounds: '))
            height = float(input('Enter height in inches: '))

            if 0 < weight and 0 < height < 107:
                return weight, height
            else:
                raise ValueError('Invalid height or weight. Let us start over.')
        except ValueError:
            print('Invalid height or weight input')
            continue

def calculate_bmi():
    pid, name, weight, height = _get_user_info()
    return BodyMassIndex(weight, height)

if __name__ == '__main__':
    bmi = calculate_bmi()
    bmi.print_score()

After entering the four values, I get a valuetype error: expecting 4 but got 2, or something sounds like that. I appreciate your help in making this work.

Body:
The return statement was missing the pid and the p_name values at lines 39 and 49.

The new code looks like this:

class BodyMassIndex:

    def __init__(self, pid, name, weight, height):
        self.patient_id = pid
        self.name = name
        self.weight = weight
        self.height = height

    @property
    def body_mass_index(self):
        return round((self.weight * 703) / self.height ** 2, 1)

    @property
    def score(self):
        if 18.5 < self.body_mass_index < 25:
            return 'normal weight'
        elif 25 < self.body_mass_index < 30:
            return 'overweight'
        elif self.body_mass_index > 30:
            return 'obese'
        else:
            return 'underweight'

    def print_score(self):
        ##print('For {}:{}'.format(self.patient_id, self.name))
        print('Your Body Mass Index score is: {}'.format(self.body_mass_index))
        print('You are {}'.format(self.score))

def _get_user_info():
    while True:
        try:
            pid = int(input("Please enter your 5-digit patient id: "))
            p_name = str(input("Please enter patient first name and last name: "))
            weight = float(input('Enter weight in pounds: '))
            height = float(input('Enter height in inches: '))

            if 0 < weight and 0 < height < 107:
                return pid, p_name, weight, height
            else:
                raise ValueError('Invalid height or weight. Let us start over.')
        except ValueError:
            print('Invalid height or weight input')
            continue

def calculate_bmi():
    pid, name, weight, height = _get_user_info()
    return BodyMassIndex(pid, name, weight, height)

if __name__ == '__main__':
    bmi = calculate_bmi()
    bmi.print_score()


问:
How to cope with the initial null problem of the async pipe as a library developer
Suppose I'm a library developer and want to publish my cool component where I have a non nullable input data

```<code><styled-list [data]="[1,2,3,4]"></styled-list>
</code>```

My code in the component might look like this

```<code>export class StyledListComponent<T> {
  @Input()
  data: ReadonlyArray<T> = [];

  action() {
    console.log(this.data.length);
  }

}
</code>```

I don't want to focus on the initial null problem of the async pipe from a user perspective like here and instead on how I as a library provider should handle this.

In the above code the user of my component passes data through using the async pipe and the action is triggered before the data is actually resolved I get an error.

Should I as a library developer handle these errors or is this an inherent problem of angular's async pipe that users just have to cope with?

答:
Internally check for null values and silently filter these out.

This can be done if using setters

```<code>set data(data: ReadonlyArray<T>) {
  if (data === null) {
    return;
  }
  this._data = data;
}
</code>```

This can't be done for annotated variables though. Any access to the variable would need to perform the null check or probably the better option would be to just write a setter.

Although it does look a bit weird to be checking for existence if the typescript types don't allow null values to be passed in the first place. Other readers of the code will have to be aware of why this is done this way.

Body:
Suppose I'm a library developer and want to publish my cool component where I have a non nullable input data

My code in the component might look like this

export class StyledListComponent<T> {
  @Input()
  data: ReadonlyArray<T> = [];

  action() {
    console.log(this.data.length);
  }

}

I don't want to focus on the initial null problem of the async pipe from a user perspective like here and instead on how I as a library provider should handle this.

In the above code the user of my component passes data through using the async pipe and the action is triggered before the data is actually resolved I get an error.

Should I as a library developer handle these errors or is this an inherent problem of angular's async pipe that users just have to cope with?

Body:
Internally check for null values and silently filter these out.

This can be done if using setters

set data(data: ReadonlyArray<T>) {
  if (data === null) {
    return;
  }
  this._data = data;
}

This can't be done for annotated variables though. Any access to the variable would need to perform the null check or probably the better option would be to just write a setter.

Although it does look a bit weird to be checking for existence if the typescript types don't allow null values to be passed in the first place. Other readers of the code will have to be aware of why this is done this way.


问:
Elastic Search 5.0 and scroll api on aggregation
I'm using the elastic search 5 version and I want to use scroll API like here (doc) but I have to use it on aggregation. I have a query:

```<code>GET data/_search?scroll=2m
{
  "aggs": {
    "values"" {
      "terms": {
        "field": "currency",
        "size": 4
      }
    }
  }
}
</code>```

...and I get:

```<code>{
  "_scroll_id": "1234...a_lot_of_signs..."
  ...
  "hits": [...],
  "aggregations": {
    "values": {
      ...
      "buckets": [
         {
           "key": "EUR",
           "doc_count": 300
         },
         {
           "key": "YEN",
           "doc_count": 300
         },
         {
           "key": "USD",
           "doc_count": 300
         }
      ]
    }
  }
}
</code>```

...which gives me first free currencies. I want to get the next 3 currencies so I'm using:

```<code>GET _search/scroll
{
  "scroll_id": "<id>",
  "scroll": "2m"
}
</code>```

and gets:

```<code>{
  "_scroll_id": "next_id"
  ...
  "hits": [...]
}
</code>```

So, there are no results for my aggregation which I need. Is there a way to get next currencies?

答: You always get aggregations for the whole data, not only the hits you get back. That's why it makes sense to use "size": 0 if you only need aggregations: you get no hits back but all the aggs.

Body:
I'm using the elastic search 5 version and I want to use scroll API like here (doc) but I have to use it on aggregation. I have a query:

GET data/_search?scroll=2m
{
  "aggs": {
    "values"" {
      "terms": {
        "field": "currency",
        "size": 4
      }
    }
  }
}

...and I get:

{
  "_scroll_id": "1234...a_lot_of_signs..."
  ...
  "hits": [...],
  "aggregations": {
    "values": {
      ...
      "buckets": [
         {
           "key": "EUR",
           "doc_count": 300
         },
         {
           "key": "YEN",
           "doc_count": 300
         },
         {
           "key": "USD",
           "doc_count": 300
         }
      ]
    }
  }
}

...which gives me first free currencies. I want to get the next 3 currencies so I'm using:

GET _search/scroll
{
  "scroll_id": "<id>",
  "scroll": "2m"
}

and gets:

{
  "_scroll_id": "next_id"
  ...
  "hits": [...]
}

So, there are no results for my aggregation which I need. Is there a way to get next currencies?


问:
why am do i keep getting a 404 error code with postman when trying to receive the data?
for some reason i keep getting a 404 error code when trying to pull data from "Post" using postman</p>
```<code>       from fastapi import FastAPI

       app = FastAPI()

       @app.get("/")
       def message_to_world():
       return {"message": "hey there gay man"}

       app.get("/posts")
       def get_posts():
       return {"data": "This is your posts"}

       @app.post("/createposts")
       def post_create():
       return{"message": "Nice job"}
</code>```

答: Dont know if this is the answer as post is ambiguous from http post or your app.get /post. But app.get(/post) doesnt have the @ by it. Dont know the lang you're using that well but might just be a typo</p>

Body:
for some reason i keep getting a 404 error code when trying to pull data from "Post" using postman

       from fastapi import FastAPI

       app = FastAPI()

       @app.get("/")
       def message_to_world():
       return {"message": "hey there gay man"}

       app.get("/posts")
       def get_posts():
       return {"data": "This is your posts"}

       @app.post("/createposts")
       def post_create():
       return{"message": "Nice job"}


问:
php json_decode function doesn't work with me
when decoding this json file 'https://2geekproar.blogspot.com/feeds/posts/default?alt=json&callback=showpostcount' ,  Nothing appears to me
and i want o get $totalResults":{"$t":"4"} which equals '4' i want to decode this json file and get this value

my code

```<code><?php

$url = 'https://2geekproar.blogspot.com/feeds/posts/default?alt=json&callback=showpostcount' ;

$json = file_get_contents($url);

// Decode the JSON file
$json_data = json_decode($json,true);

// Display data
print_r($json_data);

?>
</code>```

答:
When you add echo json_last_error_msg(); to your script, you will see that you get the following error message:

```<code>Syntax error
</code>```

That indicates to you, that the string you are trying to decode is not a valid JSON string.

Because of that, you are getting no output.

var_dump($json_data); // Returns NULL
```
<p>So, because the string you are parsing is not well formatted, you have to check that out, viewing the URL shows:</p>
<pre class="lang-js prettyprint-override"><code>// API callback
showpostcount({"version":"1.0","encoding":"UTF-8","feed":
// …
</code>```

Which indeed is not a plain JSON object.

As pointed out in the comments under your question, you can fix that, by removing &callback=showpostcount from your request URL.

```<code>https://2geekproar.blogspot.com/feeds/posts/default?alt=json
</code>```

Will give you only your valid JSON object, which you can parse without problems:

{"version":"1.0","encoding":"UTF-8","feed":…
```
<p>Decodes to:</p>
```array(3) {
  ["version"]=>
  string(3) "1.0"
  ["encoding"]=>
  string(5) "UTF-8"
  ["feed"]=>
  array(18) {
    ["xmlns"]=> …
```

Body:
when decoding this json file 'https://2geekproar.blogspot.com/feeds/posts/default?alt=json&callback=showpostcount' ,  Nothing appears to me
and i want o get $totalResults":{"$t":"4"} which equals '4' i want to decode this json file and get this value

my code

<?php

$url = 'https://2geekproar.blogspot.com/feeds/posts/default?alt=json&callback=showpostcount' ;

$json = file_get_contents($url);

// Decode the JSON file
$json_data = json_decode($json,true);

// Display data
print_r($json_data);

?>

Body:
When you add echo json_last_error_msg(); to your script, you will see that you get the following error message:

Syntax error

That indicates to you, that the string you are trying to decode is not a valid JSON string.

Because of that, you are getting no output.

var_dump($json_data); // Returns NULL

So, because the string you are parsing is not well formatted, you have to check that out, viewing the URL shows:

// API callback
showpostcount({"version":"1.0","encoding":"UTF-8","feed":
// …

Which indeed is not a plain JSON object.

As pointed out in the comments under your question, you can fix that, by removing &callback=showpostcount from your request URL.

https://2geekproar.blogspot.com/feeds/posts/default?alt=json

Will give you only your valid JSON object, which you can parse without problems:

{"version":"1.0","encoding":"UTF-8","feed":…

Decodes to:

array(3) {
  ["version"]=>
  string(3) "1.0"
  ["encoding"]=>
  string(5) "UTF-8"
  ["feed"]=>
  array(18) {
    ["xmlns"]=> …


问:
Yocto recipe to compile C++ program with usb.h include
I would like to compile a c++ program in my yocto toolchain. For this, I added a new recipe that should compile the program and install it into the image.

My issue is that I have to include some kernel headers like `usb.h``

recipe.bb

```<code>SUMMARY = "Simple helloworld application"
SECTION = "examples"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI += "file://dcdc-nuc.h \
           file://dcdc-nuc.cpp \
           file://dcdc-nuc-console.cpp \
           "

S = "${WORKDIR}"

TARGET_CC_ARCH += "${LDFLAGS}"

do_compile() {
         ${CXX}  ${BUILD_CXXFLAGS}  dcdc-nuc-console.cpp -o dcdc-nuc
}

do_install() {
         install -d ${D}${bindir}
         install -m 0755 dcdc-nuc ${D}${bindir}
}

</code>```

Current message

```<code>
| In file included from dcdc-nuc-console.cpp:23:
| dcdc-nuc.h:23:10: fatal error: linux/usb.h: No such file or directory
|    23 | #include <usb.h>
|       |          ^~~~~~~
| compilation terminated.
| WARNING: exit code 1 from a shell command.

</code>```

I know that I have to make the compile aware of the kernel headers but I'm not able to find any hint on how to do this. Thanks for all the help in advance!

答:
I believe you need to add libusb as a dependence to your recipe.

Add the following line to your recipe:

```<code>DEPENDS = "libusb"
</code>```

Body:
I would like to compile a c++ program in my yocto toolchain. For this, I added a new recipe that should compile the program and install it into the image.

My issue is that I have to include some kernel headers like `usb.h``

recipe.bb

SUMMARY = "Simple helloworld application"
SECTION = "examples"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI += "file://dcdc-nuc.h \
           file://dcdc-nuc.cpp \
           file://dcdc-nuc-console.cpp \
           "

S = "${WORKDIR}"

TARGET_CC_ARCH += "${LDFLAGS}"

do_compile() {
         ${CXX}  ${BUILD_CXXFLAGS}  dcdc-nuc-console.cpp -o dcdc-nuc
}

do_install() {
         install -d ${D}${bindir}
         install -m 0755 dcdc-nuc ${D}${bindir}
}

Current message

| In file included from dcdc-nuc-console.cpp:23:
| dcdc-nuc.h:23:10: fatal error: linux/usb.h: No such file or directory
|    23 | #include <usb.h>
|       |          ^~~~~~~
| compilation terminated.
| WARNING: exit code 1 from a shell command.

I know that I have to make the compile aware of the kernel headers but I'm not able to find any hint on how to do this. Thanks for all the help in advance!

Body:
I believe you need to add libusb as a dependence to your recipe.

Add the following line to your recipe:

DEPENDS = "libusb"


问:
Is `-ftree-slp-vectorize` not enabled by `-O2` in GCC?
From https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html

It says "-ftree-slp-vectorize: Perform basic block vectorization on trees. This flag is enabled by default at -O2 and by -ftree-vectorize, -fprofile-use, and -fauto-profile."

However it seems I have to pass a flag explicitly to turn on SIMD. Did I mis undertand something here? It is enabled at -O3 though.

https://www.godbolt.org/z/1ffzdqMoT

答:
Is -ftree-slp-vectorize not enabled by -O2 in GCC?

Yes and no. It depends on the version of the compiler.

From https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html

You have linked to the latest version of documentation. It applies to the version that is currently under development, which at the moment is version 12.

However it seems I have to pass a flag explicitly to turn on SIMD.

https://www.godbolt.org/z/1ffzdqMoT

Your example uses GCC version 11.

Did I mis undertand something here?

You read the wrong version of documentation, or used wrong version of compiler and hence your assumption didn't hold.


问:
DialogFlow CX flow not routing to next page when using page parameter
I have a  page that has an entry fulfillment and route to another page. The intent that maps to the route has training phrases for @sys.number variable which map to parameter id: number. I also have a page parameter my_variable of type sys.number. The Route condition is set to Match at least one rule.

When I test this in the test agent, my input gets mapped to the correct parameter. However, the test agent does not proceed to the next page. If I enter input a second time, then I am routed to the next page. How can I achieve being routed to the next page after my first initial input?

答: Adding the following condition resolves my issue.


问:
Performing pivot_longer() over multiple sets of columns
I am stuck in performing pivot_longer() over multiple sets of columns. Here is the sample dataset

```<code>df <- data.frame(
  id = c(1, 2),
  uid = c("m1", "m2"),
  germ_kg = c(23, 24),
  mineral_kg = c(12, 17),
  perc_germ = c(45, 34),
  perc_mineral = c(78, 10))
</code>```

I need the output dataframe to look like this

```<code>out <- df <- data.frame(
  id = c(1, 1, 2, 2),
  uid = c("m1", "m1", "m2", "m2"),
  crop = c("germ", "germ", "mineral", "mineral"),
  kg = c(23, 12, 24, 17),
  perc = c(45, 78, 34, 10))
</code>```

答:
```<code>df %>%
  rename_with(~str_replace(.x,'(.*)_kg', 'kg_\\1')) %>%
  pivot_longer(-c(id, uid), names_to = c('.value', 'crop'), names_sep = '_')

# A tibble: 4 x 5
     id uid   crop       kg  perc
  <dbl> <chr> <chr>   <dbl> <dbl>
1     1 m1    germ       23    45
2     1 m1    mineral    12    78
3     2 m2    germ       24    34
4     2 m2    mineral    17    10
</code>```

If you were to use data.table:

```<code>library(data.table)
melt(setDT(df), c('id', 'uid'), patterns(kg = 'kg', perc = 'perc'))
  id uid variable kg perc
1:  1  m1        1 23   45
2:  2  m2        1 24   34
3:  1  m1        2 12   78
4:  2  m2        2 17   10
</code>```

Body:
I am stuck in performing pivot_longer() over multiple sets of columns. Here is the sample dataset

df <- data.frame(
  id = c(1, 2),
  uid = c("m1", "m2"),
  germ_kg = c(23, 24),
  mineral_kg = c(12, 17),
  perc_germ = c(45, 34),
  perc_mineral = c(78, 10))

I need the output dataframe to look like this

out <- df <- data.frame(
  id = c(1, 1, 2, 2),
  uid = c("m1", "m1", "m2", "m2"),
  crop = c("germ", "germ", "mineral", "mineral"),
  kg = c(23, 12, 24, 17),
  perc = c(45, 78, 34, 10))

Body:
df %>%
  rename_with(~str_replace(.x,'(.*)_kg', 'kg_\\1')) %>%
  pivot_longer(-c(id, uid), names_to = c('.value', 'crop'), names_sep = '_')

# A tibble: 4 x 5
     id uid   crop       kg  perc
  <dbl> <chr> <chr>   <dbl> <dbl>
1     1 m1    germ       23    45
2     1 m1    mineral    12    78
3     2 m2    germ       24    34
4     2 m2    mineral    17    10

If you were to use data.table:

library(data.table)
melt(setDT(df), c('id', 'uid'), patterns(kg = 'kg', perc = 'perc'))
  id uid variable kg perc
1:  1  m1        1 23   45
2:  2  m2        1 24   34
3:  1  m1        2 12   78
4:  2  m2        2 17   10


问:
Is it possible to extract colour values (such as average RGB) for different regions of the face using iOS ARKit?
Is it possible to extract colour values (such as average RGB) for different regions of the face using iOS ARKit? I have seen example of overlaying a 3D mesh over the face consisting of triangular pieces. Is there anyway to perform any kind of region wise-colour filtering such as extracting RGB average, histograms, max/min values (same as what CIFilter allows on normal frameS) but through ARKit's 3D face tracker?

I have also seen ARFaceAnchor.BlendShapeLocation allowing coefficients on movements of various elements across the face. Is there anyway to extract the mesh (and specifically its colour and other characteristic) for specific elements across the face such as nose, cheeks, lips, forehead, eyes, etc.?

答:
See my answer here about how to get the realtime texture of the user's face using ARKIt

Once you have the face texture, you can sample the rgb data however and wherever you'd like. If you are only interested in a specific region:

Update the code from the linked project in the answer to only sample from a specific region (one very basic approach would be to only draw that part of the mesh you care about)

Sample regions from the entire 2D face texture. One challenge with this approach is that all your sampling regions would need to be defined on the 2D texture


答:
I suspect there might be a simpler way using pivot_long_spec, but one tricky thing here is that your column names don't have a consistent ordering of their semantic components. @Onyambu's answer deals with this nicely by fixing it upsteam.

```<code>library(tidyverse)
df %>%
  pivot_longer(-c(id, uid)) %>%
  separate(name, c("col1", "col2")) %>%                 # only needed
  mutate(crop = if_else(col2 == "kg", col1, col2),      # because name
         meas = if_else(col2 == "kg", col2, col1)) %>%  # structure
  select(id, uid, crop, meas, value) %>%                # is
  pivot_wider(names_from = meas, values_from = value)   # inconsistent

# A tibble: 4 x 5
     id uid   crop       kg  perc
  <dbl> <chr> <chr>   <dbl> <dbl>
1     1 m1    germ       23    45
2     1 m1    mineral    12    78
3     2 m2    germ       24    34
4     2 m2    mineral    17    10
</code>```

Title: Performing pivot_longer() over multiple sets of columns

Body:
I suspect there might be a simpler way using pivot_long_spec, but one tricky thing here is that your column names don't have a consistent ordering of their semantic components. @Onyambu's answer deals with this nicely by fixing it upsteam.

library(tidyverse)
df %>%
  pivot_longer(-c(id, uid)) %>%
  separate(name, c("col1", "col2")) %>%                 # only needed
  mutate(crop = if_else(col2 == "kg", col1, col2),      # because name
         meas = if_else(col2 == "kg", col2, col1)) %>%  # structure
  select(id, uid, crop, meas, value) %>%                # is
  pivot_wider(names_from = meas, values_from = value)   # inconsistent

# A tibble: 4 x 5
     id uid   crop       kg  perc
  <dbl> <chr> <chr>   <dbl> <dbl>
1     1 m1    germ       23    45
2     1 m1    mineral    12    78
3     2 m2    germ       24    34
4     2 m2    mineral    17    10