问:
DB2 add Primary Key to existing table created from Jupyter Lab via SQL magic 'PERSIST'
I created sample table from Jupyter Lab notebook via:

```<code>file_csv = 'data.csv'
df = pd.read_csv(file_csv)
df.insert(0, 'KEY_ID', df.index)
</code>```

Then added table to DB2 on IBM cloud via:

```<code>%sql PERSIST df
</code>```

Looking at that table in DB2 console it is created w/o primary key - so I tried to remedy it:

```<code>ALTER TABLE DF
    ALTER COLUMN KEY_ID
    SET NOT NULL;
</code>```

And set KEY_ID as primary key:

```<code>ALTER TABLE DF
    ADD PRIMARY KEY(KEY_ID);
</code>```

But DB2 stubbornly refuses with following error:

InternalError: (ibm_db_dbi.InternalError) ibm_db_dbi::InternalError: Exception('Statement Execute Failed: [IBM][CLI Driver][DB2/LINUXX8664] SQL0668N  Operation not allowed for reason code "7" on table "MYID9999.DF".    SQLSTATE=57016\r SQLCODE=-668')

  [SQL: ALTER TABLE DF

  ADD PRIMARY KEY(KEY_ID);]

  (Background on this error at: http://sqlalche.me/e/2j85)

答:
OK - I actually solved it while typing the question - but I will post it anyway. You need to REORG the table (I guess after resetting 'KEY_ID' column props to NOT NULL) and it only worked from when run like this:

```<code>CALL SYSPROC.ADMIN_CMD ('REORG TABLE DF')
</code>```

But after that ALTER command works like a charm.

Body:
I created sample table from Jupyter Lab notebook via:

file_csv = 'data.csv'
df = pd.read_csv(file_csv)
df.insert(0, 'KEY_ID', df.index)

Then added table to DB2 on IBM cloud via:

%sql PERSIST df

Looking at that table in DB2 console it is created w/o primary key - so I tried to remedy it:

ALTER TABLE DF
    ALTER COLUMN KEY_ID
    SET NOT NULL;

And set KEY_ID as primary key:

ALTER TABLE DF
    ADD PRIMARY KEY(KEY_ID);

But DB2 stubbornly refuses with following error:

InternalError: (ibm_db_dbi.InternalError) ibm_db_dbi::InternalError: Exception('Statement Execute Failed: [IBM][CLI Driver][DB2/LINUXX8664] SQL0668N  Operation not allowed for reason code "7" on table "MYID9999.DF".    SQLSTATE=57016\r SQLCODE=-668')

  [SQL: ALTER TABLE DF

  ADD PRIMARY KEY(KEY_ID);]

  (Background on this error at: http://sqlalche.me/e/2j85)

Body:
OK - I actually solved it while typing the question - but I will post it anyway. You need to REORG the table (I guess after resetting 'KEY_ID' column props to NOT NULL) and it only worked from when run like this:

CALL SYSPROC.ADMIN_CMD ('REORG TABLE DF')

But after that ALTER command works like a charm.


来源: stackexchange

问:
PostgreSQL check parent of parent in query
Okay, I'll try to be as precise as possible. I have a database with comments who have a parent_comment_id. I want to select a number of comments from this table and a matching number of answers to these comments. Here comes my problem: If I arbitrarily select comments, I might grab some who don't have any answers. However, if I select comment answers first, I might grab answers who are an answer to another comment already. So, what I want to do is grab answers who are immediate answers to a comment (parent_comment_id = NULL) and then get those comments base on the parent_comment_id. How would I go about this in a query?

Assume this layout of a database

```<code>comment_id    parent_comment_id
1             NULL
2             NULL
3             1
4             3
5             1
6             3
7             1
8             4
9             NULL
10            NULL
...
</code>```

Now, I would select, let's say 2 answers and the corresponding comments. If I just select the first 2 answers, I would get comment 3 and 4, but if I backtrace those, I would only get comment 1, because comment 4 is an answer to an answer. Instead, I would want to find only comments whose parent comment has no parent comment, which would be comment 3 and 5 in this example.

I haven't really tried anything beyound realizing it doesn't work without somehow recursively getting parents which I have no clue how to do in SQL queries.

答:
I would want to find only comments whose parent comment has no parent comment.

I think that you just want a self-join and some filtering:

```<code>select c.*
from comments c
inner join comments pc on pc.comment_id = c.parent_comment_id
where pc.parent_comment_id is null
</code>```

You could also use exists:

```<code>select c.*
from comments c
where exists (
    select 1
    from comments pc
    where pc.comment_id = c.parent_comment_id and pc.parent_comment_id is null
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Okay, I'll try to be as precise as possible. I have a database with comments who have a parent_comment_id. I want to select a number of comments from this table and a matching number of answers to these comments. Here comes my problem: If I arbitrarily select comments, I might grab some who don't have any answers. However, if I select comment answers first, I might grab answers who are an answer to another comment already. So, what I want to do is grab answers who are immediate answers to a comment (parent_comment_id = NULL) and then get those comments base on the parent_comment_id. How would I go about this in a query?

Assume this layout of a database

comment_id    parent_comment_id
1             NULL
2             NULL
3             1
4             3
5             1
6             3
7             1
8             4
9             NULL
10            NULL
...

Now, I would select, let's say 2 answers and the corresponding comments. If I just select the first 2 answers, I would get comment 3 and 4, but if I backtrace those, I would only get comment 1, because comment 4 is an answer to an answer. Instead, I would want to find only comments whose parent comment has no parent comment, which would be comment 3 and 5 in this example.

I haven't really tried anything beyound realizing it doesn't work without somehow recursively getting parents which I have no clue how to do in SQL queries.

Body:
I would want to find only comments whose parent comment has no parent comment.

I think that you just want a self-join and some filtering:

select c.*
from comments c
inner join comments pc on pc.comment_id = c.parent_comment_id
where pc.parent_comment_id is null

You could also use exists:

select c.*
from comments c
where exists (
    select 1
    from comments pc
    where pc.comment_id = c.parent_comment_id and pc.parent_comment_id is null
)


问:
Rotate multiple elements in Revit with C#
I'm writing a Macro in Revit with C# for rotate multiple selected elements at a time. But I'm getting this error every time I try to run it:
"System.NullReferenceException: Object Reference Not Set to an instance of an object".
I don't know why I get this error since there are no "null" references in my selection. Does anybody know what is happening?
This is the code snippet:</p>

```<code>        //Get document
        UIDocument uidoc = this.Application.ActiveUIDocument;
        Document doc = uidoc.Document;

        //Elements selection
        double angle = 45.0;
        var elements = uidoc.Selection.PickObjects(ObjectType.Element,"Select Elements") as List<Element>;
        foreach (Element element in elements)
        {
            LocationPoint lp = element.Location as LocationPoint;
            XYZ ppt = new XYZ(lp.Point.X,lp.Point.Y,0);
            Line axis = Line.CreateBound(ppt, new XYZ(ppt.X,ppt.Y,ppt.Z+10.0));

            using(Transaction rotate = new Transaction(doc,"rotate elements"))
            {
                rotate.Start();
                ElementTransformUtils.RotateElement(doc,element.Id,axis,angle);
                rotate.Commit();
            }
        }
</code>```

答:
You are getting aNullReferenceException because the return type of PickObjects is IList<Reference> and not List<Element>.

Try something like this:

```<code>var elements = uidoc.Selection.PickObjects(ObjectType.Element, "Select Elements")
.Select(o => uidoc.Document.GetElement(o));
</code>```

Consider also that the angle is measured in radians and not in degrees as you wrote, or at least i think you don't want to rotate the element 45 rad ;).

Finally, do not forget that element.Location is not always a LocationPoint, depending on the selected element you could get a LocationPoint, LocationCurve or the base class ´Location´.

Body:
I'm writing a Macro in Revit with C# for rotate multiple selected elements at a time. But I'm getting this error every time I try to run it:
"System.NullReferenceException: Object Reference Not Set to an instance of an object".
I don't know why I get this error since there are no "null" references in my selection. Does anybody know what is happening?
This is the code snippet:

        //Get document
        UIDocument uidoc = this.Application.ActiveUIDocument;
        Document doc = uidoc.Document;

        //Elements selection
        double angle = 45.0;
        var elements = uidoc.Selection.PickObjects(ObjectType.Element,"Select Elements") as List<Element>;
        foreach (Element element in elements)
        {
            LocationPoint lp = element.Location as LocationPoint;
            XYZ ppt = new XYZ(lp.Point.X,lp.Point.Y,0);
            Line axis = Line.CreateBound(ppt, new XYZ(ppt.X,ppt.Y,ppt.Z+10.0));

            using(Transaction rotate = new Transaction(doc,"rotate elements"))
            {
                rotate.Start();
                ElementTransformUtils.RotateElement(doc,element.Id,axis,angle);
                rotate.Commit();
            }
        }

Body:
You are getting aNullReferenceException because the return type of PickObjects is IList<Reference> and not List<Element>.

Try something like this:

var elements = uidoc.Selection.PickObjects(ObjectType.Element, "Select Elements")
.Select(o => uidoc.Document.GetElement(o));

Consider also that the angle is measured in radians and not in degrees as you wrote, or at least i think you don't want to rotate the element 45 rad ;).

Finally, do not forget that element.Location is not always a LocationPoint, depending on the selected element you could get a LocationPoint, LocationCurve or the base class ´Location´.


问:
grep inverse read match pattern from two files
I have a file (note that some lines have more than 2 columns, also some lines are 1 space delimited, and some are multiple space delimited, this file is quite large...)

```<code> file1.txt:
there is a line here that has more than two columns
## this line is a comment
blahblah:     blahblahSierraexample7272
foo: foo@foobar.com
nonsense:                    nonsense59s59S
nonsense:   someRandomColumn
.....
</code>```

I have another file that is a subset of file1.txt, this file has two columns only and columns are "1" space delimited!

```<code>file2.txt
foo: foo@foo.com
nonsense: nonsense59s59S
</code>```

now, I would like to delete all lines that appear in file2.txt from file1.txt, how can I do that in a shell script? note that the second file (file2.txt) has two columns only, while file1.txt has multiple... so if a matching needs to be done it should be like: $1(from file2) match $1(from file1) and $NF(from file2) match $NF(from file1) and then inverse the match and print...

P.S. already tried grep -vf file2.txt file1.txt but since the space between column1 and $NF is not fixed it didn't work...
sed and awk should do the trick but can't come up with the code...

```<code>sed -i '/^<firstColumnOfFile2> .* <lastColumnOfFile2>$/d' file1.txt (perhaps in a while loop!)
</code>```

or something like: grep -vw -f ^[(1stColofFile2)] and also [(lastColOfFile2)]$ file1.txt

答:
You can use sed to turn the lines in file2.txt into regular expressions that match one or more spaces after the colon, and then use grep to remove the lines from file1.txt that match those:

```<code>$ grep -Evf <(sed 's/^\([^:]*\): /^\1:[[:space:]]+/' file2.txt) file1.txt
there is a line here that has more than two columns
## this line is a comment
blahblah:     blahblahSierraexample7272
foo: foo@foobar.com
nonsense:   someRandomColumn
</code>```

Body:
I have a file (note that some lines have more than 2 columns, also some lines are 1 space delimited, and some are multiple space delimited, this file is quite large...)

 file1.txt:
there is a line here that has more than two columns
## this line is a comment
blahblah:     blahblahSierraexample7272
foo: foo@foobar.com
nonsense:                    nonsense59s59S
nonsense:   someRandomColumn
.....

I have another file that is a subset of file1.txt, this file has two columns only and columns are "1" space delimited!

file2.txt
foo: foo@foo.com
nonsense: nonsense59s59S

now, I would like to delete all lines that appear in file2.txt from file1.txt, how can I do that in a shell script? note that the second file (file2.txt) has two columns only, while file1.txt has multiple... so if a matching needs to be done it should be like: $1(from file2) match $1(from file1) and $NF(from file2) match $NF(from file1) and then inverse the match and print...

P.S. already tried grep -vf file2.txt file1.txt but since the space between column1 and $NF is not fixed it didn't work...
sed and awk should do the trick but can't come up with the code...

sed -i '/^<firstColumnOfFile2> .* <lastColumnOfFile2>$/d' file1.txt (perhaps in a while loop!)

or something like: grep -vw -f ^[(1stColofFile2)] and also [(lastColOfFile2)]$ file1.txt

Body:
You can use sed to turn the lines in file2.txt into regular expressions that match one or more spaces after the colon, and then use grep to remove the lines from file1.txt that match those:

$ grep -Evf <(sed 's/^\([^:]*\): /^\1:[[:space:]]+/' file2.txt) file1.txt
there is a line here that has more than two columns
## this line is a comment
blahblah:     blahblahSierraexample7272
foo: foo@foobar.com
nonsense:   someRandomColumn


问:
Wrapping Datascript query in a function?
Getting a seemingly bizarre problem with Datascript. For some reason when I run this query without it being wrapped in a function, everything works. But once I wrap it in a function, it returns the value for :block/content for every entity in the database. I'm confused because I haven't encountered any issues with wrapping other Datascript queries in the past. Does anyone more experienced than me with Datascript see any issues?

```<code>;; Works fine and returns the correct value
(ds/q '[:find ?block-text
        :where
        [?id :block/id "l_63xa4m1"]
        [?id :block/content ?block-text]]
      @conn)

;; Returns every value for `:block/content` in the db
(defn content-find
  [id-passed]
  (ds/q '[:find ?block-text
          :where
          [?id :block/id ?id-passed]
          [?id :block/content ?block-text]]
        @conn))
(content-find "l_63xa4m1")
</code>```

EDIT: Solved over here

答:
In your defn version you are using the query clause [?id :block/id ?id-passed]. This doesn't actually use the id-passed parameter you passed to the function.

I'm not sure how to pass parameters correctly. I believe there is an :in clause or so?

Body:
Getting a seemingly bizarre problem with Datascript. For some reason when I run this query without it being wrapped in a function, everything works. But once I wrap it in a function, it returns the value for :block/content for every entity in the database. I'm confused because I haven't encountered any issues with wrapping other Datascript queries in the past. Does anyone more experienced than me with Datascript see any issues?

;; Works fine and returns the correct value
(ds/q '[:find ?block-text
        :where
        [?id :block/id "l_63xa4m1"]
        [?id :block/content ?block-text]]
      @conn)

;; Returns every value for `:block/content` in the db
(defn content-find
  [id-passed]
  (ds/q '[:find ?block-text
          :where
          [?id :block/id ?id-passed]
          [?id :block/content ?block-text]]
        @conn))
(content-find "l_63xa4m1")

EDIT: Solved over here


问:
How to underline a field on a form except text in the cell
I've been asked to make a form that has labels in cells (not underlined) followed by an underlined area that indicates where someone is supposed to put information. I don't personally like this design approach, but it is what I've been asked to do.

Something like this:

```<code>First Name: ________
Last Name: ________
Street Address: ________
</code>```

In other words, everything in the table cell is underlined except the label and the trailing space character.

The labels contain varying information and clearly will not align. However, all the underlines should right-align in their respective cells.

Here's a pen that hopefully illustrates what I'm trying to do. https://codepen.io/timmerbu/pen/pojMypE?editors=1100

html {
  font-size: 16px;
}

body {
  background: #9f9;
}

div {
  background: #fff;
  padding: 1rem;
  margin: auto;
  width: 200px;
}

table,
tr,
td {
  margin: 0;
  padding: 0;
  border-collapse: collapse;
}

table {
  width: 100%;
}

tr:nth-child(odd) {
  background: #fd4;
}

td {
  padding: 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>This is a test.</p>
  <table>
    <tbody>
      <tr>
        <td>Word: __________________</td>
      </tr>
      <tr>
        <td>Word word: ______________</td>
      </tr>
      <tr>
        <td>Word word word: _________</td>
      </tr>
      <tr>
        <td>Word word word word: ____</td>
      </tr>
    </tbody>
  </table>
  <p>End of test.</p>
</div></code>```

答:
A little non-formal, but it works. Removing the underscore and adding it back with a CSS Pseudo class, while having the  for the text has a background and z-index that puts the underline behind it. You can change the underline placement by adjusting the top: -4px;.

html {
  font-size: 16px;
}

body {
  background: #9f9;
}

div {
  background: #fff;
  padding: 1rem;
  margin: auto;
  width: 200px;
}

table,
tr,
td {
  margin: 0;
  padding: 0;
  border-collapse: collapse;
}

table {
  width: 100%;
}

tr:nth-child(odd) {
  background: #fd4;
}

td {
  padding: 3px;
}

tbody td:after {
  border-bottom: 1px solid #f50909;
  content: "";
  width: 100%;
  height: 1px;
  display: block;
  position: relative;
  top: -4px;
}

td span {
  display: inline-block;
  position: relative;
  z-index: 2;
  padding-right: 5px;
  background: #FFF;
}

tr:nth-child(odd) span {
  background: #FD4;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>This is a test.</p>
  <table>
    <tbody>
      <tr>
        <td><span>Word:</span></td>
      </tr>
      <tr>
        <td><span>Word word:</span></td>
      </tr>
      <tr>
        <td><span>Word word word:</span></td>
      </tr>
      <tr>
        <td><span>Word word word word:</span></td>
      </tr>
    </tbody>
  </table>
  <p>End of test.</p>
</div></code>```

Body:
I've been asked to make a form that has labels in cells (not underlined) followed by an underlined area that indicates where someone is supposed to put information. I don't personally like this design approach, but it is what I've been asked to do.

Something like this:

First Name: ________
Last Name: ________
Street Address: ________

In other words, everything in the table cell is underlined except the label and the trailing space character.

The labels contain varying information and clearly will not align. However, all the underlines should right-align in their respective cells.

Here's a pen that hopefully illustrates what I'm trying to do. https://codepen.io/timmerbu/pen/pojMypE?editors=1100

html {
  font-size: 16px;
}

body {
  background: #9f9;
}

div {
  background: #fff;
  padding: 1rem;
  margin: auto;
  width: 200px;
}

table,
tr,
td {
  margin: 0;
  padding: 0;
  border-collapse: collapse;
}

table {
  width: 100%;
}

tr:nth-child(odd) {
  background: #fd4;
}

td {
  padding: 3px;
}

This is a test.

        Word: __________________

        Word word: ______________

        Word word word: _________

        Word word word word: ____

End of test.

Body:
A little non-formal, but it works. Removing the underscore and adding it back with a CSS Pseudo class, while having the <span> for the text has a background and z-index that puts the underline behind it. You can change the underline placement by adjusting the top: -4px;.

html {
  font-size: 16px;
}

body {
  background: #9f9;
}

div {
  background: #fff;
  padding: 1rem;
  margin: auto;
  width: 200px;
}

table,
tr,
td {
  margin: 0;
  padding: 0;
  border-collapse: collapse;
}

table {
  width: 100%;
}

tr:nth-child(odd) {
  background: #fd4;
}

td {
  padding: 3px;
}

tbody td:after {
  border-bottom: 1px solid #f50909;
  content: "";
  width: 100%;
  height: 1px;
  display: block;
  position: relative;
  top: -4px;
}

td span {
  display: inline-block;
  position: relative;
  z-index: 2;
  padding-right: 5px;
  background: #FFF;
}

tr:nth-child(odd) span {
  background: #FD4;
}

<div>
  <p>This is a test.</p>
  <table>
    <tbody>
      <tr>
        <td><span>Word:</span></td>
      </tr>
      <tr>
        <td><span>Word word:</span></td>
      </tr>
      <tr>
        <td><span>Word word word:</span></td>
      </tr>
      <tr>
        <td><span>Word word word word:</span></td>
      </tr>
    </tbody>
  </table>
  <p>End of test.</p>
</div>


问:
How do I filter data in data frame and change column's cell values based on it using a loop?
Currently working with a larger data frame with various participant IDs that looks like this:

```<code>#ASC_new Data Frame

           Pcp Choice Target ASC       Product choice_consis
2393 zwyn27soc      B      A   1     USB drive             0
2394 zwyn27soc      B      A   1           job             0
2395 zwyn27soc      B      B   1     USB drive             0
2397 zwyn27soc      B      A   1       printer             0
2399 zwyn27soc      B      B   1 walking shoes             0
2400 zwyn27soc      B      A   1       printer             0
</code>```

I would like to try to loop through each participant (Pcp), and look at their choices in column "Choice." For example, under both of the products "USB drive," the participant chose "B" (Choice). Therefore, under "choice_consis," I want there to be a 1 to replace the 0 because the choices are consistent or equal. Although, my for loop for going through the participants and product names isn't working:

```<code>#Examples/snippets of my values

pcp_list <- list("ybg606k3l", "yk83d2asc", "yl55v0zhm", "zwyn27soc")
product_list <- list("USB drive", "printer", "walking shoes", "job")

#for loop that isn't working
for (i in pcp_list){ #iterating through participant codes
  for (j in product_list){ #iterating through product names
    comparison <- filter(ASC_new, Pcp == i & Product == j) #filtering participant data and products into new dataframe

    choice_1 <- ASC_new$Choice[1] #creating labels for choice 1 and 2
    choice_2 <- ASC_new$Choice[2]

    if (isTRUE(choice_1 == choice_2)){ #comparing choice 1 and choice 2 and adding value of 1 to Choice_consis column if they are equal

      ASC_new$choice_consis[1] <- 1
      ASC_new$choice_consis[2] <- 1

    }
  }

}
</code>```

In the end I would like a data frame where each participant's choice_consis is labeled with a 1 or 0 expressing if they chose the same item (A,B,D) both times that each product appeared.

答:
This is something that's pretty natural to do using dplyr, if you don't care about collapsing across different choices. I'll illustrate on a toy data frame:

```<code>IDs <- 1:2
choices <- c('A', 'B')
products <- c('USB', 'Printer')
df <- data.frame(Pcp = rep(IDs, each = 4),
                 Choice = c(rep(choices, each = 2),
                            rep(choices, each = 2)),
                 Product = c(rep(products, times = 2),
                             rep(products, each = 2)))

df %>%
  dplyr::group_by(Pcp, Product) %>%
  dplyr::summarize(choice_consis = as.numeric(length(unique(Choice)) == 1))
</code>```

This does (in essence) the same thing you're trying to do with your for loop: look at each combination of participants and products (that's what the group_by does) and then analyze that combination (that's what the summarize does). It's a little more succinct and readable than a double for loop. I'd check out Chapter 5 of Hadley's book on R for Data Science to learn more about these sorts of things.

As far as what's wrong with your for loop, the issue is that even though you create your comparison data frame, all the subsequent operations are on ASC_new. So if you wanted to use a for loop and maintain the structure of your original data, you could do something like:

```<code>for (i in pcp_list) {
  for (j in product_list) {

    compare <- (ASC_new$Pcp == i) & (ASC_new$Product == j)
    choices <- ASC_new$Choice[compare]

    if (length(unique(choices)) == 1) {
      ASC_new$choice_consis[compare] <- 1
    }
  }
}
</code>```

Creating a new data frame as you did makes it a little harder to substitute values in the original (because we don't know "where" the filtered data frame came from), so I just get the indices of the original data frame corresponding to the participant-product combination. Note also that I eliminated the hard-coding of the fact that there are only two choices, as well as the isTRUE within the if statement (== will evaluate to TRUE or FALSE, as desired).

Hope this helps!

Body:
Currently working with a larger data frame with various participant IDs that looks like this:

#ASC_new Data Frame

           Pcp Choice Target ASC       Product choice_consis
2393 zwyn27soc      B      A   1     USB drive             0
2394 zwyn27soc      B      A   1           job             0
2395 zwyn27soc      B      B   1     USB drive             0
2397 zwyn27soc      B      A   1       printer             0
2399 zwyn27soc      B      B   1 walking shoes             0
2400 zwyn27soc      B      A   1       printer             0

I would like to try to loop through each participant (Pcp), and look at their choices in column "Choice." For example, under both of the products "USB drive," the participant chose "B" (Choice). Therefore, under "choice_consis," I want there to be a 1 to replace the 0 because the choices are consistent or equal. Although, my for loop for going through the participants and product names isn't working:

#Examples/snippets of my values

pcp_list <- list("ybg606k3l", "yk83d2asc", "yl55v0zhm", "zwyn27soc")
product_list <- list("USB drive", "printer", "walking shoes", "job")

#for loop that isn't working
for (i in pcp_list){ #iterating through participant codes
  for (j in product_list){ #iterating through product names
    comparison <- filter(ASC_new, Pcp == i & Product == j) #filtering participant data and products into new dataframe

    choice_1 <- ASC_new$Choice[1] #creating labels for choice 1 and 2
    choice_2 <- ASC_new$Choice[2]

    if (isTRUE(choice_1 == choice_2)){ #comparing choice 1 and choice 2 and adding value of 1 to Choice_consis column if they are equal

      ASC_new$choice_consis[1] <- 1
      ASC_new$choice_consis[2] <- 1

    }
  }

}

In the end I would like a data frame where each participant's choice_consis is labeled with a 1 or 0 expressing if they chose the same item (A,B,D) both times that each product appeared.

Body:
This is something that's pretty natural to do using dplyr, if you don't care about collapsing across different choices. I'll illustrate on a toy data frame:

IDs <- 1:2
choices <- c('A', 'B')
products <- c('USB', 'Printer')
df <- data.frame(Pcp = rep(IDs, each = 4),
                 Choice = c(rep(choices, each = 2),
                            rep(choices, each = 2)),
                 Product = c(rep(products, times = 2),
                             rep(products, each = 2)))

df %>%
  dplyr::group_by(Pcp, Product) %>%
  dplyr::summarize(choice_consis = as.numeric(length(unique(Choice)) == 1))

This does (in essence) the same thing you're trying to do with your for loop: look at each combination of participants and products (that's what the group_by does) and then analyze that combination (that's what the summarize does). It's a little more succinct and readable than a double for loop. I'd check out Chapter 5 of Hadley's book on R for Data Science to learn more about these sorts of things.

As far as what's wrong with your for loop, the issue is that even though you create your comparison data frame, all the subsequent operations are on ASC_new. So if you wanted to use a for loop and maintain the structure of your original data, you could do something like:

for (i in pcp_list) {
  for (j in product_list) {

    compare <- (ASC_new$Pcp == i) & (ASC_new$Product == j)
    choices <- ASC_new$Choice[compare]

    if (length(unique(choices)) == 1) {
      ASC_new$choice_consis[compare] <- 1
    }
  }
}

Creating a new data frame as you did makes it a little harder to substitute values in the original (because we don't know "where" the filtered data frame came from), so I just get the indices of the original data frame corresponding to the participant-product combination. Note also that I eliminated the hard-coding of the fact that there are only two choices, as well as the isTRUE within the if statement (== will evaluate to TRUE or FALSE, as desired).

Hope this helps!


问:
Misuning simpler regex format?
So I am working on a fraction class for school and am using a regex pattern and matcher for user input. I found this online so i'll admit im not exactly sure what does what, but the following pattern finds each digit, middle operation, and allows spaces and tabs between all characters of the user's input(a fraction expression).

```<code>String fractionPattern = "\\s*\\t*\\\\*t*(-?\\d+)\\s*\\t*\\\\*t*\\/\\s*\\t*\\\\*t*(-?\\d+)\\s*\\t*\\\\*t*([-+*/])\\s*\\t*\\\\*t(\\d+)\\s*\\t*\\\\*t*\\/\\s*\\t*\\\\*t*(-?\\d+)\\s*\\t*\\\\*t*";
</code>```

I've tried researching java regex metacharacters and symbol meanings, but I am sort of struggling. Can someone offer me an explanation on each character? Or possibly a simpler way of accomplishing the same thing.

答:
The regex pattern you posted actually matches any operation between two fractions.

There is a lot of noise in there with extra \t (tab) characters (which is redundant with \s for whitespace). Removing those and changing the double backslash to single backslash for readability, we get the following:

```<code>\s*(-?\d+)\s*\/\s*(-?\d+)\s*([-+*/])\s*(\d+)\s*\/\s*(-?\d+)\s*
</code>```

(Double backslash is needed when the regex is in a String, so it is not treated as an escape sequence)

Let's break it down:

\s* means match 0 or more whitespace characters

-? means match one - character or none, for negative numbers

\d+ means match 1 or more numbers (0-9)

The parentheses around (-?\d+) means we can capture this first number and refer to it later if we want to.

\s* means 0 or more whitespace characters again

\/ means match / literally. Some languages / regex parsers require the backslash in front of a forward slash. Others (like Python) do not.

\s*(-?\d+)\s* is the same thing we just did with the first number, again: get another (possibly negative) number, potentially surrounded by whitespace, and capture it with parentheses for later use.

([-+/]) means match any of -, +, or /: the operation we want to perform between the two fractions. Parentheses are optional, only needed if you want to grab this character later.

\s*(\d+)\s*\/\s*(-?\d+)\s* is again what we had with the first fraction, except for some reason the possible negative sign is not included in the numerator, which is probably a mistake.

You can test it out here. (Regex101 is your friend.)

Title: Misuning simpler regex format?

Body:
So I am working on a fraction class for school and am using a regex pattern and matcher for user input. I found this online so i'll admit im not exactly sure what does what, but the following pattern finds each digit, middle operation, and allows spaces and tabs between all characters of the user's input(a fraction expression).

String fractionPattern = "\\s*\\t*\\\\*t*(-?\\d+)\\s*\\t*\\\\*t*\\/\\s*\\t*\\\\*t*(-?\\d+)\\s*\\t*\\\\*t*([-+*/])\\s*\\t*\\\\*t(\\d+)\\s*\\t*\\\\*t*\\/\\s*\\t*\\\\*t*(-?\\d+)\\s*\\t*\\\\*t*";

I've tried researching java regex metacharacters and symbol meanings, but I am sort of struggling. Can someone offer me an explanation on each character? Or possibly a simpler way of accomplishing the same thing.

Body:
The regex pattern you posted actually matches any operation between two fractions.

There is a lot of noise in there with extra \t (tab) characters (which is redundant with \s for whitespace). Removing those and changing the double backslash to single backslash for readability, we get the following:

\s*(-?\d+)\s*\/\s*(-?\d+)\s*([-+*/])\s*(\d+)\s*\/\s*(-?\d+)\s*

(Double backslash is needed when the regex is in a String, so it is not treated as an escape sequence)

Let's break it down:

\s* means match 0 or more whitespace characters

-? means match one - character or none, for negative numbers

\d+ means match 1 or more numbers (0-9)

The parentheses around (-?\d+) means we can capture this first number and refer to it later if we want to.

\s* means 0 or more whitespace characters again

\/ means match / literally. Some languages / regex parsers require the backslash in front of a forward slash. Others (like Python) do not.

\s*(-?\d+)\s* is the same thing we just did with the first number, again: get another (possibly negative) number, potentially surrounded by whitespace, and capture it with parentheses for later use.

([-+/]) means match any of -, +, or /: the operation we want to perform between the two fractions. Parentheses are optional, only needed if you want to grab this character later.

\s*(\d+)\s*\/\s*(-?\d+)\s* is again what we had with the first fraction, except for some reason the possible negative sign is not included in the numerator, which is probably a mistake.

You can test it out here. (Regex101 is your friend.)


问:
Is there a way to Open an App just by its Name in Python
I'm making an "Advanced Virtual Assistant" by using Python and I want to be able to run any app on the PC with just entering its name. Something likes:

```<code>i = input("What App Do You Want To Open?:  ")
d = getDirectory(i)
os.startfile(d)
</code>```

Now I can set this up manually for some apps by getting their directory but it won't be for every app so its not what I need. Is there any easy way to do this?

答:
I've written the below which uses winapps as suggested in my previous answer. This implementation has many limitations, such as it only works for programs installed for all users. However, you could alter this code to use another way of getting the install location and use getPossibleExePaths to get the executables. This answer gives some alternative ways which may be better than winapps.

```<code>import os
import winapps
import subprocess

def getPossibleExePaths(appPath):
    if not appPath:
        raise Exception("App Path cannot be None")
    pattern = appPath + ":*exe"
    try:
        returned = subprocess.check_output(['where', pattern]).decode('utf-8')
        listOfPaths = filter(None, returned.split(os.linesep))
        return [i.strip() for i in list(listOfPaths)]
    except subprocess.CalledProcessError as e:
        raise Exception(f"Error getting path for '{appPath}'")

def getAppPath(appName):
    for app in winapps.search_installed(appName):
        installPath = str(app.install_location)
        if installPath and installPath != "None":
            return installPath
    return None

if __name__ == '__main__':
    print(getPossibleExePaths(getAppPath('Chrome')))
</code>```

This code utilises Window's where command so this will not work cross-platform.

However, please note that getPossibleExePaths will return a list of executable paths and not necessarily the executable that will launch the process. You'll need to figure out how your program will deal with that, there's no easy way to separate out an uninstaller.exe from launchApp.exe. You could, of course, match up the uninstall location that winapps provides and exclude it from the returned list but that doesn't solve the issue that it might not be the launch executable.

I hope that helps you

Body:
I'm making an "Advanced Virtual Assistant" by using Python and I want to be able to run any app on the PC with just entering its name. Something likes:

i = input("What App Do You Want To Open?:  ")
d = getDirectory(i)
os.startfile(d)

Now I can set this up manually for some apps by getting their directory but it won't be for every app so its not what I need. Is there any easy way to do this?

Body:
I've written the below which uses winapps as suggested in my previous answer. This implementation has many limitations, such as it only works for programs installed for all users. However, you could alter this code to use another way of getting the install location and use getPossibleExePaths to get the executables. This answer gives some alternative ways which may be better than winapps.

import os
import winapps
import subprocess

def getPossibleExePaths(appPath):
    if not appPath:
        raise Exception("App Path cannot be None")
    pattern = appPath + ":*exe"
    try:
        returned = subprocess.check_output(['where', pattern]).decode('utf-8')
        listOfPaths = filter(None, returned.split(os.linesep))
        return [i.strip() for i in list(listOfPaths)]
    except subprocess.CalledProcessError as e:
        raise Exception(f"Error getting path for '{appPath}'")

def getAppPath(appName):
    for app in winapps.search_installed(appName):
        installPath = str(app.install_location)
        if installPath and installPath != "None":
            return installPath
    return None

if __name__ == '__main__':
    print(getPossibleExePaths(getAppPath('Chrome')))

This code utilises Window's where command so this will not work cross-platform.

However, please note that getPossibleExePaths will return a list of executable paths and not necessarily the executable that will launch the process. You'll need to figure out how your program will deal with that, there's no easy way to separate out an uninstaller.exe from launchApp.exe. You could, of course, match up the uninstall location that winapps provides and exclude it from the returned list but that doesn't solve the issue that it might not be the launch executable.

I hope that helps you


问:
Selecting data in two tables
I have two tables: who contains these fields:

gmdc_employee

```<code>file_id     company_id  employee_id     employee_name   file_description    file_date      file_name              folder_access        upload_date  confirmation
    1        20111253     20080407         Mariel             file1         2000-01-01  agent_masterlist.xls    documents/20111253/     2011-05-16    Pending
    2        20112301     20864125         Keisha             file2         2000-02-01  auto_lapsed.xls         documents/20112301/     2011-05-16    Pending
   11        20111253     65513215          Rovy              file15        2008-01-01  attendancesheet.xls     documents/20111253/     2011-06-01    Pending
</code>```

gmdc_user

```<code>company_id  company_name    employee_id     employee_name   username    password_clear           password_hash              login_number         last_login
 25014462       NCST          20132248          Danica      ncst            ncst         c7b080d11d6766a27c02591f74b2ea4d        3           2011-05-23 11:25:03
 20112301       EAC           20113318          Emilio      eac             each         933dd8674c563081260867dfa95b5e74        4           2011-05-23 11:52:58
 20111253       DLSU          20080040          John        dlsu            dasma        3c26c824914144d0addf0ceb850ed78a        15          2011-06-01 10:45:32
</code>```

This is the query I used when I first need to get items in my gmdc_employee tables: the '%$search%' is my name for my search button and '$listname%' is my name for my panel tabs(A-Z list):

```<code>select *
   from gmdc_employee
   where employee_name like '%$search%'
     AND employee_name like '$listname%'
</code>```

The problem is in my search button. Before, my search button will only search the employee_name (my code above is the one i used which is working). But the conditions changed unfortunately :( I was asked that aside from searching the employee_name(found in gmdc_employee table) the user may also search for employee_id (which is found in the gmdc_employee) and company_name (which is found in the gmdc_user), but I don't know how to do that :( I haven't learnt from school yet about the joining of two tables, although I learned a way to do that and tried it. Unfortunately it produced wrong results. So may I give an example?

If the user searched for the company name DLSU, the output should look like this:

```<code>employee_id     employee_name   title   file_date    status    confirmation
  20080407        Mariel        file1   2000-01-01   Pending     delete //delete is a link
  65513215         Rovy         file15  2008-01-01   Pending     delete
</code>```

as to what you see,it searches and echoes files under the company name "DLSU" I hope someone could help me here :( I already tried everything but nothing works the way it was suppose to.

This is what I tried to used that produces wrong outputs. :( it echoed all data needed where and did not look in the condition that only the searched company_name info should output:

```<code>select
      a.employee_id,
      a.employee_name,
      a.file_description,
      a.file_date,
      a.confirmation
   from
      gmdc_employee  AS a
         JOIN gmdc_user AS b
   WHERE
          a.employee_name like'%'
      AND a.employee_id like '%'
      AND b.company_name like 'DLSU'
</code>```

答:
A query which should return the data you provided in the Question is:</p>

```<code>SELECT `e`.`employee_id` ,
       `e`.`employee_name` ,
       `e`.`title` ,
       `e`.`file_date` ,
       `e`.`status` ,
       `e`.`confirmation` AS "status"
FROM `gmdc_employee` `e`
  JOIN `gmdc_user` `u` ON ( `u`.`company_id` = `e`.`company_id` )
WHERE `u`.`company_name` LIKE "DLSU"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Selecting data in two tables

Body:
I have two tables: who contains these fields:

gmdc_employee

file_id     company_id  employee_id     employee_name   file_description    file_date      file_name              folder_access        upload_date  confirmation
    1        20111253     20080407         Mariel             file1         2000-01-01  agent_masterlist.xls    documents/20111253/     2011-05-16    Pending
    2        20112301     20864125         Keisha             file2         2000-02-01  auto_lapsed.xls         documents/20112301/     2011-05-16    Pending
   11        20111253     65513215          Rovy              file15        2008-01-01  attendancesheet.xls     documents/20111253/     2011-06-01    Pending

gmdc_user

company_id  company_name    employee_id     employee_name   username    password_clear           password_hash              login_number         last_login
 25014462       NCST          20132248          Danica      ncst            ncst         c7b080d11d6766a27c02591f74b2ea4d        3           2011-05-23 11:25:03
 20112301       EAC           20113318          Emilio      eac             each         933dd8674c563081260867dfa95b5e74        4           2011-05-23 11:52:58
 20111253       DLSU          20080040          John        dlsu            dasma        3c26c824914144d0addf0ceb850ed78a        15          2011-06-01 10:45:32

This is the query I used when I first need to get items in my gmdc_employee tables: the '%$search%' is my name for my search button and '$listname%' is my name for my panel tabs(A-Z list):

select *
   from gmdc_employee
   where employee_name like '%$search%'
     AND employee_name like '$listname%'

The problem is in my search button. Before, my search button will only search the employee_name (my code above is the one i used which is working). But the conditions changed unfortunately :( I was asked that aside from searching the employee_name(found in gmdc_employee table) the user may also search for employee_id (which is found in the gmdc_employee) and company_name (which is found in the gmdc_user), but I don't know how to do that :( I haven't learnt from school yet about the joining of two tables, although I learned a way to do that and tried it. Unfortunately it produced wrong results. So may I give an example?

If the user searched for the company name DLSU, the output should look like this:

employee_id     employee_name   title   file_date    status    confirmation
  20080407        Mariel        file1   2000-01-01   Pending     delete //delete is a link
  65513215         Rovy         file15  2008-01-01   Pending     delete

as to what you see,it searches and echoes files under the company name "DLSU" I hope someone could help me here :( I already tried everything but nothing works the way it was suppose to.

This is what I tried to used that produces wrong outputs. :( it echoed all data needed where and did not look in the condition that only the searched company_name info should output:

select
      a.employee_id,
      a.employee_name,
      a.file_description,
      a.file_date,
      a.confirmation
   from
      gmdc_employee  AS a
         JOIN gmdc_user AS b
   WHERE
          a.employee_name like'%'
      AND a.employee_id like '%'
      AND b.company_name like 'DLSU'

Body:
A query which should return the data you provided in the Question is:

SELECT `e`.`employee_id` ,
       `e`.`employee_name` ,
       `e`.`title` ,
       `e`.`file_date` ,
       `e`.`status` ,
       `e`.`confirmation` AS "status"
FROM `gmdc_employee` `e`
  JOIN `gmdc_user` `u` ON ( `u`.`company_id` = `e`.`company_id` )
WHERE `u`.`company_name` LIKE "DLSU"


问:
How can I export dataframes to each Excel sheet?
I used for loop to make a dataframe and I want to export these data frames for each Excel sheet, and has each sheet name.

For example, first, save the created dataframe with the name "a" in the first Excel worksheet, and the next dataframe with the name "b" in the second Excel worksheet.
these dataframes are made by for loop.

How could I do that?

答:
There is a pandas.DataFrame.to_excel method available

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html


问:
Relating column names with data from a different DataFrame
So, I have three DataFrames:

One containing the amount of sales per item (row) per day (column).

One containing a column with all days and a column with the weeks.

One containing a column with all items, their weekly price and a column with the weeks.

What I would like to do is to modify the first table so that instead of displaying the sales it displays that number multiplied by the price that the item had that day. That is (pseudocode):

```<code>for all items (rows) and days (columns) in table1:

   table1(item, day) = table1(item, day) * table3.prices(item, table2.weeks(day))
</code>```

And I would like to avoid loops and use Pandas operations.

EDIT:

Table 1 is something like this:

```<code>+-------+------+------+------+
|  item | day1 | day2 | day3 |
+-------+------+------+------+
| item1 |   0  |   2  |   3  |
+-------+------+------+------+
| item2 |   1  |   5  |   3  |
+-------+------+------+------+
| item3 |  12  |   7  |   8  |
+-------+------+------+------+
</code>```

Table 2:

```<code>+------+-------+
|  day |  week |
+------+-------+
| day1 | week1 |
+------+-------+
| day2 | week2 |
+------+-------+
| day3 | week2 |
+------+-------+
</code>```

Table 3:

```<code>+-------+-------+-------+
|  item |  week | price |
+-------+-------+-------+
| item1 | week1 |   3   |
+-------+-------+-------+
| item1 | week1 |   4   |
+-------+-------+-------+
| item2 | week2 |   7   |
+-------+-------+-------+
| item2 | week2 |   9   |
+-------+-------+-------+
| item3 | week1 |   2   |
+-------+-------+-------+
| item3 | week2 |   3   |
+-------+-------+-------+
</code>```

Therefore, the expected output would be (if I calculated properly):

```<code>+-------+------+------+------+
|  item | day1 | day2 | day3 |
+-------+------+------+------+
| item1 |   0  |   8  | 12   |
+-------+------+------+------+
| item2 |   7  |  45  | 27   |
+-------+------+------+------+
| item3 |  24  |  21  | 24   |
+-------+------+------+------+
</code>```

答:
I would do a double merge:

```<code># stack the fist table so we can use `day` information
s=tbl1.melt('item', value_name='unit', var_name='day')

(s.merge(tbl3.merge(tbl2,on='week',how='inner'),
       on=['item','day'], how='outer')
  .assign(total=lambda x: x['unit']*x['price'])
   .pivot(index='item',columns='day',values='total')
)
</code>```

Output:

```<code>day    day1  day2  day3
item
item1     0     8    12
item2     7    45    27
item3    24    21    24
</code>```

Update:

Another way is to get get the daily price by day and multiply:

```<code>daily = (tbl3.merge(tbl2,on='week',how='inner')
     .set_index(['item','day']).price
     .unstack()
)

output = tbl1.set_index('item') * daily
</code>```

Output:

```<code>       day1  day2  day3
item
item1     0     8    12
item2     7    45    27
item3    24    21    24
</code>```

Body:
So, I have three DataFrames:

One containing the amount of sales per item (row) per day (column).

One containing a column with all days and a column with the weeks.

One containing a column with all items, their weekly price and a column with the weeks.

What I would like to do is to modify the first table so that instead of displaying the sales it displays that number multiplied by the price that the item had that day. That is (pseudocode):

for all items (rows) and days (columns) in table1:

   table1(item, day) = table1(item, day) * table3.prices(item, table2.weeks(day))

And I would like to avoid loops and use Pandas operations.

EDIT:

Table 1 is something like this:

+-------+------+------+------+
|  item | day1 | day2 | day3 |
+-------+------+------+------+
| item1 |   0  |   2  |   3  |
+-------+------+------+------+
| item2 |   1  |   5  |   3  |
+-------+------+------+------+
| item3 |  12  |   7  |   8  |
+-------+------+------+------+

Table 2:

+------+-------+
|  day |  week |
+------+-------+
| day1 | week1 |
+------+-------+
| day2 | week2 |
+------+-------+
| day3 | week2 |
+------+-------+

Table 3:

+-------+-------+-------+
|  item |  week | price |
+-------+-------+-------+
| item1 | week1 |   3   |
+-------+-------+-------+
| item1 | week1 |   4   |
+-------+-------+-------+
| item2 | week2 |   7   |
+-------+-------+-------+
| item2 | week2 |   9   |
+-------+-------+-------+
| item3 | week1 |   2   |
+-------+-------+-------+
| item3 | week2 |   3   |
+-------+-------+-------+

Therefore, the expected output would be (if I calculated properly):

+-------+------+------+------+
|  item | day1 | day2 | day3 |
+-------+------+------+------+
| item1 |   0  |   8  | 12   |
+-------+------+------+------+
| item2 |   7  |  45  | 27   |
+-------+------+------+------+
| item3 |  24  |  21  | 24   |
+-------+------+------+------+

Body:
I would do a double merge:

# stack the fist table so we can use `day` information
s=tbl1.melt('item', value_name='unit', var_name='day')

(s.merge(tbl3.merge(tbl2,on='week',how='inner'),
       on=['item','day'], how='outer')
  .assign(total=lambda x: x['unit']*x['price'])
   .pivot(index='item',columns='day',values='total')
)

Output:

day    day1  day2  day3
item
item1     0     8    12
item2     7    45    27
item3    24    21    24

Update:

Another way is to get get the daily price by day and multiply:

daily = (tbl3.merge(tbl2,on='week',how='inner')
     .set_index(['item','day']).price
     .unstack()
)

output = tbl1.set_index('item') * daily

Output:

       day1  day2  day3
item
item1     0     8    12
item2     7    45    27
item3    24    21    24


问:
render function is not rendering items
I'm trying to render across an array object in react.js using this:

```<code>const myservice = getAllServices(uid).then(service => {
      renderallServices(service);
      return service;
  });
</code>```

where renderallServices(service) is

```<code>const renderallServices = (services) => (
  <>
  {services.map(service => (
          <Row className="justify-content-md-center">
          <ServiceCard service={service}>
          </ServiceCard>
          {console.log(service)}
          </Row>
        ))

    }
  </>

  );
</code>```

Note: the reason my renderallServices function is being called inside of .then() is because without that it returns a promise instead of the actual array object I want.
I know renderallServices is being called because the {console.log(service)} is returning each element in the array like I would expect. However, none of the JSX is being rendered.

答:
How about you use a state variable to maintain the services and iterate through that state array variable inside the return of your component

```<code>import React, { Fragment, useState } from "react";

const App = ()=>{
 const [services, setServices] = useState([]);
 const myservice = getAllServices(uid).then(service => {
  setServices(service);
  return service;
 });
    return (
    <Fragment>
    {services.length>0&&
      (<Fragment>
          services.map(service => (
           <Row className="justify-content-md-center">
             <ServiceCard service={service}>
             </ServiceCard>
             console.log(service)
            </Row>
           ))
       </Fragment>)
    }
  </Fragment>
    );
 }
</code>```

Hopefully this Helps :)

Title: render function is not rendering items

Body:
I'm trying to render across an array object in react.js using this:

const myservice = getAllServices(uid).then(service => {
      renderallServices(service);
      return service;
  });

where renderallServices(service) is

const renderallServices = (services) => (
  <>
  {services.map(service => (
          <Row className="justify-content-md-center">
          <ServiceCard service={service}>
          </ServiceCard>
          {console.log(service)}
          </Row>
        ))

    }
  </>

  );

Note: the reason my renderallServices function is being called inside of .then() is because without that it returns a promise instead of the actual array object I want.
I know renderallServices is being called because the {console.log(service)} is returning each element in the array like I would expect. However, none of the JSX is being rendered.

Body:
How about you use a state variable to maintain the services and iterate through that state array variable inside the return of your component

import React, { Fragment, useState } from "react";

const App = ()=>{
 const [services, setServices] = useState([]);
 const myservice = getAllServices(uid).then(service => {
  setServices(service);
  return service;
 });
    return (
    <Fragment>
    {services.length>0&&
      (<Fragment>
          services.map(service => (
           <Row className="justify-content-md-center">
             <ServiceCard service={service}>
             </ServiceCard>
             console.log(service)
            </Row>
           ))
       </Fragment>)
    }
  </Fragment>
    );
 }

Hopefully this Helps :)


问:
Can I add a self defined layers in google earth through the kml?
I want a function ,when I choose myself defined layer,then the aim come out.such as in Google earth, when I choose the "water body outlines",the water area outlines displayed.Can I achieve this in the Google earth? or there is another way to achieve this?</p>

答:
The layers are provided by the Google Earth server, not by KML. So no - it is not possible to add custom layers to GE using straight KML.

You could of course put the water body outlines into a KML object and have it be displayed in Google Earth. It'd show up under the "places" tree (in temporary places -- until the user chooses to save it to my places.) When your KML object is in temp/my places the user can toggle it on and off just like a layer, from the user perspective it looks and feels the same.

From the administrator's perspective it's not the best approach because your underlying KML becomes easily obtainable. All the user has to do is click on your KML object in temp/my places and press CTRL+C to copy the KML to the clipboard. Then they can simply CTRL+V into notepad (or some other text editor) and read/edit the KML. Something to keep in mind.

If you have a Google Earth Enterprise (Fusion) Server, the sky's the limit. You can bake whatever you want into the layers panel. But that's only if you have an enterprise server and all your users are using GE Enterprise.


答:
I think with the underlined field, you would like the user to enter the text too...
I suggest the following HTML

You can use a
 or any other suitable container tag, I am using

   First Name:
   <input type="text" style="border: none; border-bottom: solid 1px black; width: 200px" />

```
</div>
</div>
</p>

<p>You can put the styling in a CSS as well</p>

<hr>

<p><strong>UPDATED</strong></p>

<p>Right align all the underlines</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><table style="width: 300px">
    <tr>
      <td>
       <div style="width: 100%; float: left">
        <span style="background-color: white">First Name: </span>
        <hr style="margin-top: -4px;/>
       </div>
      </td>
    </tr>

    <tr>
      <td>
       <div style="width: 100%; float: left">
        <span style="background-color: white">Last Name: </span>
        <hr style="margin-top: -4px;/>
       </div>
      </td>
    </tr>

    <tr>
      <td>
       <div style="width: 100%; float: left">
        <span style="background-color: white">Age: </span>
        <hr style="margin-top: -4px;/>
       </div>
      </td>
    </tr>

    <tr>
      <td>
       <div style="width: 100%; float: left">
        <span style="background-color: white">Gender: </span>
        <hr style="margin-top: -4px;/>
       </div>
      </td>
    </tr>

    </table></code>```

Title: How to underline a field on a form except text in the cell

Body:
I think with the underlined field, you would like the user to enter the text too...
I suggest the following HTML

You can use a <span> <td> <p> or any other suitable container tag, I am using <div>

 <div>
   First Name:
   <input type="text" style="border: none; border-bottom: solid 1px black; width: 200px" />

 </div>

You can put the styling in a CSS as well

UPDATED

Right align all the underlines

<table style="width: 300px">
    <tr>
      <td>
       <div style="width: 100%; float: left">
        <span style="background-color: white">First Name: </span>
        <hr style="margin-top: -4px;/>
       </div>
      </td>
    </tr>

    <tr>
      <td>
       <div style="width: 100%; float: left">
        <span style="background-color: white">Last Name: </span>
        <hr style="margin-top: -4px;/>
       </div>
      </td>
    </tr>

    <tr>
      <td>
       <div style="width: 100%; float: left">
        <span style="background-color: white">Age: </span>
        <hr style="margin-top: -4px;/>
       </div>
      </td>
    </tr>

    <tr>
      <td>
       <div style="width: 100%; float: left">
        <span style="background-color: white">Gender: </span>
        <hr style="margin-top: -4px;/>
       </div>
      </td>
    </tr>

    </table>


问:
Channels: why message is send at the end of processing
why using sync function get_channel_layer().send(), message is send at the end of processing

def external_send(channel_name, data):
    channel_layer = get_channel_layer()
    send_sync = async_to_sync(channel_layer.send)
    send_sync(
        channel_name,
        {
            "type": "send_json",
            "message": {"datetime": datetime.datetime.now().isoformat(), **data},
        },
    )
```

<p>using <code>self.send()</code> in consumer work as expected</p>

<p>here is my consumer class for testing purpose:</p>

<pre class="lang-py prettyprint-override"><code>class TestConsumer(JsonWebsocketConsumer):
    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass

    def receive_json(self, content, **kwargs):
        logger.debug(f"RECEIVE {content}")
        self.send_json(
            {
                "id": 1,
                "text": "Before sleep: self.send_json",
                "datetime": datetime.datetime.now().isoformat(),
            }
        )
        external_send(
            self.channel_name, {"id": 2, "text": "Before sleep external_send"}
        )
        sleep(10)  # Simuleting long processing
        self.send_json(
            {
                "id": 3,
                "text": "After sleep: self.send_json",
                "datetime": datetime.datetime.now().isoformat(),
            }
        )
        super().receive_json(content, **kwargs)
        logger.debug("END")

</code>```

At frontend I'm receiving order

{id: 1, text: "Before sleep: self.send_json", datetime: "2020-05-29T14:30:58.226545"}

{id: 3, text: "After sleep: self.send_json", datetime: "2020-05-29T14:31:03.244865"}

{id: 2, text: "Before sleep external_send", datetime: "2020-05-29T14:30:58.230164"}

答:
In answer, each channel consumer gets its own little runloop. It will only handle one event at a time. This single runloop is used for both messages received from the client (over the ws) and messages being handled through group send events on the channel layers.

if you receive_json method you are sleeping that is sleeping the loop so nothing else will happen. receive_json needs to finish before any message sent over the channel layer will be handled.

Looking at your code there are a few other points that need to be pointed out

Sync sleep

If you do need to sleep in a method never do that in a sync method, this will sleep your entier python program (everything will sleep).

Use the Async consumer then you can await asyncio.sleep(20) this will then just sleep your runloop for that single consumer and other websocket connections etc will continue to run. This is also true for any other long running task you should use a async consumer and then use a async threadpool  to await these long running tasks.

You should not attempt to group send to the send_json method directly.

Intread you should create a method on your consumer handle_message this method can call send_json and your group sends should send messages with type handle.message.

Body:
why using sync function get_channel_layer().send(), message is send at the end of processing

def external_send(channel_name, data):
    channel_layer = get_channel_layer()
    send_sync = async_to_sync(channel_layer.send)
    send_sync(
        channel_name,
        {
            "type": "send_json",
            "message": {"datetime": datetime.datetime.now().isoformat(), **data},
        },
    )

using self.send() in consumer work as expected

here is my consumer class for testing purpose:

class TestConsumer(JsonWebsocketConsumer):
    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass

    def receive_json(self, content, **kwargs):
        logger.debug(f"RECEIVE {content}")
        self.send_json(
            {
                "id": 1,
                "text": "Before sleep: self.send_json",
                "datetime": datetime.datetime.now().isoformat(),
            }
        )
        external_send(
            self.channel_name, {"id": 2, "text": "Before sleep external_send"}
        )
        sleep(10)  # Simuleting long processing
        self.send_json(
            {
                "id": 3,
                "text": "After sleep: self.send_json",
                "datetime": datetime.datetime.now().isoformat(),
            }
        )
        super().receive_json(content, **kwargs)
        logger.debug("END")

At frontend I'm receiving order

{id: 1, text: "Before sleep: self.send_json", datetime: "2020-05-29T14:30:58.226545"}

{id: 3, text: "After sleep: self.send_json", datetime: "2020-05-29T14:31:03.244865"}

{id: 2, text: "Before sleep external_send", datetime: "2020-05-29T14:30:58.230164"}


问:
c# reading a tab delimitted file into datatable
```<code>    private void Form1_Load(object sender, EventArgs e)
    {
        GetDataTable(@"C:\Documents and Settings\agordon\Desktop\ACTIVITYEX.csv");
    }
    public System.Data.DataTable GetDataTable(string strFileName)
    {
        System.Data.OleDb.OleDbConnection conn =
            new System.Data.OleDb.OleDbConnection
                ("Provider=Microsoft.Jet.OleDb.4.0; Data Source = "
                + System.IO.Path.GetDirectoryName(strFileName)
                + ";Extended Properties = \"Text;HDR=YES;FMT=TabDelimited\"");
        conn.Open();
        string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
        System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
        System.Data.DataTable ds = new System.Data.DataTable("CSV File");
        adapter.Fill(ds);
        return ds;
    }
</code>```

even though the data is tab delimitted it is writing an enter row into one datapoint. it is not recognizing the tabbing. here is an example of one of the tabs: "  "

here is an example of one row that it imported into one single data point:

V2.00 Administrator       TX  0002    08:50
  04/14/11  0   F   004 H   14400   0000    0000

  ok    02  1   biscom-server   4321

    Administrator           08:50:31
  04/14/2011    08:50:33
  04/14/2011    08:50:00
  04/14/2011        12ffefe9-fa4f-4b45-8dcb-8ed2a2e28de3    419571  004 YES                 C:\MerthTesting\XIFINFax\Receive\20110414085022\FAX_8582170332_101169_20110413_13_36.pdf                                                                                normal  BISCOM-SERVER_Dev_1104141550330002

what am i doing wrong? what is the data being scrunched into one data point ?

答:
Someone else had the exact same problem:

http://social.microsoft.com/Forums/en-US/Offtopic/thread/9f7d2b67-cea5-4840-96ef-2e12011752d7

Body:
    private void Form1_Load(object sender, EventArgs e)
    {
        GetDataTable(@"C:\Documents and Settings\agordon\Desktop\ACTIVITYEX.csv");
    }
    public System.Data.DataTable GetDataTable(string strFileName)
    {
        System.Data.OleDb.OleDbConnection conn =
            new System.Data.OleDb.OleDbConnection
                ("Provider=Microsoft.Jet.OleDb.4.0; Data Source = "
                + System.IO.Path.GetDirectoryName(strFileName)
                + ";Extended Properties = \"Text;HDR=YES;FMT=TabDelimited\"");
        conn.Open();
        string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
        System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
        System.Data.DataTable ds = new System.Data.DataTable("CSV File");
        adapter.Fill(ds);
        return ds;
    }

even though the data is tab delimitted it is writing an enter row into one datapoint. it is not recognizing the tabbing. here is an example of one of the tabs: "  "

here is an example of one row that it imported into one single data point:

V2.00 Administrator       TX  0002    08:50
  04/14/11  0   F   004 H   14400   0000    0000

  ok    02  1   biscom-server   4321

    Administrator           08:50:31
  04/14/2011    08:50:33
  04/14/2011    08:50:00
  04/14/2011        12ffefe9-fa4f-4b45-8dcb-8ed2a2e28de3    419571  004 YES                 C:\MerthTesting\XIFINFax\Receive\20110414085022\FAX_8582170332_101169_20110413_13_36.pdf                                                                                normal  BISCOM-SERVER_Dev_1104141550330002

what am i doing wrong? what is the data being scrunched into one data point ?


问:
Google Sheets - Change row color once multiple boxes are checked
In Google Sheets, I would like each row to turn green, once two of the checkboxes (in Columns F and G) are checked for that row.

I have tried using conditional formatting with the following formulas applied to range A2:I145:

```<code>=IF($F2=TRUE,1)=AND($G2=TRUE,1)  /* This colors the row when cells are unchecked */

=IF($F2:$G2=TRUE) /* This does not color the row at all */
</code>```

I know that if it was only based on one checkbox, it could be accomplished with =$F2=TRUE. There is documentation on this here, but they don't give an example with requirement of two checkboxes.

Is there a simple function that can perform this task?

答: One TRUE value is treated as 1, which is why two TRUE values sum up to 2. You just need to check your cells against equating to 2. Please see a picture below; of range A1:A5 only A2 gets colored since only B2+C2 result in 2.

Body:
In Google Sheets, I would like each row to turn green, once two of the checkboxes (in Columns F and G) are checked for that row.

I have tried using conditional formatting with the following formulas applied to range A2:I145:

=IF($F2=TRUE,1)=AND($G2=TRUE,1)  /* This colors the row when cells are unchecked */

=IF($F2:$G2=TRUE) /* This does not color the row at all */

I know that if it was only based on one checkbox, it could be accomplished with =$F2=TRUE. There is documentation on this here, but they don't give an example with requirement of two checkboxes.

Is there a simple function that can perform this task?


问:
How to modify list of list elements python
I have a list of lists

```<code> check = [['KH8X070.jpeg', 'ZDO9A8O.jpeg', 'ZW25RD8.jpeg', '6ZLXW92.jpeg', 'HVLA5UT.jpeg', 'A4UDC12.jpeg', '2X5KO9A.jpeg', '5HZR4VV.jpeg', '24FWS4S.jpeg'], ['Z2QC6PW.jpeg', 'EHMK14E.jpeg', 'RTV0PRH.jpeg', '71S643D.jpeg', 'KECHDQ9.jpeg', 'RU6PYPB.jpeg'], ['UG9Z4SQ.jpeg', 'H0Y3SYV.jpeg', '61HCFOK.jpeg', '14KE527.jpeg', 'XMSM050.jpeg', '5KFI2V3.jpeg', 'QSJMKUB.jpeg', 'S6TX0ZM.jpeg', '8JV3K1Y.jpeg', 'XI9OOI7.jpeg', 'JMWDOPM.jpeg'], ['0SAXG3I.jpeg', 'LA5HJNO.jpeg', 'PHHAUSA.jpeg', '900Z7S7.jpeg']]
</code>```

such that I have:

```<code> check = [[0,0,0,0,0,0,0,0,0],[1,1,1,1,1,1], [2,2,2,2,2,2,2,2,2,2,2], [3,3,3,3]]
</code>```

I want to modify it such that in index list 0 of the list of list, I'll have 0's all through, in index 1 I would have 1's all through, in index 2 I'll have 2's all through and so on like that.

```<code>for i, j in enumerate(check):
  checks = [...]
</code>```

I know it should be a list comprehension there, but don't just know how to go about it. That's why I have come here for help.

答:
Here's my take with an one-liner code : </p>

```<code>>>> [map(lambda val : i, arr) for i,arr in enumerate(check)]
</code>```

Body:
I have a list of lists

 check = [['KH8X070.jpeg', 'ZDO9A8O.jpeg', 'ZW25RD8.jpeg', '6ZLXW92.jpeg', 'HVLA5UT.jpeg', 'A4UDC12.jpeg', '2X5KO9A.jpeg', '5HZR4VV.jpeg', '24FWS4S.jpeg'], ['Z2QC6PW.jpeg', 'EHMK14E.jpeg', 'RTV0PRH.jpeg', '71S643D.jpeg', 'KECHDQ9.jpeg', 'RU6PYPB.jpeg'], ['UG9Z4SQ.jpeg', 'H0Y3SYV.jpeg', '61HCFOK.jpeg', '14KE527.jpeg', 'XMSM050.jpeg', '5KFI2V3.jpeg', 'QSJMKUB.jpeg', 'S6TX0ZM.jpeg', '8JV3K1Y.jpeg', 'XI9OOI7.jpeg', 'JMWDOPM.jpeg'], ['0SAXG3I.jpeg', 'LA5HJNO.jpeg', 'PHHAUSA.jpeg', '900Z7S7.jpeg']]

such that I have:

 check = [[0,0,0,0,0,0,0,0,0],[1,1,1,1,1,1], [2,2,2,2,2,2,2,2,2,2,2], [3,3,3,3]]

I want to modify it such that in index list 0 of the list of list, I'll have 0's all through, in index 1 I would have 1's all through, in index 2 I'll have 2's all through and so on like that.

for i, j in enumerate(check):
  checks = [...]

I know it should be a list comprehension there, but don't just know how to go about it. That's why I have come here for help.

Body:
Here's my take with an one-liner code :

>>> [map(lambda val : i, arr) for i,arr in enumerate(check)]


问:
How do you find the namespace/module name programmatically in Ruby on Rails?
How do I find the name of the namespace or module 'Foo' in the filter below?</p>

```<code>class ApplicationController < ActionController::Base
  def get_module_name
    @module_name = ???
  end
end

class Foo::BarController < ApplicationController
  before_filter :get_module_name
end
</code>```

答:
For Rails 6.1

self.class.module_parent

Hettomei answer works fine up to Rails 6.0

DEPRECATION WARNING: Module#parent has been renamed to module_parent. parent is deprecated and will be removed in Rails 6.1.

OwnerDisplayName: Steropes

Body:
How do I find the name of the namespace or module 'Foo' in the filter below?

class ApplicationController < ActionController::Base
  def get_module_name
    @module_name = ???
  end
end

class Foo::BarController < ApplicationController
  before_filter :get_module_name
end

LastEditorDisplayName: Christoph Schiessl


问:
How to use GenericArray with a limited range of length that can be detected at compile time?
For example,

struct Foo<T, N: ArrayLength<T>> {
    data: GenericArray<T, N>
}
```

I want the length of the data array to be limited within a range like 100 to 1024 bytes. Then, if the Foo is used like let f: Foo<u8, generic_array::typenum::U8> = Foo {data: GenericArray::default()};, it will cause a compilation error.

答:
I think that what you want is Const Generics.

This feature exists in Rust, but it's still a work-in-progress. You can use it in nightly, and as far as I understand, there are some use cases that do work as intended.

Basically this allows you to have a generic type like this:

struct Foo<T, const N: usize> {
    // Here you can use `N` as a `const`. For example, to define the size of a `std::array`
}
```

Here are links to have or follow for this feature:

The const generics RFC

The tracking issue for this feature in the rustc repo

Latest report by varkor, the main implementor of this feature.

All in all, I think it's a shame that you can't use it in stable just yet. But great things take time to be built.

Check if you can use it. There are some std types that do use it today (and in stable because they have been audited to be sound and stable already). For example, std::array uses it extensively since at least 1 year ago.

I hope this helps <3

Body:
For example,

struct Foo<T, N: ArrayLength<T>> {
    data: GenericArray<T, N>
}

I want the length of the data array to be limited within a range like 100 to 1024 bytes. Then, if the Foo is used like let f: Foo<u8, generic_array::typenum::U8> = Foo {data: GenericArray::default()};, it will cause a compilation error.

Body:
I think that what you want is Const Generics.

This feature exists in Rust, but it's still a work-in-progress. You can use it in nightly, and as far as I understand, there are some use cases that do work as intended.

Basically this allows you to have a generic type like this:

struct Foo<T, const N: usize> {
    // Here you can use `N` as a `const`. For example, to define the size of a `std::array`
}

Here are links to have or follow for this feature:

The const generics RFC

The tracking issue for this feature in the rustc repo

Latest report by varkor, the main implementor of this feature.

All in all, I think it's a shame that you can't use it in stable just yet. But great things take time to be built.

Check if you can use it. There are some std types that do use it today (and in stable because they have been audited to be sound and stable already). For example, std::array uses it extensively since at least 1 year ago.

I hope this helps <3


问:
Why does this 'eloquent Javascript' recursive solution work?
I'm working through Eloquent Javascript, the exercise asks to find a recursive solution for finding the nth element in a nested list of this form;

```<code>var list = {
   value: 1,
   rest: {
     value: 2,
     rest: {
       value: 3,
       rest: null
     }
   }
};
</code>```

After scratching my head over this for far too long I duly checked the answer.

```<code>function nth(list, n) {
  if (!list)
    return undefined;
  else if (n == 0)
    return list.value;
  else
    return nth(list.rest, n - 1);
</code>```

I can see that this does indeed produce the right result but I do not understand why.

My understanding of the logic is as follows

If no list is provided or list is falsey, return undefined,
else if n is 0, then return the first element of the list - which is given by list.value.
Else call the function again but decrement n by 1.

Clearly I must be missing something but I do not understand how this logic can return the nth element. It seems like it will just keep recursing until n==0. At which point it will simply return the first element of the list.

答:
This statement also made me think well. i have finally figured it out so i feel i should add to the previous answer.

the "n-1" statement in the  nth(list.rest, n - 1) is essentially a timer that determines when the programme should terminate. remember when it gets to 0 it returns the value as per this statement.

```<code> else if (n == 0)
    return list.value;
</code>```

so for example a list is passed into your function
 "{ Value: 1, Rest: { Value: 2, Rest: { Value: 3, Rest: null } } }"
 You pass in 2 as the argument.
 it calls the function and goes through the if statements then gets to the recursive statement. it calls List.Rest and then decreases the value of your passed in argument by 1.
It repeats the cycle above and gets to the recursive function where what gets passed is now List.Rest.Rest your argument decreases by 1 again and it becomes 0 .
When it passes through the if and else if statement , because the argument is now 0 the below line gets triggered

```<code>else if (n == 0)
    return list.value;
</code>```

it then returns the list. value.... remember that your list is now list.Rest.Rest
making your value now 3.

Body:
I'm working through Eloquent Javascript, the exercise asks to find a recursive solution for finding the nth element in a nested list of this form;

var list = {
   value: 1,
   rest: {
     value: 2,
     rest: {
       value: 3,
       rest: null
     }
   }
};

After scratching my head over this for far too long I duly checked the answer.

function nth(list, n) {
  if (!list)
    return undefined;
  else if (n == 0)
    return list.value;
  else
    return nth(list.rest, n - 1);

I can see that this does indeed produce the right result but I do not understand why.

My understanding of the logic is as follows

If no list is provided or list is falsey, return undefined,
else if n is 0, then return the first element of the list - which is given by list.value.
Else call the function again but decrement n by 1.

Clearly I must be missing something but I do not understand how this logic can return the nth element. It seems like it will just keep recursing until n==0. At which point it will simply return the first element of the list.

Body:
This statement also made me think well. i have finally figured it out so i feel i should add to the previous answer.

the "n-1" statement in the  nth(list.rest, n - 1) is essentially a timer that determines when the programme should terminate. remember when it gets to 0 it returns the value as per this statement.

 else if (n == 0)
    return list.value;

so for example a list is passed into your function
 "{ Value: 1, Rest: { Value: 2, Rest: { Value: 3, Rest: null } } }"
 You pass in 2 as the argument.
 it calls the function and goes through the if statements then gets to the recursive statement. it calls List.Rest and then decreases the value of your passed in argument by 1.
It repeats the cycle above and gets to the recursive function where what gets passed is now List.Rest.Rest your argument decreases by 1 again and it becomes 0 .
When it passes through the if and else if statement , because the argument is now 0 the below line gets triggered

else if (n == 0)
    return list.value;

it then returns the list. value.... remember that your list is now list.Rest.Rest
making your value now 3.


问:
Unable to use package manager console in visual studio 2019 that running inside Virtual Machine
I'm trying to run my .NET Core 3.1 Applications by Windows Virtual Machine with new Visual studio 2019 IDE (my Applications not created in this Virtual Machine) but I encountered two problems first one is :
VS couldn't restore all solution packages , second one is : So when I wan't to try to solve this problem by some commands using Package Manager console I encountered below problem

Unable to find fallback package folder '/usr/share/dotnet/sdk/NuGetFallbackFolder'.

And here is the screen shoot:

Note : My Application has been built by (Asp.net core Boilerplate framework)

答:
I found it, I followed below steps and everything worked fine:

first of all, you should edit the paths in project. assets file to become refers to a new project path.

Open Power Shell for the same directory that .sln file exist then run below command

```<code>PS E:\WorkSpace\VMTEST\5.5.0\aspnet-core\src\VMTEST.Web.Core\obj>dotnet restore VMTEST.sln
</code>```

(if won't work, run the command again)

Ensure that you have cleared the Nuget caches.

clean your project.

Build your project.

close the VS and reopen it again.

In my case the above steps fix the problem (both problem Package console and restore packages problem).

Body:
I found it, I followed below steps and everything worked fine:

first of all, you should edit the paths in project. assets file to become refers to a new project path.

Open Power Shell for the same directory that .sln file exist then run below command

PS E:\WorkSpace\VMTEST\5.5.0\aspnet-core\src\VMTEST.Web.Core\obj>dotnet restore VMTEST.sln

(if won't work, run the command again)

Ensure that you have cleared the Nuget caches.

clean your project.

Build your project.

close the VS and reopen it again.

In my case the above steps fix the problem (both problem Package console and restore packages problem).


问:
Remove validator after submitting
I created two textboxes one for the title and another for the name.

I am using validations if the textboxes are not filled, so the information is only submitted if both are filled.

My problem is that after submitting I try to clear the values of the variables and when clearing that value the validation messages appear.

Is there a way to successfully submit and clear the value of variables, the validator does not appear?

DEMO

html

```<code><div style="margin-top:16px;width:50%">
    <dx-text-box placeholder="title..." [showClearButton]="true" [(ngModel)]="title">
        <dx-validator>
            <dxi-validation-rule type="required" message="Insert Title">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>
</div>
<div style="margin-top:16px;width:50%">
    <dx-text-box placeholder="name..." [showClearButton]="true" [(ngModel)]="name">
        <dx-validator>
            <dxi-validation-rule type="required" message="Insert Name">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>
</div>

<dx-button text="Submit" [useSubmitBehavior]="true" (onClick)="Save()"></dx-button>
</code>```

.ts

```<code>title: string;
name: string;

Save(){
  if(this.title == "" || this.title == undefined || this.name == "" || this.name == undefined){
  }
  else{
    alert("Sucess !!");
    this.title = "";
    this.name = "";
  }
}
</code>```

Problem

Here, I filled in the textboxes and submitted successfully. I cleared the value of the variables, but when doing this, the validator is activated, when in fact everything was supposed to be in the initial state :(

答:
here a trick I'm usually using to clear all validators after submit.

  @ViewChildren(DxValidatorComponent) validatorViewChildren: QueryList<DxValidatorComponent>;

  private clearDxValidators = () => {
    this.validatorViewChildren.toArray().map(ref => {
      ref.instance.reset();
    })
  }

```

read more about reset()

Title: Remove validator after submitting

Body:
I created two textboxes one for the title and another for the name.

I am using validations if the textboxes are not filled, so the information is only submitted if both are filled.

My problem is that after submitting I try to clear the values of the variables and when clearing that value the validation messages appear.

Is there a way to successfully submit and clear the value of variables, the validator does not appear?

DEMO

html

    <dx-text-box placeholder="title..." [showClearButton]="true" [(ngModel)]="title">
        <dx-validator>
            <dxi-validation-rule type="required" message="Insert Title">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>

    <dx-text-box placeholder="name..." [showClearButton]="true" [(ngModel)]="name">
        <dx-validator>
            <dxi-validation-rule type="required" message="Insert Name">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>

<dx-button text="Submit" [useSubmitBehavior]="true" (onClick)="Save()"></dx-button>

.ts

title: string;
name: string;

Save(){
  if(this.title == "" || this.title == undefined || this.name == "" || this.name == undefined){
  }
  else{
    alert("Sucess !!");
    this.title = "";
    this.name = "";
  }
}

Problem

Here, I filled in the textboxes and submitted successfully. I cleared the value of the variables, but when doing this, the validator is activated, when in fact everything was supposed to be in the initial state :(

Body:
here a trick I'm usually using to clear all validators after submit.

  @ViewChildren(DxValidatorComponent) validatorViewChildren: QueryList<DxValidatorComponent>;

  private clearDxValidators = () => {
    this.validatorViewChildren.toArray().map(ref => {
      ref.instance.reset();
    })
  }

read more about reset()


Title: Python - create matrix of tuples

Body:
I need to create a 9x9 matrix of tuples. I already have a code:

squares, sub = [], []
for y in [3, 6, 9]:
    sub.append([[(y, x) for x in range(1, 10) if x % 3 == 0] for x in range(1, 10) if x % 3 == 0])

for i in sub:
    sq = []
    for j in i:
        sq.extend(j)
    sq.sort()
    squares.append(sq)
    squares.append(sq)
    squares.append(sq)

with such result:

[[(3, 3), (3, 3), (3, 3), (3, 6), (3, 6), (3, 6), (3, 9), (3, 9), (3, 9)],
 [(3, 3), (3, 3), (3, 3), (3, 6), (3, 6), (3, 6), (3, 9), (3, 9), (3, 9)],
 [(3, 3), (3, 3), (3, 3), (3, 6), (3, 6), (3, 6), (3, 9), (3, 9), (3, 9)],
 [(6, 3), (6, 3), (6, 3), (6, 6), (6, 6), (6, 6), (6, 9), (6, 9), (6, 9)],
 [(6, 3), (6, 3), (6, 3), (6, 6), (6, 6), (6, 6), (6, 9), (6, 9), (6, 9)],
 [(6, 3), (6, 3), (6, 3), (6, 6), (6, 6), (6, 6), (6, 9), (6, 9), (6, 9)],
 [(9, 3), (9, 3), (9, 3), (9, 6), (9, 6), (9, 6), (9, 9), (9, 9), (9, 9)],
 [(9, 3), (9, 3), (9, 3), (9, 6), (9, 6), (9, 6), (9, 9), (9, 9), (9, 9)],
 [(9, 3), (9, 3), (9, 3), (9, 6), (9, 6), (9, 6), (9, 9), (9, 9), (9, 9)]]

Result is exactly as I want it to be, but do you think there is a better way to write it? Can it be done simpler?

Edit:

Result should be always identical, there isn't any dynamic input and it won't be edited afterwards. Just a static matrix used in a different part of my code.

Body:
The question is a bit unclear, as the final list (and the code) might be interpreted, and there might be multiple interpretations with the same result.

For one such interpretation, you could use a (twisted and kind of funny looking) nested list comprehension ([Python 3.Docs]: Data Structures - List Comprehensions):

>>> from pprint import pprint as pp  # For print purposes only
>>>
>>> l = [3, 6, 9]
>>>
>>> items = [[i0 for i1 in l for i0 in ((i2, i1),) * len(l)] for i2 in l for _ in l]
>>>
>>> pp(items)
[[(3, 3), (3, 3), (3, 3), (3, 6), (3, 6), (3, 6), (3, 9), (3, 9), (3, 9)],
 [(3, 3), (3, 3), (3, 3), (3, 6), (3, 6), (3, 6), (3, 9), (3, 9), (3, 9)],
 [(3, 3), (3, 3), (3, 3), (3, 6), (3, 6), (3, 6), (3, 9), (3, 9), (3, 9)],
 [(6, 3), (6, 3), (6, 3), (6, 6), (6, 6), (6, 6), (6, 9), (6, 9), (6, 9)],
 [(6, 3), (6, 3), (6, 3), (6, 6), (6, 6), (6, 6), (6, 9), (6, 9), (6, 9)],
 [(6, 3), (6, 3), (6, 3), (6, 6), (6, 6), (6, 6), (6, 9), (6, 9), (6, 9)],
 [(9, 3), (9, 3), (9, 3), (9, 6), (9, 6), (9, 6), (9, 9), (9, 9), (9, 9)],
 [(9, 3), (9, 3), (9, 3), (9, 6), (9, 6), (9, 6), (9, 9), (9, 9), (9, 9)],
 [(9, 3), (9, 3), (9, 3), (9, 6), (9, 6), (9, 6), (9, 9), (9, 9), (9, 9)]]

Note: Attempting to modify your final list (squares[0][0] = 1) might yield "unexpected" results.


问:
Pretty print CSV with many columns with each row as a table
I have a very large CSV with ~50 columns like the follows:

```<code>A,B,C,...,Z
v1,,v3,...,v26
w1,w2,w3,...,w26
</code>```

I want to display it in console, but tools like column -t doesn't work because each line is too long and wraps, making it unable to be read.

My goal is to display it row by row, with each row displayed as a table like <ColumnName> | <Value>:

```<code>----------
A |  v1
B |
C |  v3
...
Z |  v26
----------
<blank line>
----------
A |  w1
B |  w2
...
Z |  w26
----------
</code>```

Body:
I have a very large CSV with ~50 columns like the follows:

A,B,C,...,Z
v1,,v3,...,v26
w1,w2,w3,...,w26

I want to display it in console, but tools like column -t doesn't work because each line is too long and wraps, making it unable to be read.

My goal is to display it row by row, with each row displayed as a table like <ColumnName> | <Value>:

----------
A |  v1
B |
C |  v3
...
Z |  v26
----------
<blank line>
----------
A |  w1
B |  w2
...
Z |  w26
----------

Body:
Using awk:

$ awk -F, 'NR == 1 { for (i = 1; i <= NF; i++) h[i] = $i; next }
           { print "----------"
             for (i = 1; i <= NF; i++) printf "%s | %s\n", h[i], $i
             print "----------\n"
           }' input.csv
----------
A | v1
B |
C | v3
... | ...
Z | v26
----------

----------
A | w1
B | w2
C | w3
... | ...
Z | w26
----------


问:
flutter: CupertinoAlertDialog looks different from what is shown in official docs
I tried implementing the CupertinoAlertDialog (https://api.flutter.dev/flutter/cupertino/CupertinoAlertDialog-class.html) but when I used it, it looked like this:

which is quite different from how it looks when signing in with google or as shown in the image here (https://flutter.dev/docs/development/ui/widgets/cupertino)

Here's the code:

```<code>showDialog(
          context: context,
          barrierDismissible: true,
          builder: (_) => _buildAlertDialog());

Widget _buildAlertDialog() {
    return CupertinoAlertDialog(
      title: Text(
        '\"Abc\" Wants to Use \"xyz.com\" to Sign In',
      ),
      content: Text(
        'This allows the app and website to share information about you.',
      ),
      actions: <Widget>[
        CupertinoDialogAction(
          child: Text('Cancel'),
          onPressed: () {
            // Drop the dialog
            Navigator.pop(context);
          },
        ),
        CupertinoDialogAction(
          child: Text('Continue'),
          onPressed: () {
            // Drop the dialog
            Navigator.pop(context);
            // handle continue press

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

答:
I tested your Code. I get the same result.

After some digging I found this : https://issue.life/questions/57676581

Looks like the backgroundColor is hardcoded. Not sure why that would be, or why it looks different to how it should.

I also found this: Flutter change dialog background color But I couldn't make any of those answers work in this case. Maybe you can though.

If nothing else works, you'll have to write your own Dialog widget. Good luck!

Body:
I tried implementing the CupertinoAlertDialog (https://api.flutter.dev/flutter/cupertino/CupertinoAlertDialog-class.html) but when I used it, it looked like this:

which is quite different from how it looks when signing in with google or as shown in the image here (https://flutter.dev/docs/development/ui/widgets/cupertino)

Here's the code:

showDialog(
          context: context,
          barrierDismissible: true,
          builder: (_) => _buildAlertDialog());

Widget _buildAlertDialog() {
    return CupertinoAlertDialog(
      title: Text(
        '\"Abc\" Wants to Use \"xyz.com\" to Sign In',
      ),
      content: Text(
        'This allows the app and website to share information about you.',
      ),
      actions: <Widget>[
        CupertinoDialogAction(
          child: Text('Cancel'),
          onPressed: () {
            // Drop the dialog
            Navigator.pop(context);
          },
        ),
        CupertinoDialogAction(
          child: Text('Continue'),
          onPressed: () {
            // Drop the dialog
            Navigator.pop(context);
            // handle continue press

          },
        ),
      ],
    );
  }


问:
Most elegant way to store (persist) the value of a single (numeric) variable
I need to store the value of a counter between executions of a script, so I can trigger a specific subroutine every hundred counts. I know I can write my integer into a text file and re-read it, and I know I can pickle my variable to much the same effect (the script currently uses the latter approach).

The concern I have is to find the approach that makes the code as elegant - simple and easily comprehensible - as possible, particularly to a non-technical audience.

The pickle module name is not helpful in that regard - once you grok the metaphor, it is entirely memorable, but if you don't know it, a comment (or verbal explanation) is required to explain that it is a module for serialising Python objects to disk.

Although 'nice to have', I'm not particularly concerned about the atomicity of the storage operation, nor about strongly protecting the stored value from loss [although I do need it to persist through a server reboot].

My interest is elegance of code to access and update the value of my variable, not the elegance of code to initialise whatever is storing the value (so, if the value were to be stored in a file, I'm interested in the code to read and write to a file that already exists and holds a value, not in creating the file on first execution).

What is the most elegant (and/or most pythonic) way to store a single (numeric) value so it persists between executions of a script?

答:
This is a take on a 'write to a text file' approach:

```<code>with open('counter', 'r') as f:
    value = int(f.read())
# Perform increments to the counter 'value' here
with open('counter', 'w') as f:
    f.write(str(value))
</code>```

The loss of elegance here is the need to cast the variable from and to a str,but it is clear that you are writing and reading from a file on disk.

Body:
This is a take on a 'write to a text file' approach:

with open('counter', 'r') as f:
    value = int(f.read())
# Perform increments to the counter 'value' here
with open('counter', 'w') as f:
    f.write(str(value))

The loss of elegance here is the need to cast the variable from and to a str,but it is clear that you are writing and reading from a file on disk.


问:
Hibernate many-to-many mapping
I am one of hibernate user in Australia. Recently, I have been dealing with hibernate many-to-many mapping and not going well though.
I got in trouble with "join/associate table with extra columns mapping".

Let`s say there are three tables called Product Order and OrderProduct (includes extra column quantity). Product holds many-to-many relationship with Order.

My confusion is that do we have to consider both ends of associate table when we are writing mapping files? or just write either side?
Also, is it necessary to produce mapping file for the associate table as well?

Any suggestions will be appreciated!!

答:
create a view to join two tables. this view and rest table is many to one relationship
Hope it's userful</p>

ContentLicense: CC BY-SA 2.5

Title: Hibernate many-to-many mapping


问:
How do I get the values of my spreadsheet columns
I'm new to apps script and javascript but I managed to get all the defined value numbers or column numbers right except for one that is about 200 columns to the right. But column numbers don't always ad up as it seems like it skips some empty columns sometimes but not others for some reason. Is there a way to number the columns with a script? I found this one which runs successfully but I don't know how to print the result.</p>

```<code>function getValue() {
  var values = SpreadsheetApp.getActiveSheet().getDataRange().getValues()
}
</code>```

答:
```<code>function numberColumns() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const rg=sh.getRange(1,1,1,sh.getMaxColumns());
  var v=rg.getValues()[0].map(function(e,i){return i+1;});
  sh.insertRowBefore(1);//inserts a row first to hold column numbers
  rg.setValues([v]);
}
</code>```

Body:
I'm new to apps script and javascript but I managed to get all the defined value numbers or column numbers right except for one that is about 200 columns to the right. But column numbers don't always ad up as it seems like it skips some empty columns sometimes but not others for some reason. Is there a way to number the columns with a script? I found this one which runs successfully but I don't know how to print the result.

function getValue() {
  var values = SpreadsheetApp.getActiveSheet().getDataRange().getValues()
}