问:
jq - how to conditionally filter out objects
I'm trying to vastly simplify a large JSON file, and part of that process is conditionally filtering out some of the objects. I have a series of conditions I'd like to apply, but I'm not able to get even a single condition to work properly.

I've been working with the jq documentation, but I'm not a pro developer so it's challenging to read it. I found an example of this in another stackoverflow thread, so I've been trying to adapt that.

My source JSON file, while large, is clean and well-formed. It's basically one flat array of objects. A few of the keys in the objects are arrays as well, but I'll be discarding most of those anyway. Below is a sample, showing the first object:

```<code>[
   {
      "object":"card",
      "id":"86bf43b1-8d4e-4759-bb2d-0b2e03ba7012",
      "oracle_id":"0004ebd0-dfd6-4276-b4a6-de0003e94237",
      "multiverse_ids":[
         15862
      ],
      "mtgo_id":15870,
      "mtgo_foil_id":15871,
      "tcgplayer_id":3094,
      "name":"Static Orb",
      "lang":"en",
      "released_at":"2001-04-11",
      "uri":"https://api.scryfall.com/cards/86bf43b1-8d4e-4759-bb2d-0b2e03ba7012",
      "scryfall_uri":"https://scryfall.com/card/7ed/319/static-orb?utm_source=api",
      "layout":"normal",
      "highres_image":true,
      "mana_cost":"{3}",
      "cmc":3.0,
      "type_line":"Artifact",
      "oracle_text":"As long as Static Orb is untapped, players can't untap more than two permanents during their untap steps.",
      "colors":[

      ],
      "color_identity":[

      ],
      "legalities":{
         "standard":"not_legal",
         "future":"not_legal",
         "historic":"not_legal",
         "pioneer":"not_legal",
         "modern":"not_legal",
         "legacy":"legal",
         "pauper":"not_legal",
         "vintage":"legal",
         "penny":"not_legal",
         "commander":"legal",
         "brawl":"not_legal",
         "duel":"legal",
         "oldschool":"not_legal"
      },
      "games":[
         "paper",
         "mtgo"
      ],
      "reserved":false,
      "foil":true,
      "nonfoil":true,
      "oversized":false,
      "promo":false,
      "reprint":true,
      "variation":false,
      "set":"7ed",
      "set_name":"Seventh Edition",
      "set_type":"core",
      "collector_number":"319",
      "digital":false,
      "rarity":"rare",
      "flavor_text":"The warriors fought against the paralyzing waves until even their thoughts froze in place.",
      "card_back_id":"0aeebaf5-8c7d-4636-9e82-8c27447861f7",
      "artist":"Terese Nielsen",
      "artist_ids":[
         "eb55171c-2342-45f4-a503-2d5a75baf752"
      ],
      "illustration_id":"6f8b3b2c-252f-4f95-b621-712c82be38b5",
      "border_color":"white",
      "frame":"1997",
      "full_art":false,
      "textless":false,
      "booster":true,
      "story_spotlight":false,
      "edhrec_rank":1836,
      "prices":{
         "usd":"17.07",
         "usd_foil":"72.02",
         "eur":"10.73",
         "tix":"0.79"
      },
      "related_uris":{
         "gatherer":"https://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=15862",
         "tcgplayer_decks":"https://decks.tcgplayer.com/magic/deck/search?contains=Static+Orb\u0026page=1\u0026utm_campaign=affiliate\u0026utm_medium=api\u0026utm_source=scryfall",
         "edhrec":"https://edhrec.com/route/?cc=Static+Orb",
         "mtgtop8":"https://mtgtop8.com/search?MD_check=1\u0026SB_check=1\u0026cards=Static+Orb"
      }
   }
]

</code>```

First, I'm attempting to add a condition which will remove objects where the key "reprint" has the value true. This is what I've got so far:

curl -s https://archive.scryfall.com/bulk-data/default-cards/default-cards-20200529170427.json | jq .[] - "map(select(.reprint[] | contains (\"true\")))" > reprints_removed.json

But I keep getting this error:

jq: error: Could not open file map(select(.reprint[] | contains ("true"))): No such file or directory

Once I've got that working, I'd like to start using compound conditions. So, for instance, next I'll remove objects where either the key "reprint" is "true" or the key "border_color" is "silver".

Where am I going wrong?

答:
The value of .reprint in each of the objects in the top-level array is strictly boolean, as can be seen by running:

```<code>jq 'map(.reprint)|unique'
</code>```

So an efficient way to select the objects for which .reprint is false is to use the filter:

```<code>map(select(.reprint == false))
</code>```

This will preserve the array structure.  If you just want the JSON objects as a stream, you could write:

```<code>.[] | select(.reprint == false)
</code>```

Since .reprint is strictly boolean, there are various equivalent formulations of the condition.

Negation

If .reprint were multi-valued, then to exclude the objects for which .reprint == true you could use negation:

```<code>.[] | select(.reprint == true | not)
</code>```

Notice that in jq, not is a 0-ary filter -- it has no argument.

Compound conditions

remove objects where either the key "reprint" is "true" or the key "border_color" is "silver".

```<code>map(select( (.reprint == true or .border_color == "silver") | not))
</code>```

Body:
I'm trying to vastly simplify a large JSON file, and part of that process is conditionally filtering out some of the objects. I have a series of conditions I'd like to apply, but I'm not able to get even a single condition to work properly.

I've been working with the jq documentation, but I'm not a pro developer so it's challenging to read it. I found an example of this in another stackoverflow thread, so I've been trying to adapt that.

My source JSON file, while large, is clean and well-formed. It's basically one flat array of objects. A few of the keys in the objects are arrays as well, but I'll be discarding most of those anyway. Below is a sample, showing the first object:

[
   {
      "object":"card",
      "id":"86bf43b1-8d4e-4759-bb2d-0b2e03ba7012",
      "oracle_id":"0004ebd0-dfd6-4276-b4a6-de0003e94237",
      "multiverse_ids":[
         15862
      ],
      "mtgo_id":15870,
      "mtgo_foil_id":15871,
      "tcgplayer_id":3094,
      "name":"Static Orb",
      "lang":"en",
      "released_at":"2001-04-11",
      "uri":"https://api.scryfall.com/cards/86bf43b1-8d4e-4759-bb2d-0b2e03ba7012",
      "scryfall_uri":"https://scryfall.com/card/7ed/319/static-orb?utm_source=api",
      "layout":"normal",
      "highres_image":true,
      "mana_cost":"{3}",
      "cmc":3.0,
      "type_line":"Artifact",
      "oracle_text":"As long as Static Orb is untapped, players can't untap more than two permanents during their untap steps.",
      "colors":[

      ],
      "color_identity":[

      ],
      "legalities":{
         "standard":"not_legal",
         "future":"not_legal",
         "historic":"not_legal",
         "pioneer":"not_legal",
         "modern":"not_legal",
         "legacy":"legal",
         "pauper":"not_legal",
         "vintage":"legal",
         "penny":"not_legal",
         "commander":"legal",
         "brawl":"not_legal",
         "duel":"legal",
         "oldschool":"not_legal"
      },
      "games":[
         "paper",
         "mtgo"
      ],
      "reserved":false,
      "foil":true,
      "nonfoil":true,
      "oversized":false,
      "promo":false,
      "reprint":true,
      "variation":false,
      "set":"7ed",
      "set_name":"Seventh Edition",
      "set_type":"core",
      "collector_number":"319",
      "digital":false,
      "rarity":"rare",
      "flavor_text":"The warriors fought against the paralyzing waves until even their thoughts froze in place.",
      "card_back_id":"0aeebaf5-8c7d-4636-9e82-8c27447861f7",
      "artist":"Terese Nielsen",
      "artist_ids":[
         "eb55171c-2342-45f4-a503-2d5a75baf752"
      ],
      "illustration_id":"6f8b3b2c-252f-4f95-b621-712c82be38b5",
      "border_color":"white",
      "frame":"1997",
      "full_art":false,
      "textless":false,
      "booster":true,
      "story_spotlight":false,
      "edhrec_rank":1836,
      "prices":{
         "usd":"17.07",
         "usd_foil":"72.02",
         "eur":"10.73",
         "tix":"0.79"
      },
      "related_uris":{
         "gatherer":"https://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=15862",
         "tcgplayer_decks":"https://decks.tcgplayer.com/magic/deck/search?contains=Static+Orb\u0026page=1\u0026utm_campaign=affiliate\u0026utm_medium=api\u0026utm_source=scryfall",
         "edhrec":"https://edhrec.com/route/?cc=Static+Orb",
         "mtgtop8":"https://mtgtop8.com/search?MD_check=1\u0026SB_check=1\u0026cards=Static+Orb"
      }
   }
]

First, I'm attempting to add a condition which will remove objects where the key "reprint" has the value true. This is what I've got so far:

curl -s https://archive.scryfall.com/bulk-data/default-cards/default-cards-20200529170427.json | jq .[] - "map(select(.reprint[] | contains (\"true\")))" > reprints_removed.json

But I keep getting this error:

jq: error: Could not open file map(select(.reprint[] | contains ("true"))): No such file or directory

Once I've got that working, I'd like to start using compound conditions. So, for instance, next I'll remove objects where either the key "reprint" is "true" or the key "border_color" is "silver".

Where am I going wrong?

Body:
The value of .reprint in each of the objects in the top-level array is strictly boolean, as can be seen by running:

jq 'map(.reprint)|unique'

So an efficient way to select the objects for which .reprint is false is to use the filter:

map(select(.reprint == false))

This will preserve the array structure.  If you just want the JSON objects as a stream, you could write:

.[] | select(.reprint == false)

Since .reprint is strictly boolean, there are various equivalent formulations of the condition.

Negation

If .reprint were multi-valued, then to exclude the objects for which .reprint == true you could use negation:

.[] | select(.reprint == true | not)

Notice that in jq, not is a 0-ary filter -- it has no argument.

Compound conditions

remove objects where either the key "reprint" is "true" or the key "border_color" is "silver".

map(select( (.reprint == true or .border_color == "silver") | not))


来源: stackexchange

问:
Change specific values in dataframe
I have df like this:

```<code>Name   Value       NUM_SC

A      1000        421

B      2000        127

C      3000        511

D      2000        718

E      1500        511 (may duplicate)
</code>```

And I would like to multiply some Values by (-1) based on their NUM_SC. For example, for 511 and 127 in NUM_SC multiply Value by (-1). What worked for me is:

```<code>for i in negative_sc:
    for j in range(76818):
        if df.NUM_SC[j] == i:
            df.Values[j] *= (-1)
</code>```

where  negative_sc containts NUM_SC for which I would like multiply Value by (-1). In this example negative_sc = (511,127).

But this method takes a lot of time. I tried something like this:

```<code>for i in negative_sc:
   df[df.NUM_SC == i].Values *= (-1)
</code>```

But this produced error and didn't yield any results.

What is the best way to handle tasks like this? Change values in one column based on values in another column

Thanks a lot!

答:
You should not chain [ ] and .column_name. So both df.Values[j] *= -1 and df[df.NUM_SC == i].Values *= -1 don't work. See this document for details.

Instead do:

```<code>df.loc[df.NUM_SC.isin(negative_sc), 'Values'] *= -1
</code>```

ContentLicense: CC BY-SA 4.0

Title: Change specific values in dataframe

Body:
I have df like this:

Name   Value       NUM_SC

A      1000        421

B      2000        127

C      3000        511

D      2000        718

E      1500        511 (may duplicate)

And I would like to multiply some Values by (-1) based on their NUM_SC. For example, for 511 and 127 in NUM_SC multiply Value by (-1). What worked for me is:

for i in negative_sc:
    for j in range(76818):
        if df.NUM_SC[j] == i:
            df.Values[j] *= (-1)

where  negative_sc containts NUM_SC for which I would like multiply Value by (-1). In this example negative_sc = (511,127).

But this method takes a lot of time. I tried something like this:

for i in negative_sc:
   df[df.NUM_SC == i].Values *= (-1)

But this produced error and didn't yield any results.

What is the best way to handle tasks like this? Change values in one column based on values in another column

Thanks a lot!

Body:
You should not chain [ ] and .column_name. So both df.Values[j] *= -1 and df[df.NUM_SC == i].Values *= -1 don't work. See this document for details.

Instead do:

df.loc[df.NUM_SC.isin(negative_sc), 'Values'] *= -1


问:
Calculate Percentile Value using MySQL
I have a table which contains thousands of rows and I would like to calculate the 90th percentile for one of the fields, called 'round'.

For example, select the value of round which is at the 90th percentile.

I don't see a straightforward way to do this in MySQL.

Can somebody provide some suggestions as to how I may start this sort of calculation?

Thank you!

答:
Compare solutions:

Number of seconds it took on my server to get 99 percentile of 1.3 million rows:

LIMIT x,y with index and no where: 0.01 seconds

LIMIT x,y with no where: 0.7 seconds

LIMIT x,y with where: 2.3 seconds

Full scan with no where: 1.6 seconds

Full scan with where: 5.7 seconds

Fastest solution for large tables using LIMIT x,y ():

Get count of values: SELECT COUNT(*) AS cnt FROM t

Get nth value, where n = (cnt - 1) * (1 - 0.95) : SELECT k FROM t ORDER BY k DESC LIMIT n,1

This solution requires two queries, because mysql does not support specifying variables in LIMIT clause, except for stored procedures (can be optimized with stored procedure). Usually additional query overhead is very low

This solution can be further optimized if you add index to k column and do not use complex where clauses (like 0.01 second for table with 1 million rows, because sorting is not needed).

Implementation example in PHP (can calculate percentile not only of columns, but also of expressions):

```<code>function get_percentile($table, $where, $expr, $percentile) {
  if ($where) $subq = "WHERE $where";
  else $subq = "";

  $r = query("SELECT COUNT(*) AS cnt FROM $table $subq");
  $w = mysql_fetch_assoc($r);
  $num = abs(round(($w['cnt'] - 1) * (100 - $percentile) / 100.0));

  $q = "SELECT ($expr) AS prcres FROM $table $subq ORDER BY ($expr) DESC LIMIT $num,1";
  $r = query($q);
  if (!mysql_num_rows($r)) return null;
  $w = mysql_fetch_assoc($r);
  return $w['prcres'];
}

// Usage example
$time = get_percentile(
  "state", // table
  "service='Time' AND cnt>0 AND total>0", // some filter
  "total/cnt", // expression to evaluate
  80); // percentile
</code>```

ContentLicense: CC BY-SA 3.0

Title: Calculate Percentile Value using MySQL

Body:
Compare solutions:

Number of seconds it took on my server to get 99 percentile of 1.3 million rows:

LIMIT x,y with index and no where: 0.01 seconds

LIMIT x,y with no where: 0.7 seconds

LIMIT x,y with where: 2.3 seconds

Full scan with no where: 1.6 seconds

Full scan with where: 5.7 seconds

Fastest solution for large tables using LIMIT x,y ():

Get count of values: SELECT COUNT(*) AS cnt FROM t

Get nth value, where n = (cnt - 1) * (1 - 0.95) : SELECT k FROM t ORDER BY k DESC LIMIT n,1

This solution requires two queries, because mysql does not support specifying variables in LIMIT clause, except for stored procedures (can be optimized with stored procedure). Usually additional query overhead is very low

This solution can be further optimized if you add index to k column and do not use complex where clauses (like 0.01 second for table with 1 million rows, because sorting is not needed).

Implementation example in PHP (can calculate percentile not only of columns, but also of expressions):

function get_percentile($table, $where, $expr, $percentile) {
  if ($where) $subq = "WHERE $where";
  else $subq = "";

  $r = query("SELECT COUNT(*) AS cnt FROM $table $subq");
  $w = mysql_fetch_assoc($r);
  $num = abs(round(($w['cnt'] - 1) * (100 - $percentile) / 100.0));

  $q = "SELECT ($expr) AS prcres FROM $table $subq ORDER BY ($expr) DESC LIMIT $num,1";
  $r = query($q);
  if (!mysql_num_rows($r)) return null;
  $w = mysql_fetch_assoc($r);
  return $w['prcres'];
}

// Usage example
$time = get_percentile(
  "state", // table
  "service='Time' AND cnt>0 AND total>0", // some filter
  "total/cnt", // expression to evaluate
  80); // percentile


问:
How to call a function in mainwindow from secondwindow(widget) with a button
I am able to call a variable (result) into second window(widget) from MainWindow with using below code:

MainWindow:

```<code>def Two_items_show(self):
    self.Two_Items = QtWidgets.QWidget()
    self.ui = Ui_Two_Items(self.result)
    self.ui.setupUi(self.Two_Items)
    self.Two_Items.show()
</code>```

Second Window:

```<code>class Ui_Two_Items(object):
    def __init__(self, result = ''):
        self.result = result
</code>```

The Question is:
Mainwindow has a function, and second window has a push button, I want to  call that function from second window with the push button.

Second Window:

```<code>self.btn.clicked.connect(self.change)

def change(self):
    self.delete_item()
</code>```

MainWindow:

```<code> def delete_item(self):
    ...
    ...
</code>```

If it is possible please let me know the solution..

答:
What you may do is to add the parent in the init method of your window as:

```<code>def __init__(self, result=None, parent=None)
</code>```

You would call your MainWindow function as:

```<code>def change(self):
    parent.delete_item()
</code>```

And to open your second window from the Main,

```<code>win = UI_Two_Items(result=xx,parent=self)
</code>```

Hope it works for you.

Body:
I am able to call a variable (result) into second window(widget) from MainWindow with using below code:

MainWindow:

def Two_items_show(self):
    self.Two_Items = QtWidgets.QWidget()
    self.ui = Ui_Two_Items(self.result)
    self.ui.setupUi(self.Two_Items)
    self.Two_Items.show()

Second Window:

class Ui_Two_Items(object):
    def __init__(self, result = ''):
        self.result = result

The Question is:
Mainwindow has a function, and second window has a push button, I want to  call that function from second window with the push button.

Second Window:

self.btn.clicked.connect(self.change)

def change(self):
    self.delete_item()

MainWindow:

 def delete_item(self):
    ...
    ...

If it is possible please let me know the solution..

Body:
What you may do is to add the parent in the init method of your window as:

def __init__(self, result=None, parent=None)

You would call your MainWindow function as:

def change(self):
    parent.delete_item()

And to open your second window from the Main,

win = UI_Two_Items(result=xx,parent=self)

Hope it works for you.


问:
Interaction between redux and useEffect
I was working on a function which loads some data to a component artificially ie. recreates a page display based on the uploaded data.
I am facing issues with when useEffect gets called.
Here is the code:

```<code>const funcA = (props) => {
    let a = [1, 2, 3];
    let b = [2, 3];
    setSelected(a);
    setParam(b);
    return (
        <div>...</div>
);
}

const funcB = (props) => {
    useEffect(
        () => {
            setParam([]);
        },
        [props.selected]
    );
    return (<div>...</div>);
}
</code>```

setSelected() and setParam() are actions which modify my redux store.
Now When I change selected using setSelected() in funcA, useEffect is called in funcB which modifies the param data based on selected values.
I thought this should not be an issue as I am calling setParam() after calling setSelected but it seems useEffect is getting executed after setParam().

So long story short, this is the order I want them to execute in:

setSelected()

useEffect() (because of change in selected)

setParam()

but they are executing in this order:

setSelected()

setParam()

useEffect() (because of change in selected)

Any help is appreciated. Thanks!!

答:
In the react world you should generally not rely on the order in which your setSomething() functions are called.

React "collects" state update calls, and decides the most efficient way to update the state.

Instead of thinking in "call order", you should think in "what should state B be if state A is X ?".

Instead of "change state if user clicks", think of "what does the user want so get/see ?".

Not good:

setSelected()

useEffect() (because of change in selected)

setParam()

Better:

setSelected()

useEffect() (calls setParam(), because of change in selected)

useEffect() (calls setParam(), because of ... why ?)

You probably have to rethink, and change the structure of your state a bit.

Title: Interaction between redux and useEffect

Body:
I was working on a function which loads some data to a component artificially ie. recreates a page display based on the uploaded data.
I am facing issues with when useEffect gets called.
Here is the code:

const funcA = (props) => {
    let a = [1, 2, 3];
    let b = [2, 3];
    setSelected(a);
    setParam(b);
    return (

...

);
}

const funcB = (props) => {
    useEffect(
        () => {
            setParam([]);
        },
        [props.selected]
    );
    return (
...
);
}

setSelected() and setParam() are actions which modify my redux store.
Now When I change selected using setSelected() in funcA, useEffect is called in funcB which modifies the param data based on selected values.
I thought this should not be an issue as I am calling setParam() after calling setSelected but it seems useEffect is getting executed after setParam().

So long story short, this is the order I want them to execute in:

setSelected()

useEffect() (because of change in selected)

setParam()

but they are executing in this order:

setSelected()

setParam()

useEffect() (because of change in selected)

Any help is appreciated. Thanks!!


问:
Should one table reference every other table
I'm working on an application that routinely gathers information from a large number of websites and saves it to a mysql database with a table for each site. The idea is to create a sort of customizable news feed.

stackoverflow_table(id, url, title, date)

reddit_table(id, title, url, author, date)

github_commit_table(id,
commit_message, author, repository,
branch, date)

twitter_table(id, tweet, author, url, date)

etc...

I want the ability to request any number of news items and filter out certain sites too. As an example:

Show newest 100 items but exclude items from Twitter and GitHub.

It seems like the best way to handle this is to create a table that just has foreign keys and website names.

master_table(id, website, date, foreign_key)

and I can just query the foreign ids I need from this table.

Am I going about this horribly wrong?

答:
Some ideas which you may find useful:

As you said, you can put all common properties in one table :
master_table(id, website, date, foreign_key,url)
Then create another table:

details_tables(id, master_id, property_name, property_value, property_type) which is used to retrieve data specific to each site. I believe it will give more flexibility than storing everything in json . If you expect many records in these tables, consider using partitioning.

You can also keep the existing table structure, but add a view :

SELECT 'Stack Overflow' as site_name, id, url, date

  FROM stackoverflow_table
  UNION

  SELECT 'Reddit' as site_name, id, url, date

  FROM reddit_table
  ...etc


问:
Filtering patient data - how to return bool/string for patients taking two different medications?
I have a very large data set that contains patient-level information on drug names. I am wanting to find patients that are taking certain combinations of drugs but I am having difficulties finding a simple method without creating two subset dataframes and mapping them back to the original dataframe using R.

Here is a fake patient dataframe in R

```<code>df <- data.frame(pt_id=["p1","p2","p3","p4","p1","p2","p3","p4"],
                 drug=["d1","d1","d1","d1","d2","d2","d3","d3"])
show(df)
##      pt_id     drug
## 1       p1       d1
## 2       p2       d1
## 3       p3       d1
## 4       p4       d1
## 5       p1       d2
## 6       p2       d2
## 7       p3       d3
## 8       p4       d3
</code>```

How do I get the following?

```<code>##      pt_id     drug   drug_combo
## 1       p1       d1         TRUE
## 2       p2       d1         TRUE
## 3       p3       d1        FALSE
## 4       p4       d1        FALSE
## 5       p1       d2         TRUE
## 6       p2       d2         TRUE
## 7       p3       d3        FALSE
## 8       p4       d3        FALSE
</code>```

Where only patients taking "d1" and "d2" (i.e. "p1" and "p2" in this example) are returned TRUE or a per-specified string like "on_d1_d2"

Thank you in advance!

答:
This checks if both "d1" and "d2" are present for pt_id.

```<code>library(dplyr)
df %>% group_by(pt_id) %>% mutate(drug_combo = all(c('d1', 'd2') %in% drug))

#  pt_id drug  drug_combo
#  <chr> <chr> <lgl>
#1 p1    d1    TRUE
#2 p2    d1    TRUE
#3 p3    d1    FALSE
#4 p4    d1    FALSE
#5 p1    d2    TRUE
#6 p2    d2    TRUE
#7 p3    d3    FALSE
#8 p4    d3    FALSE
</code>```

You can also do this in base R :

```<code>df$drug_combo <- with(df,ave(drug, pt_id, FUN = function(x)
                      all(c('d1', 'd2') %in% x)))
</code>```

and data.table

```<code>library(data.table)
setDT(df)[, drug_combo := all(c('d1', 'd2') %in% drug), pt_id]
</code>```

Body:
I have a very large data set that contains patient-level information on drug names. I am wanting to find patients that are taking certain combinations of drugs but I am having difficulties finding a simple method without creating two subset dataframes and mapping them back to the original dataframe using R.

Here is a fake patient dataframe in R

df <- data.frame(pt_id=["p1","p2","p3","p4","p1","p2","p3","p4"],
                 drug=["d1","d1","d1","d1","d2","d2","d3","d3"])
show(df)
##      pt_id     drug
## 1       p1       d1
## 2       p2       d1
## 3       p3       d1
## 4       p4       d1
## 5       p1       d2
## 6       p2       d2
## 7       p3       d3
## 8       p4       d3

How do I get the following?

##      pt_id     drug   drug_combo
## 1       p1       d1         TRUE
## 2       p2       d1         TRUE
## 3       p3       d1        FALSE
## 4       p4       d1        FALSE
## 5       p1       d2         TRUE
## 6       p2       d2         TRUE
## 7       p3       d3        FALSE
## 8       p4       d3        FALSE

Where only patients taking "d1" and "d2" (i.e. "p1" and "p2" in this example) are returned TRUE or a per-specified string like "on_d1_d2"

Thank you in advance!

Body:
This checks if both "d1" and "d2" are present for pt_id.

library(dplyr)
df %>% group_by(pt_id) %>% mutate(drug_combo = all(c('d1', 'd2') %in% drug))

#  pt_id drug  drug_combo
#  <chr> <chr> <lgl>
#1 p1    d1    TRUE
#2 p2    d1    TRUE
#3 p3    d1    FALSE
#4 p4    d1    FALSE
#5 p1    d2    TRUE
#6 p2    d2    TRUE
#7 p3    d3    FALSE
#8 p4    d3    FALSE

You can also do this in base R :

df$drug_combo <- with(df,ave(drug, pt_id, FUN = function(x)
                      all(c('d1', 'd2') %in% x)))

and data.table

library(data.table)
setDT(df)[, drug_combo := all(c('d1', 'd2') %in% drug), pt_id]


问:
How to assert a null object in dolphindb?
I can create a null objects in dolphindb like

```<code>x = 00i;
y = 00l;
</code>```

but when I run

```<code>00i == 00l
eqObj(00i,00l)
</code>```

they are all return true，I can't make a distinction between two null value or objects, is there any function to do that?

what I want :

```<code>x = 00i
x == somefunction(somevalue)
</code>```

to assert x is a null value in correct type

答:
```<code>def identicalNullObj(a, b){
    return a == b && a.type() == b.type()
}
</code>```

Body:
I can create a null objects in dolphindb like

x = 00i;
y = 00l;

but when I run

00i == 00l
eqObj(00i,00l)

they are all return true，I can't make a distinction between two null value or objects, is there any function to do that?

what I want :

x = 00i
x == somefunction(somevalue)

to assert x is a null value in correct type


问:
Change color text with click on Angular
I want to make a simple thing that the user input a color that he choose and make the color begin on some paragraph .

The input and the click button that the user send the inputColor to the typescript  :

```<code><form>
    <input #inputColor  type="text"/>
    <button type="button" (click)="changeColorText(inputColor)"></button>
    </form>
</code>```

The function changeColorText() on the typescript :

```<code>export class HelloWorld implements OnInit {
public inputColor:string;

  constructor() { }

  ngOnInit(): void {
  }

  public changeColorText(str:string) :void {
    this.inputColor = str;
  }

}
</code>```

The problem :

The paragraph change the color if i choose one (Witout input from the user) :

```<code><p style="color:blue">Hello World !</p>
</code>```

But I want what the user put in the box to make the paragraph like the color that sent, I couldn't find the correct syntax here:

```<code><p style="color:{{inputColor}}">Hello World !</p> // ERROR !!!!

<p style=`color:{{inputColor}}`>Hello World !</p> // No compilation error .. but not working:
</code>```

答:
You should use a style binding as following, details can be found at https://angular.io/guide/template-syntax:</p>

```<code><p [style.color]="inputColor" >Hello World !</p>
</code>```

Title: Change color text with click on Angular

Body:
I want to make a simple thing that the user input a color that he choose and make the color begin on some paragraph .

The input and the click button that the user send the inputColor to the typescript  :

<form>
    <input #inputColor  type="text"/>
    <button type="button" (click)="changeColorText(inputColor)"></button>
    </form>

The function changeColorText() on the typescript :

export class HelloWorld implements OnInit {
public inputColor:string;

  constructor() { }

  ngOnInit(): void {
  }

  public changeColorText(str:string) :void {
    this.inputColor = str;
  }

}

The problem :

The paragraph change the color if i choose one (Witout input from the user) :

Hello World !

But I want what the user put in the box to make the paragraph like the color that sent, I couldn't find the correct syntax here:

Hello World !
 // ERROR !!!!

<p style=`color:{{inputColor}}`>Hello World !
 // No compilation error .. but not working:

Body:
You should use a style binding as following, details can be found at https://angular.io/guide/template-syntax:

<p [style.color]="inputColor" >Hello World !</p>


问:
JavaScript Removing Elements Dynamically! removeChild
Technology I am using is materialize and vanilla js. I've created a materialize button that opens a model. within the model is a form that takes user input, then places the input text onto the main page, when the Submit button is triggered. then I have a button that should remove/delete the input posted. So the issue I'm having is that the JavaScript linked to the button which should delete/removeChild isn't working. please help :)

// ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', () => {
    var elems = document.querySelectorAll('.modal');
    var instances = M.Modal.init(elems);
  });

//Delete From The Dom
const delExerciseBtn = document.querySelector('.del-exercise-btn');

delExerciseBtn.addEventListener('click', (e) => {
if(e.target.className == 'delete'){
  const h6 = e.target.parentElement;
  delExerciseBtn.removeChild(h6);
}

});

// Add User's To the Dom.
const addExerciseDom = document.querySelector('.exercise-dom');
const exerciseForm = document.querySelector('.exercises-form');
const disabledExersiceBtn = document.querySelector('.disabled-exersicebtn');

exerciseForm.addEventListener('submit', (e) => {
e.preventDefault();

  // Get Input Value
  const value = exerciseForm.querySelector('input[type="text"]').value;

  // Create Elements
  const h6 = document.createElement('h6');

  // Add Content
  h6.textContent = value;

  // Append To Dom
  addExerciseDom.appendChild(h6);

  //Disable Btn
  disabledExersiceBtn.setAttribute('disabled', 'disabled');

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en">
<head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <title></title>

      <!-- Google icons -->
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">

      <!-- Compiled and minified CSS -->
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

      <!-- Sytle.css -->
      <link rel="stylesheet" type="text/css" href="style.css">

</head>
<body>

<!----- user's input ------->
<div class="row">
  <div class="col s12 center valign-wrapper center-align">
   <div class=" exercise-dom delete"> <!--Users text input h6----> </div>
   </div>
</div>

<!-- Btn/Modals/form -->
   <div class="row">
   <!-- Dom Btn -->
    <div class="col s12 center ">

        <i class="material-icons white-text">add </i>

    </div>

   <!-- Modal/form -->
  <div class="modal modal-position" id="exercise">
   <div class="modal-content">

    <div class="row exercises-padding">
     <form class="col s12 exercises-form" autocomplete="off">
       <div class="input-field col s10">
         <i class="material-icons prefix">fitness_center</i>
          <input type="text" id="autocomplete-input"  class="autocomplete center">
            <label for="autocomplete-input" ><h6>Exercises</h6></label>
       </div>
       <div class="modal-footer">
         <input class="modal-close btn black" type="submit" value="Submit">
       </div>
     </form>
    </div>
   </div>
  </div>

<!-- Remove Users Btn -->
  <div class="col s12 center remove-padding">

      <i class="material-icons white-text ">remove </i>

  </div>

     <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

     <!-- app.JavaScript -->
    <script src="app.js"></script>
</body>
</html></code>```

答:
```<code>const h6 = e.target.parentElement;
delExerciseBtn.removeChild(h6);
</code>```

You are trying to remove its parent from a button. And you need to remove the button from the parent.

```<code>const h6 = e.target.parentElement;
h6.removeChild(e.target);
</code>```

Body:
Technology I am using is materialize and vanilla js. I've created a materialize button that opens a model. within the model is a form that takes user input, then places the input text onto the main page, when the Submit button is triggered. then I have a button that should remove/delete the input posted. So the issue I'm having is that the JavaScript linked to the button which should delete/removeChild isn't working. please help :)

// ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', () => {
    var elems = document.querySelectorAll('.modal');
    var instances = M.Modal.init(elems);
  });

//Delete From The Dom
const delExerciseBtn = document.querySelector('.del-exercise-btn');

delExerciseBtn.addEventListener('click', (e) => {
if(e.target.className == 'delete'){
  const h6 = e.target.parentElement;
  delExerciseBtn.removeChild(h6);
}

});

// Add User's To the Dom.
const addExerciseDom = document.querySelector('.exercise-dom');
const exerciseForm = document.querySelector('.exercises-form');
const disabledExersiceBtn = document.querySelector('.disabled-exersicebtn');

exerciseForm.addEventListener('submit', (e) => {
e.preventDefault();

  // Get Input Value
  const value = exerciseForm.querySelector('input[type="text"]').value;

  // Create Elements
  const h6 = document.createElement('h6');

  // Add Content
  h6.textContent = value;

  // Append To Dom
  addExerciseDom.appendChild(h6);

  //Disable Btn
  disabledExersiceBtn.setAttribute('disabled', 'disabled');

});

      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <title></title>

      <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">

      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

      <link rel="stylesheet" type="text/css" href="style.css">

        add

     <form class="col s12 exercises-form" autocomplete="off">

         fitness_center
          <input type="text" id="autocomplete-input"  class="autocomplete center">

Exercises

         <input class="modal-close btn black" type="submit" value="Submit">

     </form>

      remove

Body:
const h6 = e.target.parentElement;
delExerciseBtn.removeChild(h6);

You are trying to remove its parent from a button. And you need to remove the button from the parent.

const h6 = e.target.parentElement;
h6.removeChild(e.target);


问:
Prevent Modal Rerendering when only Modal Content Change: React Hooks useReducer
I have a parent-child component Modal and ModalContent in my React App both functional.

1) I have created an AppContext in App.js for accessing it globally in all components.

const [state, dispatch] = useReducer(reducer, {modalOpen: false, content: []});

```<code>    <AppContext.Provider value={{ state, dispatch }} >
      //BrowserRouter and Routes Definition
    </App>
</code>```

Here reducer is a fairly plain function with toggle for modalOpen and push/pop functionality in content(array).

2) My Modal Component makes use of

```<code>const { state, dispatch } = useContext(AppContext);
<Modal open={state.modalOpen} />
</code>```

to get the state of modal visibility to set it open/closed.

3) My ModalContent Component makes use of

```<code>const { state, dispatch } = useContext(AppContext);
<ModalContent data={state.content} />
  //Dispatch from the `ModalContent`
  dispatch({ type: 'UPDATE_CONTENT', data: 'newata' });
</code>```

4) Here is my reducer.

```<code>export const reducer = (state, action) => {
switch (action.type) {
    case 'TOGGLE_MODAL':
            return {...state, modalOpen: !state.modalOpen};
    case 'UPDATE_CONTENT':
        return { ...state, content: [...state.content, action.data]};
    default:
        return {modalOpen: false,content: []};
 }
}
</code>```

I have set up some code in ModalContent to update the data content property using dispatch and the reducer store is updated perfectly and returns fresh/updated:

```<code> {modalOpen: true/false, content: updatedContentArray}
</code>```

The issue is: Whenever I dispatch an action via ModalContent complete state is returned(expected), by the reducer and Modal reopens itself as it listens to state.modalOpen.

Unsuccessful Attempt: I attempted to specifically pull required properties in respective components. But the Modal component still rerenders even when just content is changed. Is there any way to watch for specific state only

How can make this work by rerendering only ModalContent not Modal.

Edit: Updated question with my mock(working) reducer code and dispatch statement from the ModalContent itself.

答:
As @Shubham said you have to keep modal state and modal content separate.

It can be done with separate context or even simple useState

Example snippet

const { useReducer, createContext, useContext, useState, useEffect, memo, useMemo } = React;

const AppContext = createContext();

const reducer = (state, action) => {
  if(action.type == 'toggleModal') {
    return {
      ...state,
      modalOpen: !state.modalOpen
    }
  }

  return state;
}

const AppContextProvider = ({children}) => {
  const [state, dispatch] = useReducer(reducer, {modalOpen: false, content: [{id: 1, value: 'test'}]});

  return <AppContext.Provider value={{state, dispatch}}>
    {children}
  </AppContext.Provider>
}

const Modal = ({children, modalOpen}) => {
  const { state, dispatch } = useContext(AppContext);

  console.log('Render Modal');

  return <div className={`modal ${modalOpen ? 'modal--open': null}`}>
    {children}

}

const ModalContent = ({data, onClick}) => {

  console.log('Render Modal Content');

  return

    {data.map(({id, value}) =>
{value}
)}
    <button onClick={onClick} className="modal__close">Close</button>

}

const App = () => {
  const { state, dispatch } = useContext(AppContext);
  const { modalOpen, } = state;
  const [content, setContent] = useState([]);

  const onClick = () => {
    dispatch({ type: 'toggleModal' });
  }

  return

    <Modal modalOpen={modalOpen}>
      {useMemo(() => {

  console.log('render useMemo');

  return <ModalContent onClick={onClick} data={content}></ModalContent>
  }, [content])}
    </Modal>
    <button onClick={onClick}>Open Modal</button>

}

ReactDOM.render(
    <AppContextProvider>
      <App />
    </AppContextProvider>,
    document.getElementById('root')
  );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
  background: black;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: -1;
  transition: all .3s ease-in;
}

.modal__close {
  padding: .5rem 1rem;
  color: white;
  border: 1px solid white;
  background: transparent;
  cursor: pointer;
}

.modal--open {
  opacity: 1;
  z-index: 1;
}

.item {
  padding: 1rem;
  color: white;
  border: 1px solid white;
}</code>```

```

Body:
I have a parent-child component Modal and ModalContent in my React App both functional.

1) I have created an AppContext in App.js for accessing it globally in all components.

const [state, dispatch] = useReducer(reducer, {modalOpen: false, content: []});

    <AppContext.Provider value={{ state, dispatch }} >
      //BrowserRouter and Routes Definition
    </App>

Here reducer is a fairly plain function with toggle for modalOpen and push/pop functionality in content(array).

2) My Modal Component makes use of

const { state, dispatch } = useContext(AppContext);
<Modal open={state.modalOpen} />

to get the state of modal visibility to set it open/closed.

3) My ModalContent Component makes use of

const { state, dispatch } = useContext(AppContext);
<ModalContent data={state.content} />
  //Dispatch from the `ModalContent`
  dispatch({ type: 'UPDATE_CONTENT', data: 'newata' });

4) Here is my reducer.

export const reducer = (state, action) => {
switch (action.type) {
    case 'TOGGLE_MODAL':
            return {...state, modalOpen: !state.modalOpen};
    case 'UPDATE_CONTENT':
        return { ...state, content: [...state.content, action.data]};
    default:
        return {modalOpen: false,content: []};
 }
}

I have set up some code in ModalContent to update the data content property using dispatch and the reducer store is updated perfectly and returns fresh/updated:

 {modalOpen: true/false, content: updatedContentArray}

The issue is: Whenever I dispatch an action via ModalContent complete state is returned(expected), by the reducer and Modal reopens itself as it listens to state.modalOpen.

Unsuccessful Attempt: I attempted to specifically pull required properties in respective components. But the Modal component still rerenders even when just content is changed. Is there any way to watch for specific state only

How can make this work by rerendering only ModalContent not Modal.

Edit: Updated question with my mock(working) reducer code and dispatch statement from the ModalContent itself.

Body:
As @Shubham said you have to keep modal state and modal content separate.

It can be done with separate context or even simple useState

Example snippet

const { useReducer, createContext, useContext, useState, useEffect, memo, useMemo } = React;

const AppContext = createContext();

const reducer = (state, action) => {
  if(action.type == 'toggleModal') {
    return {
      ...state,
      modalOpen: !state.modalOpen
    }
  }

  return state;
}

const AppContextProvider = ({children}) => {
  const [state, dispatch] = useReducer(reducer, {modalOpen: false, content: [{id: 1, value: 'test'}]});

  return <AppContext.Provider value={{state, dispatch}}>
    {children}
  </AppContext.Provider>
}

const Modal = ({children, modalOpen}) => {
  const { state, dispatch } = useContext(AppContext);

  console.log('Render Modal');

  return <div className={`modal ${modalOpen ? 'modal--open': null}`}>
    {children}
  </div>
}

const ModalContent = ({data, onClick}) => {

  console.log('Render Modal Content');

  return <div className="modal__content">
    {data.map(({id, value}) => <div className="item" key={id}>{value}</div>)}
    <button onClick={onClick} className="modal__close">Close</button>
  </div>
}

const App = () => {
  const { state, dispatch } = useContext(AppContext);
  const { modalOpen, } = state;
  const [content, setContent] = useState([]);

  const onClick = () => {
    dispatch({ type: 'toggleModal' });
  }

  return <div>
    <Modal modalOpen={modalOpen}>
      {useMemo(() => {

  console.log('render useMemo');

  return <ModalContent onClick={onClick} data={content}></ModalContent>
  }, [content])}
    </Modal>
    <button onClick={onClick}>Open Modal</button>
  </div>
}

ReactDOM.render(
    <AppContextProvider>
      <App />
    </AppContextProvider>,
    document.getElementById('root')
  );

.modal {
  background: black;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: -1;
  transition: all .3s ease-in;
}

.modal__close {
  padding: .5rem 1rem;
  color: white;
  border: 1px solid white;
  background: transparent;
  cursor: pointer;
}

.modal--open {
  opacity: 1;
  z-index: 1;
}

.item {
  padding: 1rem;
  color: white;
  border: 1px solid white;
}

<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>


问:
c# Protected base class only used for inheritance
Struggling a bit with inheritance here. I have common properties to use in two derived classes, so I made a base class LogBaseViewModel. I don't ever want this base class to be used except to be inherited by derived classes, so I made it protected (also tried private).

I found this bit, and maybe I'm mis-interpreting, but thought if I wrapped all 3 of these classes within one, they'd no longer be "outside" and hence this would be allowed.

From section 3.5.3 of the C# 5 specification:

When a protected instance member is accessed outside the program text
  of the class in which it is declared, and when a protected internal
  instance member is accessed outside the program text of the program in
  which it is declared, the access must take place within a class
  declaration that derives from the class in which it is declared.
  Furthermore, the access is required to take place through an instance
  of that derived class type or a class type constructed from it.

However, no joy, I get the error: Error CS0060 Inconsistent accessibility: base class 'LogViewModels.LogBaseViewModel' is less accessible than class 'LogViewModels.LogSearchViewModel'.

```<code>public class LogViewModels
{
    protected class LogBaseViewModel
    {
        public int Id { get; set; }
        public string Level { get; set; }
        public string Message { get; set; }
        public string Exception { get; set; }
    }

    public class LogSearchViewModel : LogBaseViewModel
    {

        public DateTime? FromDate { get; set; }
        public DateTime? ToDate { get; set; }
    }

    public class LogViewModel : LogBaseViewModel
    {
        public System.DateTime Date { get; set; }
    }
}
</code>```

答:
Applying the protected modifier on LogBaseViewModel would make it accessible only inside LogViewModels, and in subclasses of LogViewModels, not subclasses of LogBaseViewModel.

From here:

A protected member is accessible within its class and by derived class instances.

The "protected member" is the class LogBaseViewModel. "Its class" refers to the enclosing class LogViewModels.

By making LogBaseViewModel protected, you are telling the compiler that you don't want any external class to know about the insides of LogBaseViewModel. But then you said public class LogSearchViewModel : LogBaseViewModel. This allows people to access the insides of LogBaseViewModel through LogSearchViewModel! The compiler sees that this will make the protected modifier on LogBaseViewModel meaningless, so it gives you an error.

You said:

I don't ever want this base class to be used except to be inherited by derived classes.

Which is the use case for an abstract class. You should keep LogBaseViewModel public, and make it abstract.

Body:
Struggling a bit with inheritance here. I have common properties to use in two derived classes, so I made a base class LogBaseViewModel. I don't ever want this base class to be used except to be inherited by derived classes, so I made it protected (also tried private).

I found this bit, and maybe I'm mis-interpreting, but thought if I wrapped all 3 of these classes within one, they'd no longer be "outside" and hence this would be allowed.

From section 3.5.3 of the C# 5 specification:

When a protected instance member is accessed outside the program text
  of the class in which it is declared, and when a protected internal
  instance member is accessed outside the program text of the program in
  which it is declared, the access must take place within a class
  declaration that derives from the class in which it is declared.
  Furthermore, the access is required to take place through an instance
  of that derived class type or a class type constructed from it.

However, no joy, I get the error: Error CS0060 Inconsistent accessibility: base class 'LogViewModels.LogBaseViewModel' is less accessible than class 'LogViewModels.LogSearchViewModel'.

public class LogViewModels
{
    protected class LogBaseViewModel
    {
        public int Id { get; set; }
        public string Level { get; set; }
        public string Message { get; set; }
        public string Exception { get; set; }
    }

    public class LogSearchViewModel : LogBaseViewModel
    {

        public DateTime? FromDate { get; set; }
        public DateTime? ToDate { get; set; }
    }

    public class LogViewModel : LogBaseViewModel
    {
        public System.DateTime Date { get; set; }
    }
}


问:
Why my text is centred in Column even I set crossAxisAlignment: CrossAxisAlignment.start in flutter?

I want the Column() to start at the very start(left) of the Card(), so I putted my text() in a column, and I have set the crossAxisAlignment: CrossAxisAlignment.start, set container width to double.infinity, but the text still align in the centre of the container.

What did I do wrong?

Thanks in advance guys.

```<code>class _ClassCardState extends State<ClassCard> {
  var _isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.only(
            left: 10,
            right: 10,
            top: 40,
          ),
          width: double.infinity,
          child: GestureDetector(
            onTap: () {
              setState(() {
                _isExpanded = !_isExpanded;
              });
            },
            child: Card(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
              ),
              elevation: 0.3,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  children: <Widget>[
                    Container(
                      // padding: const EdgeInsets.only(left: 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'Yoga (Beginner)',
                            style: TextStyle(
                              color: Colors.black87,
                              fontWeight: FontWeight.bold,
                              fontSize: 20,
                            ),
                          ),
                          SizedBox(
                            height: 3,
                          ),
                          Text(
                            'Stretch',
                          ),
                          SizedBox(
                            height: 3,
                          ),
                          Text('30mins'),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    // if (_isExpanded)
                    // TimeSlot(),
                    if (_isExpanded)
                      SizedBox(
                        height: 10,
                      ),
                    if (_isExpanded)
                      Text(
                        'Sheung Wan MAXFIT',
                        style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.bold,
                        ),
                      )
                  ],
                ),
              ),
            ),
          ),
        ),
        // Positioned(
        //   child: Container(
        //     child: ClipRRect(
        //       borderRadius: BorderRadius.circular(10),
        //       child: Image.asset(
        //         './assets/images/yoga.png',
        //         fit: BoxFit.cover,
        //       ),
        //     ),
        //     height: 118,
        //     width: 90,
        //   ),
        //   left: 30,
        //   top: 15,
        // ),
      ],
    );
  }
}
</code>```

答:
instead of using a container widget for purpose of padding just use the Padding Widget itself, and set crossAxisAlignment: CrossAxisAlignment.stretch to stretch children of the column, full code below:

Stack(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(
                left: 10,
                right: 10,
                top: 40,
              ),
              child: GestureDetector(
                onTap: () {
                  setState(() {
                    _isExpanded = !_isExpanded;
                  });
                },
                child: Card(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                  elevation: 0.3,
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      children: <Widget>[
                        Container(
                          // padding: const EdgeInsets.only(left: 20),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: <Widget>[
                              Text(
                                'Yoga (Beginner)',
                                style: TextStyle(
                                  color: Colors.black87,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 20,
                                ),
                              ),
                              SizedBox(
                                height: 3,
                              ),
                              Text(
                                'Stretch',
                              ),
                              SizedBox(
                                height: 3,
                              ),
                              Text('30mins'),
                            ],
                          ),
                        ),
                        SizedBox(
                          height: 30,
                        ),
                        // if (_isExpanded)
                        // TimeSlot(),
                        if (_isExpanded)
                          SizedBox(
                            height: 10,
                          ),
                        if (_isExpanded)
                          Text(
                            'Sheung Wan MAXFIT',
                            style: TextStyle(
                              fontSize: 15,
                              fontWeight: FontWeight.bold,
                            ),
                          )
                      ],
                    ),
                  ),
                ),
              ),
            ),
            // Positioned(
            //   child: Container(
            //     child: ClipRRect(
            //       borderRadius: BorderRadius.circular(10),
            //       child: Image.asset(
            //         './assets/images/yoga.png',
            //         fit: BoxFit.cover,
            //       ),
            //     ),
            //     height: 118,
            //     width: 90,
            //   ),
            //   left: 30,
            //   top: 15,
            // ),
          ],
        )
```

Body:
I want the Column() to start at the very start(left) of the Card(), so I putted my text() in a column, and I have set the crossAxisAlignment: CrossAxisAlignment.start, set container width to double.infinity, but the text still align in the centre of the container.

What did I do wrong?

Thanks in advance guys.

class _ClassCardState extends State<ClassCard> {
  var _isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.only(
            left: 10,
            right: 10,
            top: 40,
          ),
          width: double.infinity,
          child: GestureDetector(
            onTap: () {
              setState(() {
                _isExpanded = !_isExpanded;
              });
            },
            child: Card(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
              ),
              elevation: 0.3,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  children: <Widget>[
                    Container(
                      // padding: const EdgeInsets.only(left: 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'Yoga (Beginner)',
                            style: TextStyle(
                              color: Colors.black87,
                              fontWeight: FontWeight.bold,
                              fontSize: 20,
                            ),
                          ),
                          SizedBox(
                            height: 3,
                          ),
                          Text(
                            'Stretch',
                          ),
                          SizedBox(
                            height: 3,
                          ),
                          Text('30mins'),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    // if (_isExpanded)
                    // TimeSlot(),
                    if (_isExpanded)
                      SizedBox(
                        height: 10,
                      ),
                    if (_isExpanded)
                      Text(
                        'Sheung Wan MAXFIT',
                        style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.bold,
                        ),
                      )
                  ],
                ),
              ),
            ),
          ),
        ),
        // Positioned(
        //   child: Container(
        //     child: ClipRRect(
        //       borderRadius: BorderRadius.circular(10),
        //       child: Image.asset(
        //         './assets/images/yoga.png',
        //         fit: BoxFit.cover,
        //       ),
        //     ),
        //     height: 118,
        //     width: 90,
        //   ),
        //   left: 30,
        //   top: 15,
        // ),
      ],
    );
  }
}


问:
CSharpMath.Forms in Windows Application How to Use?
I just want to show a integral question via a label (lblQuestion.Text = ;) but have no idea how to use this NuGet class CSharpMath and couldn't find any documentation that was useful or at least that I could understand. I want to write a integral to ask the user to solve (e.g. using integration by parts, solve:  (integral symbol) (xlnx)dx).

If anyone knows how to use this class and/or a better way to write maths function in text that that would be greatly appreciated.

答:
I'm the maintainer of CSharpMath and what you described can be displayed with a CSharpMath.Forms.TextView. You can't do it with a Label because it only supports normal text.

For the text using integration by parts, solve: (integral symbol) (xlnx)dx, you can use this:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:math="clr-namespace:CSharpMath.Forms;assembly=CSharpMath.Forms"
             x:Class="Namespace.Class">
    <math:TextView x:Name="View" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        Using integration by parts, solve: $\int\left(x\ln x\right)dx$
    </math:TextView>
</ContentPage>
```

You can ask on GitHub directly, you will get a much quicker response than on StackOverflow :)

Body:
I'm the maintainer of CSharpMath and what you described can be displayed with a CSharpMath.Forms.TextView. You can't do it with a Label because it only supports normal text.

For the text using integration by parts, solve: (integral symbol) (xlnx)dx, you can use this:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:math="clr-namespace:CSharpMath.Forms;assembly=CSharpMath.Forms"
             x:Class="Namespace.Class">
    <math:TextView x:Name="View" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        Using integration by parts, solve: $\int\left(x\ln x\right)dx$
    </math:TextView>
</ContentPage>

You can ask on GitHub directly, you will get a much quicker response than on StackOverflow :)


问:
Error when checking target: expected dense_3 to have 2 dimensions, but got array with shape (5, 200, 200, 1)
I've just started to learn Tensorflow (2.1.0) and Keras (2.3.7) with Python 3.7.7.

I have this network:

```<code>def vgg16(input_size = (224,224,3)):
    inputs = Input(input_size, name='input')

    conv1 = Conv2D(64, (3, 3), activation = 'relu', padding = 'same', name ='conv1_1')(inputs)
    conv1 = Conv2D(64, (3, 3), activation = 'relu', padding = 'same', name ='conv1_2')(conv1)
    pool1 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_1')(conv1)

    conv2 = Conv2D(128, (3, 3), activation = 'relu', padding = 'same', name ='conv2_1')(pool1)
    conv2 = Conv2D(128, (3, 3), activation = 'relu', padding = 'same', name ='conv2_2')(conv2)
    pool2 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_2')(conv2)

    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_1')(pool2)
    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_2')(conv3)
    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_3')(conv3)
    pool3 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_3')(conv3)

    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_1')(pool3)
    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_2')(conv4)
    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_3')(conv4)

    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_1')(pool4)
    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_2')(conv5)
    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_3')(conv5)
    pool5 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_5')(conv5)
    flatten = Flatten(name = 'flatten')(pool5)

    dense1 = Dense(units = 4096,activation = "relu", name = 'dense_1')(flatten)
    dense2 = Dense(units = 4096,activation = "relu", name = 'dense_2')(dense1)
    dense3 = Dense(units = 2, activation = "softmax", name = 'dense_3')(dense2)

    opt = Adam(lr=0.001)

    model = Model(inputs = inputs, outputs = dense3, name ='vgg-16')

    model.compile(optimizer=opt, loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])

    return model
</code>```

And this is the code that use it:

```<code>model = vgg16(input_size=(200, 200, 1))

for episode in range(num_episodes):
    selected = np.random.permutation(no_of_samples)[:num_shot + num_query]
    # Create our Support Set.
    support_set = np.array(D[selected[:num_shot]])
    # Create our Query Set.
    query_set = np.array(D[selected[num_query:]])

    X_train = support_set[:,0,:]
    y_train = support_set[:,1,:]

    X_valid = query_set[:,0,:]
    y_valid = query_set[:,1,:]

    results = model.fit(X_train, y_train, epochs=20, batch_size=5,
                        validation_data=(X_valid, y_valid))
</code>```

X_train, y_train, X_valid and y_valid have a this shape: (5, 200, 200, 1).

But I get this error:

Error when checking target: expected dense_3 to have 2 dimensions, but
  got array with shape (5, 200, 200, 1)

I don't understand why. I have changed the fit call removing the batch_size:

```<code>results = model.fit(X_train, y_train, epochs=20, validation_data=(X_valid, y_valid))
</code>```

But I get the same error:

How can I fix this error?

Maybe, the problem is that I'm using one channel images.

Model summary:

```<code>Model: "vgg-16"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           (None, 200, 200, 1)       0
_________________________________________________________________
conv1_1 (Conv2D)             (None, 200, 200, 64)      640
_________________________________________________________________
conv1_2 (Conv2D)             (None, 200, 200, 64)      36928
_________________________________________________________________
pool_1 (MaxPooling2D)        (None, 100, 100, 64)      0
_________________________________________________________________
conv2_1 (Conv2D)             (None, 100, 100, 128)     73856
_________________________________________________________________
conv2_2 (Conv2D)             (None, 100, 100, 128)     147584
_________________________________________________________________
pool_2 (MaxPooling2D)        (None, 50, 50, 128)       0
_________________________________________________________________
conv3_1 (Conv2D)             (None, 50, 50, 256)       295168
_________________________________________________________________
conv3_2 (Conv2D)             (None, 50, 50, 256)       590080
_________________________________________________________________
conv3_3 (Conv2D)             (None, 50, 50, 256)       590080
_________________________________________________________________
pool_3 (MaxPooling2D)        (None, 25, 25, 256)       0
_________________________________________________________________
conv4_1 (Conv2D)             (None, 25, 25, 512)       1180160
_________________________________________________________________
conv4_2 (Conv2D)             (None, 25, 25, 512)       2359808
_________________________________________________________________
conv4_3 (Conv2D)             (None, 25, 25, 512)       2359808
_________________________________________________________________
pool_4 (MaxPooling2D)        (None, 12, 12, 512)       0
_________________________________________________________________
conv5_1 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv5_2 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv5_3 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
pool_5 (MaxPooling2D)        (None, 6, 6, 512)         0
_________________________________________________________________
flatten (Flatten)            (None, 18432)             0
_________________________________________________________________
dense_1 (Dense)              (None, 4096)              75501568
_________________________________________________________________
dense_2 (Dense)              (None, 4096)              16781312
_________________________________________________________________
dense_3 (Dense)              (None, 2)                 8194
=================================================================
Total params: 107,004,610
Trainable params: 107,004,610
Non-trainable params: 0
_________________________________________________________________
</code>```

Body:
I've just started to learn Tensorflow (2.1.0) and Keras (2.3.7) with Python 3.7.7.

I have this network:

def vgg16(input_size = (224,224,3)):
    inputs = Input(input_size, name='input')

    conv1 = Conv2D(64, (3, 3), activation = 'relu', padding = 'same', name ='conv1_1')(inputs)
    conv1 = Conv2D(64, (3, 3), activation = 'relu', padding = 'same', name ='conv1_2')(conv1)
    pool1 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_1')(conv1)

    conv2 = Conv2D(128, (3, 3), activation = 'relu', padding = 'same', name ='conv2_1')(pool1)
    conv2 = Conv2D(128, (3, 3), activation = 'relu', padding = 'same', name ='conv2_2')(conv2)
    pool2 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_2')(conv2)

    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_1')(pool2)
    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_2')(conv3)
    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_3')(conv3)
    pool3 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_3')(conv3)

    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_1')(pool3)
    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_2')(conv4)
    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_3')(conv4)

    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_1')(pool4)
    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_2')(conv5)
    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_3')(conv5)
    pool5 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_5')(conv5)
    flatten = Flatten(name = 'flatten')(pool5)

    dense1 = Dense(units = 4096,activation = "relu", name = 'dense_1')(flatten)
    dense2 = Dense(units = 4096,activation = "relu", name = 'dense_2')(dense1)
    dense3 = Dense(units = 2, activation = "softmax", name = 'dense_3')(dense2)

    opt = Adam(lr=0.001)

    model = Model(inputs = inputs, outputs = dense3, name ='vgg-16')

    model.compile(optimizer=opt, loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])

    return model

And this is the code that use it:

model = vgg16(input_size=(200, 200, 1))

for episode in range(num_episodes):
    selected = np.random.permutation(no_of_samples)[:num_shot + num_query]
    # Create our Support Set.
    support_set = np.array(D[selected[:num_shot]])
    # Create our Query Set.
    query_set = np.array(D[selected[num_query:]])

    X_train = support_set[:,0,:]
    y_train = support_set[:,1,:]

    X_valid = query_set[:,0,:]
    y_valid = query_set[:,1,:]

    results = model.fit(X_train, y_train, epochs=20, batch_size=5,
                        validation_data=(X_valid, y_valid))

X_train, y_train, X_valid and y_valid have a this shape: (5, 200, 200, 1).

But I get this error:

Error when checking target: expected dense_3 to have 2 dimensions, but
  got array with shape (5, 200, 200, 1)

I don't understand why. I have changed the fit call removing the batch_size:

results = model.fit(X_train, y_train, epochs=20, validation_data=(X_valid, y_valid))

But I get the same error:

How can I fix this error?

Maybe, the problem is that I'm using one channel images.

Model summary:

Model: "vgg-16"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           (None, 200, 200, 1)       0
_________________________________________________________________
conv1_1 (Conv2D)             (None, 200, 200, 64)      640
_________________________________________________________________
conv1_2 (Conv2D)             (None, 200, 200, 64)      36928
_________________________________________________________________
pool_1 (MaxPooling2D)        (None, 100, 100, 64)      0
_________________________________________________________________
conv2_1 (Conv2D)             (None, 100, 100, 128)     73856
_________________________________________________________________
conv2_2 (Conv2D)             (None, 100, 100, 128)     147584
_________________________________________________________________
pool_2 (MaxPooling2D)        (None, 50, 50, 128)       0
_________________________________________________________________
conv3_1 (Conv2D)             (None, 50, 50, 256)       295168
_________________________________________________________________
conv3_2 (Conv2D)             (None, 50, 50, 256)       590080
_________________________________________________________________
conv3_3 (Conv2D)             (None, 50, 50, 256)       590080
_________________________________________________________________
pool_3 (MaxPooling2D)        (None, 25, 25, 256)       0
_________________________________________________________________
conv4_1 (Conv2D)             (None, 25, 25, 512)       1180160
_________________________________________________________________
conv4_2 (Conv2D)             (None, 25, 25, 512)       2359808
_________________________________________________________________
conv4_3 (Conv2D)             (None, 25, 25, 512)       2359808
_________________________________________________________________
pool_4 (MaxPooling2D)        (None, 12, 12, 512)       0
_________________________________________________________________
conv5_1 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv5_2 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv5_3 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
pool_5 (MaxPooling2D)        (None, 6, 6, 512)         0
_________________________________________________________________
flatten (Flatten)            (None, 18432)             0
_________________________________________________________________
dense_1 (Dense)              (None, 4096)              75501568
_________________________________________________________________
dense_2 (Dense)              (None, 4096)              16781312
_________________________________________________________________
dense_3 (Dense)              (None, 2)                 8194
=================================================================
Total params: 107,004,610
Trainable params: 107,004,610
Non-trainable params: 0
_________________________________________________________________

Body:
X_train, y_train, X_valid and y_valid have a this shape: (5, 200, 200,1).

According to your network's summary

>> vvg16().summary()

Model: "vgg-16"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           [(None, 224, 224, 3)]     0
_________________________________________________________________
conv1_1 (Conv2D)             (None, 224, 224, 64)      1792
_________________________________________________________________
conv1_2 (Conv2D)             (None, 224, 224, 64)      36928
_________________________________________________________________
pool_1 (MaxPooling2D)        (None, 112, 112, 64)      0
_________________________________________________________________
conv2_1 (Conv2D)             (None, 112, 112, 128)     73856
_________________________________________________________________
conv2_2 (Conv2D)             (None, 112, 112, 128)     147584
_________________________________________________________________
pool_2 (MaxPooling2D)        (None, 56, 56, 128)       0
_________________________________________________________________
conv3_1 (Conv2D)             (None, 56, 56, 256)       295168
_________________________________________________________________
conv3_2 (Conv2D)             (None, 56, 56, 256)       590080
_________________________________________________________________
conv3_3 (Conv2D)             (None, 56, 56, 256)       590080
_________________________________________________________________
pool_3 (MaxPooling2D)        (None, 28, 28, 256)       0
_________________________________________________________________
conv4_1 (Conv2D)             (None, 28, 28, 512)       1180160
_________________________________________________________________
conv4_2 (Conv2D)             (None, 28, 28, 512)       2359808
_________________________________________________________________
conv4_3 (Conv2D)             (None, 28, 28, 512)       2359808
_________________________________________________________________
pool_4 (MaxPooling2D)        (None, 14, 14, 512)       0
_________________________________________________________________
conv5_1 (Conv2D)             (None, 14, 14, 512)       2359808
_________________________________________________________________
conv5_2 (Conv2D)             (None, 14, 14, 512)       2359808
_________________________________________________________________
conv5_3 (Conv2D)             (None, 14, 14, 512)       2359808
_________________________________________________________________
pool_5 (MaxPooling2D)        (None, 7, 7, 512)         0
_________________________________________________________________
flatten (Flatten)            (None, 25088)             0
_________________________________________________________________
dense_1 (Dense)              (None, 4096)              102764544
_________________________________________________________________
dense_2 (Dense)              (None, 4096)              16781312
_________________________________________________________________
dense_3 (Dense)              (None, 2)                 8194
=================================================================
Total params: 134,268,738
Trainable params: 134,268,738
Non-trainable params: 0
_________________________________________________________________

Your X_train and X_valid need to have a shape of (224,224,3)

Your y_train and y_valid need to have total 2 classes and be one-hot encoded due to keras.losses.categorical_crossentropy

Edit:

When the output is an array of N classes:

last layer should be Dense(N,"softmax")

the loss should be keras.losses.sparse_categorical_crossentropy

When the output is one-hot encoded N classes:

if not already encoded use keras.utils.to_categorical(array, N)

last layer should be Dense(N,"softmax")

the loss should be keras.losses.categorical_crossentropy

When the purpose is not to classify:

your last layer should produce the same shape

you need to use a proper activation

you don't need to use flatten

check autoencoder concept to see how you can produce output that's has the same shape as your input


问:
Android less than api 23 couldnt connect to the server
I have developed an android app , and all my users who has android less than api 23 couldnt connect to the server, and the rest just work normal, and that just started from this day (2020-05-30), before this day it was working normally for many years.
Any idea whats the reason. Is it from our ISP or from google it self.</p>

答:
There is a certificate expiry event today, could be related.

https://twitter.com/bitcynth/status/1266683552030212096

https://crt.sh/?id=1

Not certain this is the same thing - https://support.sectigo.com/articles/Knowledge/Sectigo-AddTrust-External-CA-Root-Expiring-May-30-2020

Probable options if you confirm this is the case

Get the server team to issue a new certificate with a different root CA.

Add a new Root CA to the device, but this requires a manual process on each phone.


问:
How to calculate cumulative normal distribution?
I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.</p>

答:
Simple like this:

```<code>import math
def my_cdf(x):
    return 0.5*(1+math.erf(x/math.sqrt(2)))
</code>```

I found the formula in this page https://www.danielsoper.com/statcalc/formulas.aspx?id=55

OwnerDisplayName: toma

Body:
Simple like this:

import math
def my_cdf(x):
    return 0.5*(1+math.erf(x/math.sqrt(2)))

I found the formula in this page https://www.danielsoper.com/statcalc/formulas.aspx?id=55


问:
get text of second child in div - jQuery
I'm trying to create a kind of a online shopping cart
My problem is that I can't get the price of a single product showing in the shopping cart.

So here is my code

```<code><div id="shoe_one">
  <img src="imgs/img_0.JPG" id="training_shoe" alt="purple adidas shoe" width="150" class="product">
  <p>Adidas Courtset</p>
  <p>Preis: 59,90 €</p>
  <input type="button" value="Warenkorb" class="button">
</div>
</code>```

my js code:

```<code>let selectedItem = $(this).parent();

if(!contains) {

   //let price = selectedItem.("nth-child(3)").text();

   let addedProduct = $("<div class='newProduct'></div>");
   addedProduct.append(selectedImage.clone());
   addedProduct.append("<p>Anzahl: " + amount + "</p>" + "<p>" + price + "</p>");
   cart.append(addedProduct);
   content.append(cart);
}
</code>```

答:
As your HTML stands, if you want to get the price text on clicking the button then you can target the previous p element.

Demo:

$(".button").click(function(){
  let selectedItem = $(this);
  let price = selectedItem.prev("p").text();
  console.log(price);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="shoe_one">
    <img src="imgs/img_0.JPG" id="training_shoe" alt="purple adidas shoe" width="150" class="product">
    <p>Adidas Courtset</p>
    <p>Preis: 59,90 €</p>
    <input type="button" value="Warenkorb" class="button">
</div></code>```

Body:
I'm trying to create a kind of a online shopping cart
My problem is that I can't get the price of a single product showing in the shopping cart.

So here is my code

Adidas Courtset

Preis: 59,90 €

  <input type="button" value="Warenkorb" class="button">

my js code:

let selectedItem = $(this).parent();

if(!contains) {

   //let price = selectedItem.("nth-child(3)").text();

   let addedProduct = $("

");
   addedProduct.append(selectedImage.clone());
   addedProduct.append("
Anzahl: " + amount + "
" + "
" + price + "
");
   cart.append(addedProduct);
   content.append(cart);
}

Body:
As your HTML stands, if you want to get the price text on clicking the button then you can target the previous p element.

Demo:

$(".button").click(function(){
  let selectedItem = $(this);
  let price = selectedItem.prev("p").text();
  console.log(price);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="shoe_one">
    <img src="imgs/img_0.JPG" id="training_shoe" alt="purple adidas shoe" width="150" class="product">
    <p>Adidas Courtset</p>
    <p>Preis: 59,90 €</p>
    <input type="button" value="Warenkorb" class="button">
</div>


问:
Radio buttons change value from another class
I have a class where i want to create 6 one time choice radio buttons, so I have created a radio button separate widget,   how can i call this widget and change the values of radio buttons. here is what i have done

Here is the separated widget which i want to call 6 times from another class :

```<code>  class ChooseTime extends StatefulWidget {
      final int value;
      final int selection;
      final int num;
      final String time;
      final Function selectTime;
      ChooseTime(
          {this.selection, this.value, this.num, this.time, this.selectTime});
      @override
      _ChooseTimeState createState() => _ChooseTimeState();
    }

 Row(
            children: <Widget>[
              Radio(
                focusColor: Colors.white,
                activeColor: Colors.white,
                groupValue: _selection,
                onChanged: widget.selectTime,
                value: widget.value,
              ),
              Text(
                widget.time,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: _selection == widget.num
                      ? Colors.white
                      : Colors.deepOrangeAccent,
                ),
              ),
            ],
          ),
</code>```

And here is the Class where i am calling widget above :

```<code>  selectTime(int timeSelected) {
    setState(() {
      _selection = timeSelected;
    });
  }

          Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      ChooseTime(
                        selection: 1,
                        value: 1,
                        num: 1,
                        time: "09:00-11:00",
                        selectTime: selectTime,
                      ),
                      ChooseTime(
                        selection: 2,
                        value: 2,
                        num: 2,
                        time: "11:00-14:00",
                        selectTime: selectTime,
                      ),
                    ],
                  ),
</code>```

I have tried the code above but when i press the button they are not changing.

答: Use Provider , bloc Pattern to manage your app state </p>

Body:
I have a class where i want to create 6 one time choice radio buttons, so I have created a radio button separate widget,   how can i call this widget and change the values of radio buttons. here is what i have done

Here is the separated widget which i want to call 6 times from another class :

  class ChooseTime extends StatefulWidget {
      final int value;
      final int selection;
      final int num;
      final String time;
      final Function selectTime;
      ChooseTime(
          {this.selection, this.value, this.num, this.time, this.selectTime});
      @override
      _ChooseTimeState createState() => _ChooseTimeState();
    }

 Row(
            children: <Widget>[
              Radio(
                focusColor: Colors.white,
                activeColor: Colors.white,
                groupValue: _selection,
                onChanged: widget.selectTime,
                value: widget.value,
              ),
              Text(
                widget.time,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: _selection == widget.num
                      ? Colors.white
                      : Colors.deepOrangeAccent,
                ),
              ),
            ],
          ),

And here is the Class where i am calling widget above :

  selectTime(int timeSelected) {
    setState(() {
      _selection = timeSelected;
    });
  }

          Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      ChooseTime(
                        selection: 1,
                        value: 1,
                        num: 1,
                        time: "09:00-11:00",
                        selectTime: selectTime,
                      ),
                      ChooseTime(
                        selection: 2,
                        value: 2,
                        num: 2,
                        time: "11:00-14:00",
                        selectTime: selectTime,
                      ),
                    ],
                  ),

I have tried the code above but when i press the button they are not changing.


问:
Find CouchDB docs missing an arbitrary field
I need a CouchDB view where I can get back all the documents that don't have an arbitrary field. This is easy to do if you know in advance what fields a document might not have. For example, this lets you send view/my_view/?key="foo" to easily retrieve docs without the "foo" field:

```<code>function (doc) {
  var fields = [ "foo", "bar", "etc" ];

  for (var idx in fields) {
    if (!doc.hasOwnProperty(fields[idx])) {
      emit(fields[idx], 1);
    }
  }
}
</code>```

However, you're limited to asking about the three fields set in the view; something like view/my_view/?key="baz" won't get you anything, even if you have many docs missing that field. I need a view where it will--where I don't need to specify possible missing fields in advance. Any thoughts?

答:
This technique is called the Thai massage. Use it to efficiently find documents not in a view if (and only if) the view is keyed on the document id.

```<code>function(doc) {
    // _view/fields map, showing all fields of all docs
    // In principle you could emit e.g. "foo.bar.baz"
    // for nested objects. Obviously I do not.
    for (var field in doc)
        emit(field, doc._id);
}

function(keys, vals, is_rerun) {
    // _view/fields reduce; could also be the string "_count"
    return re ? sum(vals) : vals.length;
}
</code>```

To find documents not having that field,

GET /db/_all_docs and remember all the ids

GET /db/_design/ex/_view/fields?reduce=false&key="some_field"

Compare the ids from _all_docs vs the ids from the query.

The ids in _all_docs but not in the view are those missing that field.

It sounds bad to keep the ids in memory, but you don't have to! You can use a merge sort strategy, iterating through both queries simultaneously. You start with the first id of the has list (from the view) and the first id of the full list (from _all_docs).

If full < has, it is missing the field, redo with the next full element

If full = has, it has the field, redo with the next full element

If full > has, redo with the next has element

Depending on your language, that might be difficult. But it is pretty easy in Javascript, for example, or other event-driven programming frameworks.

Body:
I need a CouchDB view where I can get back all the documents that don't have an arbitrary field. This is easy to do if you know in advance what fields a document might not have. For example, this lets you send view/my_view/?key="foo" to easily retrieve docs without the "foo" field:

function (doc) {
  var fields = [ "foo", "bar", "etc" ];

  for (var idx in fields) {
    if (!doc.hasOwnProperty(fields[idx])) {
      emit(fields[idx], 1);
    }
  }
}

However, you're limited to asking about the three fields set in the view; something like view/my_view/?key="baz" won't get you anything, even if you have many docs missing that field. I need a view where it will--where I don't need to specify possible missing fields in advance. Any thoughts?

Body:
This technique is called the Thai massage. Use it to efficiently find documents not in a view if (and only if) the view is keyed on the document id.

function(doc) {
    // _view/fields map, showing all fields of all docs
    // In principle you could emit e.g. "foo.bar.baz"
    // for nested objects. Obviously I do not.
    for (var field in doc)
        emit(field, doc._id);
}

function(keys, vals, is_rerun) {
    // _view/fields reduce; could also be the string "_count"
    return re ? sum(vals) : vals.length;
}

To find documents not having that field,

GET /db/_all_docs and remember all the ids

GET /db/_design/ex/_view/fields?reduce=false&key="some_field"

Compare the ids from _all_docs vs the ids from the query.

The ids in _all_docs but not in the view are those missing that field.

It sounds bad to keep the ids in memory, but you don't have to! You can use a merge sort strategy, iterating through both queries simultaneously. You start with the first id of the has list (from the view) and the first id of the full list (from _all_docs).

If full < has, it is missing the field, redo with the next full element

If full = has, it has the field, redo with the next full element

If full > has, redo with the next has element

Depending on your language, that might be difficult. But it is pretty easy in Javascript, for example, or other event-driven programming frameworks.


问:
Rewrite this SQL query using scala slick
```<code>class ItemTable(tag: Tag) extends Table[Item](tag, _tableName = "items") {

  def id: Rep[Int] = column[Int]("id", O.PrimaryKey, O.AutoInc)
  def authId: Rep[String] = column[String]("auth_id")
  def productId: Rep[Int] = column[Int]("product_id")
  def position: Rep[Int] = column[Int]("position")

  override def * : ProvenShape[Item] = (id, authId, productId, position) <> ((Item.apply _).tupled, Item.unapply)
}

class ItemService @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext) {

    private lazy val query = TableQuery[ItemTable]
    def updateItem(item: Item, previousPosition: Int): Future[Item] = {

        if (previousPosition < item.position) {
          // this is the sql I want to convert to slick
          db.run(sqlu""" UPDATE #${query.baseTableRow.tableName} SET position = position - 1 WHERE position >= #$previousPosition AND position <= #${item.position} AND auth_id = '#${item.authId}'""")
        }
        else if (previousPosition > item.position) {
          db.run(sqlu""" UPDATE #${query.baseTableRow.tableName} SET position = position + 1 WHERE position <= #$previousPosition AND position >= #${item.position} AND auth_id = '#${item.authId}' """)
        }
        else {
         // some other code
        }
    }
}

case class Item(id: Int, authId: String, productId: Int, position: Int){}
</code>```

My SQL works, I'm getting stuck here translating it to slick.

```<code>val q2 = query.filter(f=> f.authId === item.authId && f.position >= previousPosition && f.position <= item.position)
</code>```

// I don't know how to update multiple or pass the result set to the update function

答:
The embedded style of Slick doesn't support dynamic mutating batch updates of the form SET position = position + 1 (Slick issue 497).

That means using Plain SQL style you already have is the right approach here.

An andditional note on idiomatic sqlu: I notice the sqlu you have uses "splicing" (#$ for the table name). That prevents Slick from treating the value as a string, which is appropriate for what you're doing.  But the later usage #$previousPosition would be more typically written as a plain substitution, $previousPosition. That's because you'd typically want a SQL parameter there to be correctly escaped by Slick. It probably won't make a difference for integers, but could for other data types.

Body:
class ItemTable(tag: Tag) extends Table[Item](tag, _tableName = "items") {

  def id: Rep[Int] = column[Int]("id", O.PrimaryKey, O.AutoInc)
  def authId: Rep[String] = column[String]("auth_id")
  def productId: Rep[Int] = column[Int]("product_id")
  def position: Rep[Int] = column[Int]("position")

  override def * : ProvenShape[Item] = (id, authId, productId, position) <> ((Item.apply _).tupled, Item.unapply)
}

class ItemService @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext) {

    private lazy val query = TableQuery[ItemTable]
    def updateItem(item: Item, previousPosition: Int): Future[Item] = {

        if (previousPosition < item.position) {
          // this is the sql I want to convert to slick
          db.run(sqlu""" UPDATE #${query.baseTableRow.tableName} SET position = position - 1 WHERE position >= #$previousPosition AND position <= #${item.position} AND auth_id = '#${item.authId}'""")
        }
        else if (previousPosition > item.position) {
          db.run(sqlu""" UPDATE #${query.baseTableRow.tableName} SET position = position + 1 WHERE position <= #$previousPosition AND position >= #${item.position} AND auth_id = '#${item.authId}' """)
        }
        else {
         // some other code
        }
    }
}

case class Item(id: Int, authId: String, productId: Int, position: Int){}

My SQL works, I'm getting stuck here translating it to slick.

val q2 = query.filter(f=> f.authId === item.authId && f.position >= previousPosition && f.position <= item.position)

// I don't know how to update multiple or pass the result set to the update function