问:
OLS error while loading shared libraries libargon2.so.0
I am a newbie in Openlitespeed and while configuring OpenLiteSpeed to run my wordpress website, I checked the error.log and found out this error:

No request delivery notification has been received from LSAPI application, possible dead lock

and here it is the content of my stderr.log

/usr/local/lsws/lsphp73/bin/lsphp: error while loading shared libraries: libargon2.so.0: cannot open shared object file: No such file or directory

答:
It means your OS/System need libargon2 package but not exist.

For Debian/Ubuntu, please run

```<code>apt-get update -y
apt-get install -y libargon2-0
</code>```

For CentOS, please run

```<code>yum install epel-release
</code>```

Best

Body:
It means your OS/System need libargon2 package but not exist.

For Debian/Ubuntu, please run

apt-get update -y
apt-get install -y libargon2-0

For CentOS, please run

yum install epel-release

Best


来源: stackexchange

问:
Passing a double pointer in a function
I was creating a program with linked lists in C. I created a head variable in main function. Then I passed it by reference to a function insert_at_head(struct node **head).

I have another function for inserting at tail. In a base condition, if my list is empty, I want to call insert_at_head(struct node **head) again. But I am getting confused in passing the actual parameter. Should it be insert_at_head (&(*head)) or insert_at_head (head)?

Personally, I think both are same, because both of them are passing a double pointer. Which one should I use?

答:
Assuming the type of head is struct node **, then you can pass it directly to a function expecting a parameter of that type.

&(*head) is exactly the same as head.  When the operand of the & operator is the result of the unary * operator, they cancel each other out and neither is actually evaluated.

This is spelled out in section 6.5.3.2p3 of the C standard regarding the address-of and indirection operators:

The unary & operator yields the address of its operand. If the
  operand has type ‘‘type’’, the result has type ‘‘pointer to type’’. If
  the operand is the result of a unary * operator, neither that
  operator nor the & operator is evaluated and the result is as if
  both were omitted, except that the constraints on the operators still
  apply and the result is not an lvalue.

So if head is a pointer, the expressions head and &(*head) are equivalent.

ContentLicense: CC BY-SA 4.0

Title: Passing a double pointer in a function


问:
Displaying Date and time in textbox
```<code>Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
    Dim formatdate As Date

    If cboPurpose.Text = "Photocopy" Then
        formatdate = DateAdd(DateInterval.Minute, 30, Now)
        txtdue.Text = Format(formatdate, "yyyy-MM-dd HH:mm:ss")

    ElseIf cboPurpose.Text = "Overnight" Then
        formatdate = DateAdd(DateInterval.Hour, 24, Now)
        txtdue.Text = Format(formatdate, "yyyy-MM-dd HH:mm:ss")
    End If
</code>```

can someone help me with this? what happen is after i click the save button then that is the time when the time and date will show up. what i want is after i select a condition in my combo box it will automatically display the date and time in my textbox not after i click the save button. . thanks admin/s.

答:
Its the event, the event handler should be comboBox's event OnChange or something.

Try changing the event to combobox and then sending the value to the text box.
Why not use DateTimePicker control?? Its easy, useful calendar gadget.

Title: Displaying Date and time in textbox

Body:
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
    Dim formatdate As Date

    If cboPurpose.Text = "Photocopy" Then
        formatdate = DateAdd(DateInterval.Minute, 30, Now)
        txtdue.Text = Format(formatdate, "yyyy-MM-dd HH:mm:ss")

    ElseIf cboPurpose.Text = "Overnight" Then
        formatdate = DateAdd(DateInterval.Hour, 24, Now)
        txtdue.Text = Format(formatdate, "yyyy-MM-dd HH:mm:ss")
    End If

can someone help me with this? what happen is after i click the save button then that is the time when the time and date will show up. what i want is after i select a condition in my combo box it will automatically display the date and time in my textbox not after i click the save button. . thanks admin/s.


问:
SQL to Get Latest Field Value
I'm trying to write an SQL query (SQL Server) that returns the latest value of a field from a history table.

The table structure is basically as below:

ISSUE TABLE:

```<code>issueid
10
20
30
</code>```

CHANGEGROUP TABLE:

```<code>changegroupid | issueid | updated    |
1             | 10      | 01/01/2020 |
2             | 10      | 02/01/2020 |
3             | 10      | 03/01/2020 |
4             | 20      | 05/01/2020 |
5             | 20      | 06/01/2020 |
6             | 20      | 07/01/2020 |
7             | 30      | 04/01/2020 |
8             | 30      | 05/01/2020 |
9             | 30      | 06/01/2020 |
</code>```

CHANGEITEM TABLE:

```<code>changegroupid | field   | newvalue |
1             | ONE     | 1        |
1             | TWO     | A        |
1             | THREE   | Z        |
2             | ONE     | J        |
2             | ONE     | K        |
2             | ONE     | L        |
3             | THREE   | K        |
3             | ONE     | 2        |
3             | ONE     | 1        | <--
4             | ONE     | 1A       |
5             | ONE     | 1B       |
6             | ONE     | 1C       | <--
7             | ONE     | 1D       |
8             | ONE     | 1E       |
9             | ONE     | 1F       | <--
</code>```

EXPECTED RESULT:

```<code>issueid | updated    | newvalue
10      | 03/01/2020 | 1
20      | 07/01/2020 | 1C
30      | 06/01/2020 | 1F
</code>```

So each change to an issue item creates 1 change group record with the date the change was made, which can then contain 1 or more change item records.

Each change item shows the field name that was changed and the new value.

I then need to link those tables together to get each issue, the latest value of the field name called 'ONE', and ideally the date of the latest change.

These tables are from Jira, for those familiar with that table structure.

I've been trying to get this to work for a while now, so far I've got this query:

```<code>SELECT issuenum, MIN(created) AS updated FROM
(
    SELECT ISSUE.IssueId, UpdGrp.Created as Created, UpdItm.NEWVALUE
    FROM ISSUE
        JOIN ChangeGroup UpdGrp ON (UpdGrp.IssueID = CR.ID)
        JOIN CHANGEITEM UpdItm ON (UpdGrp.ID = UpdItm.groupid)
    WHERE   UPPER(UpdItm.FIELD) = UPPER('ONE')

) AS dummy
GROUP BY issuenum
ORDER BY issuenum
</code>```

This returns the first 2 columns I'm looking for but I'm struggling to work out how to return the final column as when I include that in the first line I get an error saying "Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."

I've done a search on here and can't find anything that exactly matches my requirements.

答:
Use window functions:</p>

```<code>SELECT i.*
FROM (SELECT i.IssueId, cg.Created as Created, ui.NEWVALUE,
             ROW_NUMBER() OVER (PARTITION BY i.IssueId ORDER BY cg.Created DESC) as seqnum
      FROM ISSUE i JOIN
           ChangeGroup cg
           ON cg.IssueID = CR.ID JOIN
           CHANGEITEM ci
           ON cg.ID = ci.groupid
      WHERE UPPER(UpdItm.FIELD) = UPPER('ONE')
    ) i
WHERE seqnum = 1
ORDER BY issueid;
</code>```

Title: SQL to Get Latest Field Value

Body:
I'm trying to write an SQL query (SQL Server) that returns the latest value of a field from a history table.

The table structure is basically as below:

ISSUE TABLE:

issueid
10
20
30

CHANGEGROUP TABLE:

changegroupid | issueid | updated    |
1             | 10      | 01/01/2020 |
2             | 10      | 02/01/2020 |
3             | 10      | 03/01/2020 |
4             | 20      | 05/01/2020 |
5             | 20      | 06/01/2020 |
6             | 20      | 07/01/2020 |
7             | 30      | 04/01/2020 |
8             | 30      | 05/01/2020 |
9             | 30      | 06/01/2020 |

CHANGEITEM TABLE:

changegroupid | field   | newvalue |
1             | ONE     | 1        |
1             | TWO     | A        |
1             | THREE   | Z        |
2             | ONE     | J        |
2             | ONE     | K        |
2             | ONE     | L        |
3             | THREE   | K        |
3             | ONE     | 2        |
3             | ONE     | 1        | <--
4             | ONE     | 1A       |
5             | ONE     | 1B       |
6             | ONE     | 1C       | <--
7             | ONE     | 1D       |
8             | ONE     | 1E       |
9             | ONE     | 1F       | <--

EXPECTED RESULT:

issueid | updated    | newvalue
10      | 03/01/2020 | 1
20      | 07/01/2020 | 1C
30      | 06/01/2020 | 1F

So each change to an issue item creates 1 change group record with the date the change was made, which can then contain 1 or more change item records.

Each change item shows the field name that was changed and the new value.

I then need to link those tables together to get each issue, the latest value of the field name called 'ONE', and ideally the date of the latest change.

These tables are from Jira, for those familiar with that table structure.

I've been trying to get this to work for a while now, so far I've got this query:

SELECT issuenum, MIN(created) AS updated FROM
(
    SELECT ISSUE.IssueId, UpdGrp.Created as Created, UpdItm.NEWVALUE
    FROM ISSUE
        JOIN ChangeGroup UpdGrp ON (UpdGrp.IssueID = CR.ID)
        JOIN CHANGEITEM UpdItm ON (UpdGrp.ID = UpdItm.groupid)
    WHERE   UPPER(UpdItm.FIELD) = UPPER('ONE')

) AS dummy
GROUP BY issuenum
ORDER BY issuenum

This returns the first 2 columns I'm looking for but I'm struggling to work out how to return the final column as when I include that in the first line I get an error saying "Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."

I've done a search on here and can't find anything that exactly matches my requirements.

Body:
Use window functions:

SELECT i.*
FROM (SELECT i.IssueId, cg.Created as Created, ui.NEWVALUE,
             ROW_NUMBER() OVER (PARTITION BY i.IssueId ORDER BY cg.Created DESC) as seqnum
      FROM ISSUE i JOIN
           ChangeGroup cg
           ON cg.IssueID = CR.ID JOIN
           CHANGEITEM ci
           ON cg.ID = ci.groupid
      WHERE UPPER(UpdItm.FIELD) = UPPER('ONE')
    ) i
WHERE seqnum = 1
ORDER BY issueid;


问:
Subgit --authors-file not mapped, in the git the authors.txt is empty
I use subgit to import a svn repository to a local git.

```<code>$ subgit import --authors-file authors.txt https://foobar.com:8443/svn/project/ gitproject.git
</code>```

Unfortunately, the users apper in my gitlab as:

```<code>svnuser@localhost
</code>```

I noticed that the authors.txt in the gitproject.git is only an empty file with the introductory header.

Even though in the log-file there is a correct authors.txt (copied full path and opened in explorer):

```<code>authorsFile = C:/foo/bar/authors.txt
</code>```

I tried several ways to set username = foo bar <user.name@foo.bar>like it is written in the git-users-mapping but no change. If the wrong format is used, will the real authors.txt be empty?

How can I make subgit take my authors.txt file?

答:
A possible workaround is to use import with preliminary configuration. For this, first run the 'configure' command:

```<code>subgit configure --svn-url https://foobar.com:8443/svn/project gitproject.git
</code>```

then edit gitproject.git/subgit/authors.txt and fulfill it with actual users mapping. After that run the import:

```<code>subgit import gitproject.git
</code>```

This file would definitely work.

Body:
I use subgit to import a svn repository to a local git.

$ subgit import --authors-file authors.txt https://foobar.com:8443/svn/project/ gitproject.git

Unfortunately, the users apper in my gitlab as:

svnuser@localhost

I noticed that the authors.txt in the gitproject.git is only an empty file with the introductory header.

Even though in the log-file there is a correct authors.txt (copied full path and opened in explorer):

authorsFile = C:/foo/bar/authors.txt

I tried several ways to set username = foo bar <user.name@foo.bar>like it is written in the git-users-mapping but no change. If the wrong format is used, will the real authors.txt be empty?

How can I make subgit take my authors.txt file?

Body:
A possible workaround is to use import with preliminary configuration. For this, first run the 'configure' command:

subgit configure --svn-url https://foobar.com:8443/svn/project gitproject.git

then edit gitproject.git/subgit/authors.txt and fulfill it with actual users mapping. After that run the import:

subgit import gitproject.git

This file would definitely work.


问:
drop down country selection for phone country code in rails
Rails noob here posing a question.

I'm trying to get users to input their phone number. Form contains separate fields for countrycode, areacode and phonenumber at the moment.

```<code><% form_tag phones_path, :method => 'get' do %>
<th><%= text_field_tag :countrycode %></th>
<th><%= text_field_tag :areacode %></th>
<th><%= text_field_tag :search, params[:search] %></th>
<th><%= submit_tag "Search", :name => nil %></th>
<% end %>
</code>```

I want to convert the countrycode field into a dropdown selection of country names, and automatically display the actual country code upon selection. Eg user selections USA, and +1 is displayed. I am going to store both the country name and the numerical code.

I think I need to use a combination of collection_select for the dropdown and javascript to refresh the display. But I'm kinda lost as to how to proceed. Will any kind soul give some hints please?

答:
You can also do this:

```<code><%= f.collection_select(:subject_heading_source_id, SubjectHeadingSource.all, :id, :name, :prompt => "Please select...") %>
</code>```

This is dependent upon having the contents of the select represented in a table somewhere and using the "form_for" approach to building your form, so it may not be entirely applicable.

EDIT: accidental-submit, sorry.

I use jQuery to find the element and update it:

```<code>$("#phones_path_country_code").attr("selected", value_of_selection)
</code>```

you put this part into :onchange => "..." in the html options for the erb bit.

My jQuery is likely off but you can get a better idea at the api site. jQuery

ContentLicense: CC BY-SA 3.0

Body:
Rails noob here posing a question.

I'm trying to get users to input their phone number. Form contains separate fields for countrycode, areacode and phonenumber at the moment.

<% form_tag phones_path, :method => 'get' do %>
<%= text_field_tag :countrycode %>
<%= text_field_tag :areacode %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
<% end %>

I want to convert the countrycode field into a dropdown selection of country names, and automatically display the actual country code upon selection. Eg user selections USA, and +1 is displayed. I am going to store both the country name and the numerical code.

I think I need to use a combination of collection_select for the dropdown and javascript to refresh the display. But I'm kinda lost as to how to proceed. Will any kind soul give some hints please?

Body:
You can also do this:

<%= f.collection_select(:subject_heading_source_id, SubjectHeadingSource.all, :id, :name, :prompt => "Please select...") %>

This is dependent upon having the contents of the select represented in a table somewhere and using the "form_for" approach to building your form, so it may not be entirely applicable.

EDIT: accidental-submit, sorry.

I use jQuery to find the element and update it:

$("#phones_path_country_code").attr("selected", value_of_selection)

you put this part into :onchange => "..." in the html options for the erb bit.

My jQuery is likely off but you can get a better idea at the api site. jQuery


问:
Set a Single Select control as required in Google Data Studio
I have a filter control with style "Single Select". This filter has two options: "New Users" and "All Users", by default its value is "All Users".

Now I need to force one of the options is always selected. Is there a way to achieve this? It's something like set this control as "required".

答:
Added a GIF to elaborate on the below.

Default Selection: Are you looking to have a default value? that could be achieved by adding the required value into the "Default Selection" section in the Data Tab of the Filter Control.

"I need to force one of the options is always selected"

Fixed Value: If you are looking to always include a certain value, then the regular Multi select Filter Control would be required.  One way to ensure that viewers can't deselect a value from a Filter Control is to use a Fixed Size Filter Control (sorted by Dimension in the required order) and add a transparent shape over the respective area checkbox area of the Filter Control (as well as the deselect all checkbox at the top of the Filter Control.


问:
Execute Python files from a main file and stop running when an assertion fails in any of the files
I want to run several Python files from a main file.
I am doing it using the following custom function in my_module:

```<code>import os

def run(file):
    os.system(f"python3 -m folder.subfolder.{file}")
</code>```

In the main file I have:

```<code>from folder.my_module import run

run("first_file")
run("second_file")
</code>```

Inside first_file and second_file I have written several assertions.
The second_file must not run unless all the assertions have run without raising an error in the first_file.

In general, I would like the whole program to stop running when an error occurs in any of the files.

I have tried:

```<code>assert run("first_file"), "Error in file 1"
assert run("second_file"), "Error in file 2"
</code>```

But the program stops working always after the first file has run, regardless of an exception occurring or not.

I have also tried:

```<code>try:
    run("first_file")
except:
    raise

try:
    run("second_file")
except:
    raise
</code>```

But this does not have any effect: The second_file runs even if there was an assertion failing in first_file.

答:
The assertion will always fail here because run returns None, which in turn evaluates to False.

A simple fix:

def run(file):
    os.system(f"python3 -m folder.subfolder.{file}")
    return True
```

<p><em>EDIT</em></p>

<p>I had to double check the <code>os</code> module. <code>os.system</code> will return the exit code of the program you're running so you should actually be comparing that to <code>0</code> (normal non error exit status) like so:</p>

<pre class="lang-py prettyprint-override"><code>def run(file):
    return 0 == os.system(f"python3 -m folder.subfolder.{file}")
</code>```

Body:
I want to run several Python files from a main file.
I am doing it using the following custom function in my_module:

import os

def run(file):
    os.system(f"python3 -m folder.subfolder.{file}")

In the main file I have:

from folder.my_module import run

run("first_file")
run("second_file")

Inside first_file and second_file I have written several assertions.
The second_file must not run unless all the assertions have run without raising an error in the first_file.

In general, I would like the whole program to stop running when an error occurs in any of the files.

I have tried:

assert run("first_file"), "Error in file 1"
assert run("second_file"), "Error in file 2"

But the program stops working always after the first file has run, regardless of an exception occurring or not.

I have also tried:

try:
    run("first_file")
except:
    raise

try:
    run("second_file")
except:
    raise

But this does not have any effect: The second_file runs even if there was an assertion failing in first_file.

Body:
The assertion will always fail here because run returns None, which in turn evaluates to False.

A simple fix:

def run(file):
    os.system(f"python3 -m folder.subfolder.{file}")
    return True

EDIT

I had to double check the os module. os.system will return the exit code of the program you're running so you should actually be comparing that to 0 (normal non error exit status) like so:

def run(file):
    return 0 == os.system(f"python3 -m folder.subfolder.{file}")


问:
Scroll View inside view not working react native
Here I am trying a simple code but the scroll view is not working if kept inside another view. Code is like this:

```<code>  return(
  <View>
    <Toolbar title={this.props.title}>
    </Toolbar>

    <ScrollView>

      <HomeScreenTop />
      <HomeScreenBottom navigator={navigator}/>

      </ScrollView>

  </View>
 );
</code>```

But if scroll view kept as parent view it works perfectly. Code is as below:

```<code>  return(
  <ScrollView>
    <Toolbar title={this.props.title}>
    </Toolbar>

      <HomeScreenTop />
      <HomeScreenBottom navigator={navigator}/>

  </ScrollView>
 );
</code>```

Now the problem is I don't want my toolbar to scroll up and down, I just want the contents below the toolbar to move. How can I achieve that?

And next question: Is scroll view has to be parent view to be returned to work?

答:
Update 2020-02: It will work with React.Fragment <> and </> or <React.Fragment> and </React.Fragment>. So Try this.

```<code>return(
  <>
    <Toolbar title={this.props.title}>
    </Toolbar>

    <ScrollView>

      <HomeScreenTop />
      <HomeScreenBottom navigator={navigator}/>

    </ScrollView>

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

Body:
Here I am trying a simple code but the scroll view is not working if kept inside another view. Code is like this:

  return(
  <View>
    <Toolbar title={this.props.title}>
    </Toolbar>

    <ScrollView>

      <HomeScreenTop />
      <HomeScreenBottom navigator={navigator}/>

      </ScrollView>

  </View>
 );

But if scroll view kept as parent view it works perfectly. Code is as below:

  return(
  <ScrollView>
    <Toolbar title={this.props.title}>
    </Toolbar>

      <HomeScreenTop />
      <HomeScreenBottom navigator={navigator}/>

  </ScrollView>
 );

Now the problem is I don't want my toolbar to scroll up and down, I just want the contents below the toolbar to move. How can I achieve that?

And next question: Is scroll view has to be parent view to be returned to work?

Body:
Update 2020-02: It will work with React.Fragment <> and </> or <React.Fragment> and </React.Fragment>. So Try this.

return(
  <>
    <Toolbar title={this.props.title}>
    </Toolbar>

    <ScrollView>

      <HomeScreenTop />
      <HomeScreenBottom navigator={navigator}/>

    </ScrollView>

  </>
 );


问:
Define the selected option in a select after loading
I have the following scenario:

variable timezones

```<code>["Africa/Abidjan", "Africa/Accra", "Africa/Algiers", "Africa/Bissau", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/El_Aaiun", "Africa/Johannesburg", "Africa/Juba", "Africa/Khartoum", "Africa/Lagos", "Africa/Maputo", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Araguaina", "America/Argentina/Buenos_Aires", ....... ]
</code>```

(shortened version)

component.html

```<code><select>
    <option value="0">GMT/UTC</option>
    <option *ngFor="let tz of timezones" [value]="tz">{{tz}}</option>
</select>
</code>```

compontent.ts

```<code>const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone;
</code>```

In my case, tzid is Europe/Berlin. How can I define this value as my selected option?

答:
As you are using template driven forms, the first step is to define a variable to hold the value in ts file, for example, selectedTimezone and initialize it to the correct value :

```<code>selectedTimezone = 'Africa/Tripoli';
</code>```

Then, in the template, use [(ngModel)] on the <select> tag :

```<code><select [(ngModel)]="selectedTimezone">
  <option *ngFor="let tz of timezones" [value]="tz">{{tz}}</option>
</select>
</code>```

Here is a stackblitz showing how it works with both template driven forms and reactive forms.

Body:
I have the following scenario:

variable timezones

["Africa/Abidjan", "Africa/Accra", "Africa/Algiers", "Africa/Bissau", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/El_Aaiun", "Africa/Johannesburg", "Africa/Juba", "Africa/Khartoum", "Africa/Lagos", "Africa/Maputo", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Araguaina", "America/Argentina/Buenos_Aires", ....... ]

(shortened version)

component.html

<select>
    <option value="0">GMT/UTC</option>
    <option *ngFor="let tz of timezones" [value]="tz">{{tz}}</option>
</select>

compontent.ts

const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone;

In my case, tzid is Europe/Berlin. How can I define this value as my selected option?

Body:
As you are using template driven forms, the first step is to define a variable to hold the value in ts file, for example, selectedTimezone and initialize it to the correct value :

selectedTimezone = 'Africa/Tripoli';

Then, in the template, use [(ngModel)] on the <select> tag :

<select [(ngModel)]="selectedTimezone">
  <option *ngFor="let tz of timezones" [value]="tz">{{tz}}</option>
</select>

Here is a stackblitz showing how it works with both template driven forms and reactive forms.


问:
Calculate multiple columns based on threshold
data

```<code>data=data.frame("student"=c(1,2,3,4,5),
"score1"=c(77,NA,52,99,89),
"score2"=c(95,89,79,89,73),
"score3"=c(92,52,73,64,90),
"score4"=c(84,57,78,81,66),
"score1x"=c(0,NA,0,1,1),
"score2x"=c(1,1,0,1,0),
"score3x"=c(1,0,0,0,1),
"score4x"=c(1,0,0,1,0))
</code>```

I have data with student id and score1-score4 and hope to create score1x-score4x in a simple fast way. The rule is if say score1 is less than 80 then score1x is 0 otherwise it is 1.
I can do this by: data$score1x=ifelse(score1<80,0,1) but am wondering is there a way to do this for all of them at the same time to create score1x-score4x more quickly?

Body:
data

data=data.frame("student"=c(1,2,3,4,5),
"score1"=c(77,NA,52,99,89),
"score2"=c(95,89,79,89,73),
"score3"=c(92,52,73,64,90),
"score4"=c(84,57,78,81,66),
"score1x"=c(0,NA,0,1,1),
"score2x"=c(1,1,0,1,0),
"score3x"=c(1,0,0,0,1),
"score4x"=c(1,0,0,1,0))

I have data with student id and score1-score4 and hope to create score1x-score4x in a simple fast way. The rule is if say score1 is less than 80 then score1x is 0 otherwise it is 1.
I can do this by: data$score1x=ifelse(score1<80,0,1) but am wondering is there a way to do this for all of them at the same time to create score1x-score4x more quickly?

Body:
Try:

cbind(data, (data[, 1:4] < 80) * 1)


问:
Permission issue on vsdbg while running docker.exe - exec: \"/app/vsdbg\: permission denied
My object is to debug the Docker container using vsdbg. This container contains an ASP.NET Core API application.

To do this, I created a Docker image using a Docker file, and then ran the container.

And to start remote debugging, I used the below command:

```<code>docker exec -i  a05a0439540b  "/app/vsdbg"
</code>```

Then I got the below error message:

OCI runtime exec failed: exec failed: container_linux.go:344: starting
container process caused "exec: "/app/vsdbg": permission denied": unknown

Please find below the Docker file content:

```<code>FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base
WORKDIR /app
EXPOSE 80
#EXPOSE 443

#RUN Invoke-WebRequest -OutFile c:\vs_remotetools.exe -Uri

http://download.microsoft.com/download/1/2/2/1225c23d-3599-48c9-a314-f7d631f43241/vs_remotetools.exe;
#RUN &amp; 'c:\rtools_setup_x64.exe' /install /quiet
#RUN  & 'c:\vs_remotetools.exe' /install /quiet

EXPOSE 4024
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
    unzip \
    && curl -sSL https://aka.ms/getvsdbgsh | bash /dev/stdin -v latest -l ./vsdbg \
    && rm -rf /var/lib/apt/lists/*

#RUN chmod 700 -R /app/vsdbg

RUN /bin/bash -c 'ls -la; chmod 777 /app/vsdbg; ls -la'

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
WORKDIR /src
COPY ["testDockerCore.csproj", ""]
RUN dotnet restore "testDockerCore.csproj"
COPY . .
WORKDIR "/src/"
RUN dotnet build "testDockerCore.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "testDockerCore.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "testDockerCore.dll"]
</code>```

But I am still facing the same error.

Using the below command to start the Docker image:

```<code>docker run -it -p 4200:4024 testdockercore:dev
</code>```

How can I resolve this problem?

答:
I ran into this same issue today - the error message is a little confusing. There are no execute permissions on the /vsdbg directory; instead of "/app/vsdbg" you're launch.json needs to read:

```<code>"debuggerPath": "/app/vsdbg/vsdbg",
</code>```

Body:
My object is to debug the Docker container using vsdbg. This container contains an ASP.NET Core API application.

To do this, I created a Docker image using a Docker file, and then ran the container.

And to start remote debugging, I used the below command:

docker exec -i  a05a0439540b  "/app/vsdbg"

Then I got the below error message:

OCI runtime exec failed: exec failed: container_linux.go:344: starting
container process caused "exec: "/app/vsdbg": permission denied": unknown

Please find below the Docker file content:

FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base
WORKDIR /app
EXPOSE 80
#EXPOSE 443

#RUN Invoke-WebRequest -OutFile c:\vs_remotetools.exe -Uri

http://download.microsoft.com/download/1/2/2/1225c23d-3599-48c9-a314-f7d631f43241/vs_remotetools.exe;
#RUN &amp;amp; 'c:\rtools_setup_x64.exe' /install /quiet
#RUN  & 'c:\vs_remotetools.exe' /install /quiet

EXPOSE 4024
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
    unzip \
    && curl -sSL https://aka.ms/getvsdbgsh | bash /dev/stdin -v latest -l ./vsdbg \
    && rm -rf /var/lib/apt/lists/*

#RUN chmod 700 -R /app/vsdbg

RUN /bin/bash -c 'ls -la; chmod 777 /app/vsdbg; ls -la'

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
WORKDIR /src
COPY ["testDockerCore.csproj", ""]
RUN dotnet restore "testDockerCore.csproj"
COPY . .
WORKDIR "/src/"
RUN dotnet build "testDockerCore.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "testDockerCore.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "testDockerCore.dll"]

But I am still facing the same error.

Using the below command to start the Docker image:

docker run -it -p 4200:4024 testdockercore:dev

How can I resolve this problem?

Body:
I ran into this same issue today - the error message is a little confusing. There are no execute permissions on the /vsdbg directory; instead of "/app/vsdbg" you're launch.json needs to read:

"debuggerPath": "/app/vsdbg/vsdbg",


问:
How to solve Flutter drawer showing Vertical viewport was given unbounded height
To be mentioned I'm new to both Flutter and Stackoverflow.

In my News reader app I have added a side drawer which pulls the news categories from an API using FutureBuilder. There is a DrawerHeader that contains the category named Popular News which is not fetched from the API, that is static.

Each time I'm opening the API, the Popular News category shows up and works fine but other categories do not show up rather in the console it shows an error like below.

```<code>I/flutter ( 4486): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 4486): The following assertion was thrown during performResize():
I/flutter ( 4486): Vertical viewport was given unbounded height.
I/flutter ( 4486): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter ( 4486): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter ( 4486): typically happens when a scrollable widget is nested inside another scrollable widget.
I/flutter ( 4486): If this widget is always nested in a scrollable widget there is no need to use a viewport because
I/flutter ( 4486): there will always be enough vertical space for the children. In this case, consider using a Column
I/flutter ( 4486): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
I/flutter ( 4486): the height of the viewport to the sum of the heights of its children.
</code>```

My codes are given below

The widget that returns the Drawer

```<code>@override
  Widget build(BuildContext context) {
    SizeConfig().init(context);

    return SizedBox(
      width: SizeConfig.safeBlockHorizontal*50,
      child: Theme(
        data: Theme.of(context).copyWith(canvasColor: const Color(0xFF2b4849)),
        child: Drawer(
          child: ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              DrawerHeader(
                child:  ListTile(
                  title: Text(
                    "Popular News",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 25
                    ),
                  ),
                  onTap: (){
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (BuildContext context) => MostPopularNewsfeed(),
                        )
                    );
                  },
                ),
              ),
          FutureBuilder(
            future: category,
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if(snapshot.data == null) {
                return Container(
                  child: Center(
                    child: Text(
                      "Loading",
                      style: TextStyle(
                          color: Colors.white
                      ),
                    ),
                  ),
                );
              } else {
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                    return _getDrawer(snapshot, index);
                  },
                );
              }
            },
          ),
            ],
          ),
        ),
      ),
    );
  }

</code>```

initState() : This category is a Future<List>

```<code>void initState() {
    super.initState();

    setState(() {
       category = fetchCategory();
    });
  }

</code>```

fetchCategory() : This one fetches the categories from the API.

```<code>Future<List<Category>> fetchCategory() async {
    //try {
    String url = "https://tbsnews.net/json/category/news/list";
    dio.interceptors.add(DioCacheManager(CacheConfig(baseUrl: url)).interceptor);
    Response response = await Dio().get(url);
    print(response);

    List<Category> categoryList = [];
    final Future<Database> dbFuture = categoryDatabaseHelper.initDb();

    if(response.statusCode == 200) {
      var decode = response.data;
      print(decode);
      for (var c in decode) {
        Category category = Category(c['tid'], c['name']);
        await categoryDatabaseHelper.insertCategory(category);
        categoryList.add(category);
      }
      return categoryList;
      //categoryDatabaseHelper.insertCategory(categoryList);
    } else {
      throw Exception("Failed to fetch category");
    }
  }

</code>```

What I have tried so far

I have tried putting the DrawerHeader and FutureBuilder inside an Expanded widget instead of ListView. Did not work.

In the ListView I added shrinkWrap: true, also scrollDirection: Axis.vertical. That was of no use either.

Tried to put them inside a SizeBox and Column widgets also. That did not work either.

The above are what I found by searching the previous questions related to this issue in StackOverflow. Lastly, I'm posting a question myself.

To be noted, when I take away that DrawerHeader everything starts working fine, no trouble then anymore. But this DrawerHeader has to be there.

Thank you very much for your time and sincere help.

答:
If the issue is only with the DrawerHeader try to wrap it with a SizedBox or a ConstrainedBox and give it a certain height and width.
The issue is that the DrawerHeader is not conststrained so the ListView while being built doesn't get to know its dimensions or constraints and throws this error.

This is my educated guess and let me know whether it worked or not.

Body:
To be mentioned I'm new to both Flutter and Stackoverflow.

In my News reader app I have added a side drawer which pulls the news categories from an API using FutureBuilder. There is a DrawerHeader that contains the category named Popular News which is not fetched from the API, that is static.

Each time I'm opening the API, the Popular News category shows up and works fine but other categories do not show up rather in the console it shows an error like below.

I/flutter ( 4486): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 4486): The following assertion was thrown during performResize():
I/flutter ( 4486): Vertical viewport was given unbounded height.
I/flutter ( 4486): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter ( 4486): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter ( 4486): typically happens when a scrollable widget is nested inside another scrollable widget.
I/flutter ( 4486): If this widget is always nested in a scrollable widget there is no need to use a viewport because
I/flutter ( 4486): there will always be enough vertical space for the children. In this case, consider using a Column
I/flutter ( 4486): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
I/flutter ( 4486): the height of the viewport to the sum of the heights of its children.

My codes are given below

The widget that returns the Drawer

@override
  Widget build(BuildContext context) {
    SizeConfig().init(context);

    return SizedBox(
      width: SizeConfig.safeBlockHorizontal*50,
      child: Theme(
        data: Theme.of(context).copyWith(canvasColor: const Color(0xFF2b4849)),
        child: Drawer(
          child: ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              DrawerHeader(
                child:  ListTile(
                  title: Text(
                    "Popular News",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 25
                    ),
                  ),
                  onTap: (){
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (BuildContext context) => MostPopularNewsfeed(),
                        )
                    );
                  },
                ),
              ),
          FutureBuilder(
            future: category,
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if(snapshot.data == null) {
                return Container(
                  child: Center(
                    child: Text(
                      "Loading",
                      style: TextStyle(
                          color: Colors.white
                      ),
                    ),
                  ),
                );
              } else {
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                    return _getDrawer(snapshot, index);
                  },
                );
              }
            },
          ),
            ],
          ),
        ),
      ),
    );
  }

initState() : This category is a Future<List>

void initState() {
    super.initState();

    setState(() {
       category = fetchCategory();
    });
  }

fetchCategory() : This one fetches the categories from the API.

Future<List<Category>> fetchCategory() async {
    //try {
    String url = "https://tbsnews.net/json/category/news/list";
    dio.interceptors.add(DioCacheManager(CacheConfig(baseUrl: url)).interceptor);
    Response response = await Dio().get(url);
    print(response);

    List<Category> categoryList = [];
    final Future<Database> dbFuture = categoryDatabaseHelper.initDb();

    if(response.statusCode == 200) {
      var decode = response.data;
      print(decode);
      for (var c in decode) {
        Category category = Category(c['tid'], c['name']);
        await categoryDatabaseHelper.insertCategory(category);
        categoryList.add(category);
      }
      return categoryList;
      //categoryDatabaseHelper.insertCategory(categoryList);
    } else {
      throw Exception("Failed to fetch category");
    }
  }

What I have tried so far

I have tried putting the DrawerHeader and FutureBuilder inside an Expanded widget instead of ListView. Did not work.

In the ListView I added shrinkWrap: true, also scrollDirection: Axis.vertical. That was of no use either.

Tried to put them inside a SizeBox and Column widgets also. That did not work either.

The above are what I found by searching the previous questions related to this issue in StackOverflow. Lastly, I'm posting a question myself.

To be noted, when I take away that DrawerHeader everything starts working fine, no trouble then anymore. But this DrawerHeader has to be there.

Thank you very much for your time and sincere help.


问:
Jupyter notebook: need to run a cell even though close the tab
My notebook is located on a server, which means that the kernel will still run even though I close the notebook tab. I was thus wondering if it was possible to let the cell running by itself while closing the window? As the notebook is located on a server the kernel will not stop running...

I tried to read previous questions but could not find an answer. Any idea on how to proceed?
Thanks!

答: You can make open a new file and write outputs to it. I think that's the best that you can do.</p>


问:
how to Create and Use SnackBar for ReUse(Globally) in Flutter
i want create SnackBar for reusable(globally)

i already created but its only for 1 page , i don't know how to create reusable.

below code:

```<code>import 'package:flutter/material.dart';

class SnackBarMain extends StatefulWidget {
  @override
  _SnackBarMainState createState() => _SnackBarMainState();
}

class _SnackBarMainState extends State<SnackBarMain> {
  final globalKey = GlobalKey<ScaffoldState>();
  String title = 'SnackBar';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: globalKey,
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        centerTitle: true,
        title: Text(title),
      ),
      body: Center(
        child: RaisedButton(
          shape: new RoundedRectangleBorder(
              borderRadius: new BorderRadius.circular(18.0),
              side: BorderSide(color: Colors.purple)),
          onPressed: () => snackBarMsg(context),
          color: Colors.purple,
          textColor: Colors.white,
          child: Text("SnackBar",
              style: TextStyle(fontSize: 18)),
        ),
      ),
    );
  }

snackBarMsg(BuildContext context) {
    final sb = SnackBar(
      elevation: 0.0,
      //behavior: SnackBarBehavior.floating,
      content: Text('SnackBar Bottom Message'),
      duration: new Duration(seconds: 5000000),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)),
      ),
      //backgroundColor: Colors.redAccent,
      action: SnackBarAction(
        textColor: Color(0xFFFAF2FB),
        label: 'OK',
        onPressed: () {},
      ),
    );
    globalKey.currentState.showSnackBar(sb);
  }
}
</code>```

so any one please give me example for this

答:
Just create a public class and put your custom functions inside, here you go for example:</p>

```<code>//Custom class in project directory
class CustomWidgets {
 CustomWidgets._();
 static buildErrorSnackbar(BuildContext context, String message) {
  Scaffold.of(context)
     .showSnackBar(
    SnackBar(
      content: Text("$message"),
    ),
  );
 }
}

 // This is any page in your project

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
     backgroundColor: Colors.white,
      //        Always create body with Builder method so you can
      //        get exact context to pass
      body: Builder(
      builder: (context) =>
          Center(
              child: RaisedButton(
              color: Colors.pink,
              textColor: Colors.white,
              onPressed: (){
                CustomWidgets.buildErrorSnackbar(context,"Your message here");
              },
              child: Text('Display SnackBar'),
          ),
         ),
     ),
  );
 }
}
</code>```

Body:
i want create SnackBar for reusable(globally)

i already created but its only for 1 page , i don't know how to create reusable.

below code:

import 'package:flutter/material.dart';

class SnackBarMain extends StatefulWidget {
  @override
  _SnackBarMainState createState() => _SnackBarMainState();
}

class _SnackBarMainState extends State<SnackBarMain> {
  final globalKey = GlobalKey<ScaffoldState>();
  String title = 'SnackBar';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: globalKey,
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        centerTitle: true,
        title: Text(title),
      ),
      body: Center(
        child: RaisedButton(
          shape: new RoundedRectangleBorder(
              borderRadius: new BorderRadius.circular(18.0),
              side: BorderSide(color: Colors.purple)),
          onPressed: () => snackBarMsg(context),
          color: Colors.purple,
          textColor: Colors.white,
          child: Text("SnackBar",
              style: TextStyle(fontSize: 18)),
        ),
      ),
    );
  }

snackBarMsg(BuildContext context) {
    final sb = SnackBar(
      elevation: 0.0,
      //behavior: SnackBarBehavior.floating,
      content: Text('SnackBar Bottom Message'),
      duration: new Duration(seconds: 5000000),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)),
      ),
      //backgroundColor: Colors.redAccent,
      action: SnackBarAction(
        textColor: Color(0xFFFAF2FB),
        label: 'OK',
        onPressed: () {},
      ),
    );
    globalKey.currentState.showSnackBar(sb);
  }
}

so any one please give me example for this

Body:
Just create a public class and put your custom functions inside, here you go for example:

//Custom class in project directory
class CustomWidgets {
 CustomWidgets._();
 static buildErrorSnackbar(BuildContext context, String message) {
  Scaffold.of(context)
     .showSnackBar(
    SnackBar(
      content: Text("$message"),
    ),
  );
 }
}

 // This is any page in your project

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
     backgroundColor: Colors.white,
      //        Always create body with Builder method so you can
      //        get exact context to pass
      body: Builder(
      builder: (context) =>
          Center(
              child: RaisedButton(
              color: Colors.pink,
              textColor: Colors.white,
              onPressed: (){
                CustomWidgets.buildErrorSnackbar(context,"Your message here");
              },
              child: Text('Display SnackBar'),
          ),
         ),
     ),
  );
 }
}


问:
how to build Slick-carousel
I'm trying to build a fork of slick-carousel by Ken Wheeler.

The project is quite old and that implies it has a different build setup than most projects we can see lately.

Files relevant for the build (you can look for more on the Github linked above)

Makefile:

```<code>build: components slick.js slick.css
    @component build --dev

components: component.json
    @component install --dev

.PHONY: clean
</code>```

component.json:

```<code>{
    "name": "slick",
    "repo": "kenwheeler/slick",
    "description": "the last carousel you'll ever need",
    "version": "1.8.1",
    "keywords": ["ui", "jquery", "carousel", "responsive", "slider"],
    "dependencies": {
        "component/jquery": "*"
    },
    "development": {},
    "scripts": {
        "slick/slick.js": "slick.js"
    },
    "styles": {
        "slick/slick.css": "slick.css",
        "slick/slick-theme.css": "slick-theme.css"
    }
}
</code>```

So far I was able to figure out I needed the componentjs build tool.

Note: current version is 1.x but slick's component.json syntax only works with version 0.x.

```<code>npm install -g component@0
</code>```

Then I try to run make to build:

I get an output in the /components directory

Then I get an error:

make: *** No rule to make target `slick.js', needed by `build'.  Stop.

I'm not sure what that means, I've read I could have a make version incompatible with the one used to build the lib originally; but I don't see any meta that could help me find a proper make version to use.

Can someone help ?

答:
Make sure that slick.js is in the same directory. Note also that Slick.js is not equal to slick.js(case sensitive).

Also, I found this thread on trying to build a fork with a similar error. Although it is about a different project, it may help. Have a look: https://github.com/kubernetes/kubernetes/issues/28987

Here is an another piece of information that might help:

You can't run make config just anywhere - You have to be in a directory which >contains a Make file. To verify:

```<code>ls Makefile
</code>```

This file has to contain a target called config:

```<code>grep ^config Makefile
</code>```

(this last command will not match all possible Makefile syntax, but if it's a >simple file it should at least show you if there is another target like >configure or configuration.)

(You should look at the original post at this adress:https://unix.stackexchange.com/questions/103080/how-do-i-fix-make-no-rule-to-make-target-config)

Title: how to build Slick-carousel

Body:
I'm trying to build a fork of slick-carousel by Ken Wheeler.

The project is quite old and that implies it has a different build setup than most projects we can see lately.

Files relevant for the build (you can look for more on the Github linked above)

Makefile:

build: components slick.js slick.css
    @component build --dev

components: component.json
    @component install --dev

.PHONY: clean

component.json:

{
    "name": "slick",
    "repo": "kenwheeler/slick",
    "description": "the last carousel you'll ever need",
    "version": "1.8.1",
    "keywords": ["ui", "jquery", "carousel", "responsive", "slider"],
    "dependencies": {
        "component/jquery": "*"
    },
    "development": {},
    "scripts": {
        "slick/slick.js": "slick.js"
    },
    "styles": {
        "slick/slick.css": "slick.css",
        "slick/slick-theme.css": "slick-theme.css"
    }
}

So far I was able to figure out I needed the componentjs build tool.

Note: current version is 1.x but slick's component.json syntax only works with version 0.x.

npm install -g component@0

Then I try to run make to build:

I get an output in the /components directory

Then I get an error:

make: *** No rule to make target `slick.js', needed by `build'.  Stop.

I'm not sure what that means, I've read I could have a make version incompatible with the one used to build the lib originally; but I don't see any meta that could help me find a proper make version to use.

Can someone help ?

Body:
Make sure that slick.js is in the same directory. Note also that Slick.js is not equal to slick.js(case sensitive).

Also, I found this thread on trying to build a fork with a similar error. Although it is about a different project, it may help. Have a look: https://github.com/kubernetes/kubernetes/issues/28987

Here is an another piece of information that might help:

You can't run make config just anywhere - You have to be in a directory which >contains a Make file. To verify:

ls Makefile

This file has to contain a target called config:

grep ^config Makefile

(this last command will not match all possible Makefile syntax, but if it's a >simple file it should at least show you if there is another target like >configure or configuration.)

(You should look at the original post at this adress:https://unix.stackexchange.com/questions/103080/how-do-i-fix-make-no-rule-to-make-target-config)


问:
How can we create an anonymous object from json string in c#?
My JSON string will be like

when I deserialize it using Newtonsoft.Json, instead of object I am getting below response

But it should be like below image

tried JsonConvert.DeserializeObject and  JObject.Parse. is there any way to get in direct object structure when we deserialize it without knowing type?

答:
Try a dynamic? e.g.</p>

```<code>dynamic thing = JObject.Parse("{Id:123, PhoneNumber: { Primary: 12345, Secondary: 78945}");

Console.WriteLine(thing.Id);
Console.WriteLine(thing.PhoneNumber);
Console.WriteLine(thing.PhoneNumber.Primary);
</code>```

Body:
Try a dynamic? e.g.

dynamic thing = JObject.Parse("{Id:123, PhoneNumber: { Primary: 12345, Secondary: 78945}");

Console.WriteLine(thing.Id);
Console.WriteLine(thing.PhoneNumber);
Console.WriteLine(thing.PhoneNumber.Primary);


问:
Is Java using pointer to access Array by index?
I am curious. is java using Pointer like C or C++ to access array by index? when use C languange, x[a] can be converted to *(x + a). What about Java languange? its same with c and c++ or it just use Sequential search to access the element?</p>

答:
OK, i found an answer from this https://softwareengineering.stackexchange.com/a/105919

In Java, plain pointer arithmetics (referencing and dereferencing) don't exist anymore. However pointers exist. They call them references, but it doesn't change what it is. And array access still is exactly the same thing: Look at the address, add the index and use that memory location. However in Java, it will check whether or not that index is within the bounds of the array you originally allocated. If not, it will throw an exception.


问:
Push a div to the right
I'm coding a menu in french but I need to move all the buttons (Home, About us...) to the right.

I tried with float: right; but it doesn't work.

Here is my Result :

My Result

The  Home, Informations, etc.. are in a div. It's this div that i want to push right !

My Objective :

My Objective

My Code:

/*

            ==============================
            NAVBAR
            ==============================

            */

.container {
  width: 80%;
  margin: 0 auto;
}

header {
  background: #9ebd11/*55d6aa*/
  ;
}

header::after {
  content: '';
  display: table;
  clear: both;
}

.logo {
  float: left;
  /*padding: 10px 0;*/
}

nav {
  float: right;
}

nav #navbar-ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

nav .navbar-li {
  display: inline-block;
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav .navbar-button {
  color: #444;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav .navbar-button:hover {
  color: #000;
}

nav .navbar-button::before {
  content: '';
  display: block;
  height: 5px;
  background-color: #444;
  position: absolute;
  top: 0;
  width: 0%;
  transition: all ease-in-out 250ms;
}

nav .navbar-button:hover::before {
  width: 100%;
}

nav #register-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #register-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav #login-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #login-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

ul {
  list-style-type: none;
}

nav,
.container {
  display: flex;
}

.connection {
  line-height: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="container">

    <h1 class="logo">
      <img src="images/Logo/logo_gp_.png" width="100" alt="Description de l'image">
    </h1>

    <nav>
      <ul id="navbar-ul">
        <li class="navbar-li">Home</li>
        <li class="navbar-li">Informations</li>
        <li class="navbar-li">About us</li>
      </ul>
      <ul class="connection">
        <li>S'inscrire</li>
        <li>Se connecter</li>
      </ul>
    </nav>
  </div>
</header></code>```

Thanks

答:
Try changing your nav class from:

```<code>nav{
  floaf: right;
}
</code>```

to:

```<code>nav{
  position: absolute;
  right: 20px;
  top: 0px;
}
</code>```

This should force your nav element to position it's right 20px left of the parent elements right. Tested in chrome.

Title: Push a div to the right

Body:
I'm coding a menu in french but I need to move all the buttons (Home, About us...) to the right.

I tried with float: right; but it doesn't work.

Here is my Result :

My Result

The  Home, Informations, etc.. are in a div. It's this div that i want to push right !

My Objective :

My Objective

My Code:

/*

            ==============================
            NAVBAR
            ==============================

            */

.container {
  width: 80%;
  margin: 0 auto;
}

header {
  background: #9ebd11/*55d6aa*/
  ;
}

header::after {
  content: '';
  display: table;
  clear: both;
}

.logo {
  float: left;
  /*padding: 10px 0;*/
}

nav {
  float: right;
}

nav #navbar-ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

nav .navbar-li {
  display: inline-block;
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav .navbar-button {
  color: #444;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav .navbar-button:hover {
  color: #000;
}

nav .navbar-button::before {
  content: '';
  display: block;
  height: 5px;
  background-color: #444;
  position: absolute;
  top: 0;
  width: 0%;
  transition: all ease-in-out 250ms;
}

nav .navbar-button:hover::before {
  width: 100%;
}

nav #register-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #register-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav #login-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #login-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

ul {
  list-style-type: none;
}

nav,
.container {
  display: flex;
}

.connection {
  line-height: 2;
}

Home

Informations

About us

S'inscrire

Se connecter

Thanks

Body:
Try changing your nav class from:

nav{
  floaf: right;
}

to:

nav{
  position: absolute;
  right: 20px;
  top: 0px;
}

This should force your nav element to position it's right 20px left of the parent elements right. Tested in chrome.


问:
How to insert one query result to another query as an input
When I try to run a query I am getting 500 Internal Error. I want to insert query2 result to query as a data.

Query:

```<code>exports.create = async (req, res) => {
  try {
  const connection = await mysql.createConnection(config.mysql.credentials);
  var query2='select MAX(orders) from pdb_product';
  const query = `insert into pdb_product (product_code, description, active, third_party,
  orders) values ("${req.body.product_code}", "${req.body.description}", ${(req.body.active == 'on' ? 1 : 0)}, ${(req.body.third_party == 'on' ? 1 : 0)}, ${query2});`;
  await connection.query(query);
  res.redirect('/products');
  } catch (e) {
    utils.error500(req, res, e.message);
  }
  };
</code>```

The error I am getting:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select MAX(orders) from pdb_product)' at line 1

How can I resolve this?

答:
You are missing a '(' bracket before the query2 parameter:</p>

```<code>const query = `insert into pdb_product (product_code, description, active, third_party,
  orders)
values ("${req.body.product_code}",
    "${req.body.description}",
     ${(req.body.active == 'on' ? 1 : 0)},
     ${(req.body.third_party == 'on' ? 1 : 0)},
     (${query2}));`;
</code>```

Body:
When I try to run a query I am getting 500 Internal Error. I want to insert query2 result to query as a data.

Query:

exports.create = async (req, res) => {
  try {
  const connection = await mysql.createConnection(config.mysql.credentials);
  var query2='select MAX(orders) from pdb_product';
  const query = `insert into pdb_product (product_code, description, active, third_party,
  orders) values ("${req.body.product_code}", "${req.body.description}", ${(req.body.active == 'on' ? 1 : 0)}, ${(req.body.third_party == 'on' ? 1 : 0)}, ${query2});`;
  await connection.query(query);
  res.redirect('/products');
  } catch (e) {
    utils.error500(req, res, e.message);
  }
  };

The error I am getting:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select MAX(orders) from pdb_product)' at line 1

How can I resolve this?

Body:
You are missing a '(' bracket before the query2 parameter:

const query = `insert into pdb_product (product_code, description, active, third_party,
  orders)
values ("${req.body.product_code}",
    "${req.body.description}",
     ${(req.body.active == 'on' ? 1 : 0)},
     ${(req.body.third_party == 'on' ? 1 : 0)},
     (${query2}));`;


问:
read a csv file and and add its all data into vector in c++
For example to add the following CSV data:

I am trying to add CSV file into a 2D array string vector and get the sum of each column. The following program didn't work properly,

```<code>vector<string> read_csv(string filename){

    vector<string> result;
    fstream fin;
    fin.open(filename, ios::in);

    if(!fin.is_open())
        throw std::runtime_error("Could not open file");

    std::string line, colname;
    int val;

    // Read the column names
    if(fin.good())
    {
        std::getline(fin, line);
        std::stringstream ss(line);
        while(std::getline(ss, colname, ',')){
            result.push_back(colname);
            cout << colname << endl;
        }
    }

    while(std::getline(fin, line))
    {
        std::stringstream ss(line);
        int colIdx = 0;
        while(ss >> val){

            if(ss.peek() == ',') ss.ignore();
            colIdx++;
        }
    }
    fin.close();
    return result;
}
</code>```

when I tried to go through the vector, I didn't get a proper result. It showed only the column names.

```<code>for (int i = 0; i < vectorCsv.size(); ++i)
{
        cout << vectorCsv[i] << endl;
}
</code>```

I couldn't find whether the error is in read_csv() function or in the forloop.
Thank you for looking at this problem.

答:
Don't try to create vectors of std::strings, that's probably not very efficient - each string being allocated and de-allocated separately.

Don't read CSV's yourself - you're reinventing the wheel. Use an existing library. Here's a question about finding one at Software Recommendations StackExchange:

Modern C++ CSV reader (and maybe writer) library

Body:
For example to add the following CSV data:

I am trying to add CSV file into a 2D array string vector and get the sum of each column. The following program didn't work properly,

vector<string> read_csv(string filename){

    vector<string> result;
    fstream fin;
    fin.open(filename, ios::in);

    if(!fin.is_open())
        throw std::runtime_error("Could not open file");

    std::string line, colname;
    int val;

    // Read the column names
    if(fin.good())
    {
        std::getline(fin, line);
        std::stringstream ss(line);
        while(std::getline(ss, colname, ',')){
            result.push_back(colname);
            cout << colname << endl;
        }
    }

    while(std::getline(fin, line))
    {
        std::stringstream ss(line);
        int colIdx = 0;
        while(ss >> val){

            if(ss.peek() == ',') ss.ignore();
            colIdx++;
        }
    }
    fin.close();
    return result;
}

when I tried to go through the vector, I didn't get a proper result. It showed only the column names.

for (int i = 0; i < vectorCsv.size(); ++i)
{
        cout << vectorCsv[i] << endl;
}

I couldn't find whether the error is in read_csv() function or in the forloop.
Thank you for looking at this problem.


答:
The os.system(f"python3 -m folder.subfolder.{file}") command will return the exit code of the supplied command. It just so happens that a Python program that ends with an AssertionError will have an exit code of 2 (on linux, may be different elsewhere), although really any non-zero code means error.

You can test this yourself on the command line:

```<code>$ python3 -c "assert True"
$ echo $?
0
$ python3 -c "assert False"
$ echo $?
2
</code>```

Simply check the return value of your os.system() call.

Title: Execute Python files from a main file and stop running when an assertion fails in any of the files

Body:
I want to run several Python files from a main file.
I am doing it using the following custom function in my_module:

import os

def run(file):
    os.system(f"python3 -m folder.subfolder.{file}")

In the main file I have:

from folder.my_module import run

run("first_file")
run("second_file")

Inside first_file and second_file I have written several assertions.
The second_file must not run unless all the assertions have run without raising an error in the first_file.

In general, I would like the whole program to stop running when an error occurs in any of the files.

I have tried:

assert run("first_file"), "Error in file 1"
assert run("second_file"), "Error in file 2"

But the program stops working always after the first file has run, regardless of an exception occurring or not.

I have also tried:

try:
    run("first_file")
except:
    raise

try:
    run("second_file")
except:
    raise

But this does not have any effect: The second_file runs even if there was an assertion failing in first_file.

Body:
The os.system(f"python3 -m folder.subfolder.{file}") command will return the exit code of the supplied command. It just so happens that a Python program that ends with an AssertionError will have an exit code of 2 (on linux, may be different elsewhere), although really any non-zero code means error.

You can test this yourself on the command line:

$ python3 -c "assert True"
$ echo $?
0
$ python3 -c "assert False"
$ echo $?
2

Simply check the return value of your os.system() call.


问:
VBA: Trying to make code that executes a formula down the line to retrieve data from another worksheet
I am trying to write a VBA code that pulls data from another worksheet via an index match array function (because it needs to satisfy two variables). Basically, I have a source worksheet (Worksheet 1) that is populated with data, and then my main worksheet (Worksheet 2) will pull the data given the criteria to make sure the numbers match up correctly.

Below is an example of what I am trying to do.

The formula that I want to replicate down Column G is an index match array function for 2 criteria:

{=INDEX($C$4:$C$7,MATCH(1,(F4=$B$4:$B$7)*(E4=$A$4:$A$7),0))}

Of course there might be a better way to retrieve "Salary" given the 2 criteria ("Country" and "Name") so I am open to those suggestions as well.

EDIT: I wish for this code to be dynamic so that if new rows of data are added, the formula will still replicate down for all rows.

答:
Using array functions slows down your computer and makes you unable to run Excel files at some point.
Using the Dictionary is convenient.</p>

```<code>Sub test()
    Dim wsS As Worksheet
    Dim wsM As Worksheet
    Dim vDB, vResult
    Dim Dic As Object 'Dictionary
    Dim rngResult As Range
    Dim i As Long, s As String

    Set wsS = Sheets("Source")
    Set wsM = Sheets("Main")

    Set Dic = CreateObject("Scripting.Dictionary")

    vDB = wsS.Range("a1").CurrentRegion
    Set rngResult = wsM.Range("a1").CurrentRegion
    vResult = rngResult

    For i = 2 To UBound(vDB, 1)
        s = vDB(i, 1) & "," & vDB(i, 2)
        If Dic.Exists(s) Then
        Else
            Dic.Add s, vDB(i, 3)
        End If
    Next i
    For i = 2 To UBound(vResult, 1)
        s = vResult(i, 1) & "," & vResult(i, 2)
        vResult(i, 3) = Dic.Item(s)
    Next i
    rngResult = vResult
End Sub
</code>```

Body:
Using array functions slows down your computer and makes you unable to run Excel files at some point.
Using the Dictionary is convenient.

Sub test()
    Dim wsS As Worksheet
    Dim wsM As Worksheet
    Dim vDB, vResult
    Dim Dic As Object 'Dictionary
    Dim rngResult As Range
    Dim i As Long, s As String

    Set wsS = Sheets("Source")
    Set wsM = Sheets("Main")

    Set Dic = CreateObject("Scripting.Dictionary")

    vDB = wsS.Range("a1").CurrentRegion
    Set rngResult = wsM.Range("a1").CurrentRegion
    vResult = rngResult

    For i = 2 To UBound(vDB, 1)
        s = vDB(i, 1) & "," & vDB(i, 2)
        If Dic.Exists(s) Then
        Else
            Dic.Add s, vDB(i, 3)
        End If
    Next i
    For i = 2 To UBound(vResult, 1)
        s = vResult(i, 1) & "," & vResult(i, 2)
        vResult(i, 3) = Dic.Item(s)
    Next i
    rngResult = vResult
End Sub


问:
Count pages from word file that is a byte[]
Is there a way to count the pages of a word file that is currently a byte[].
In the Code you can see what i have so far. The formLanguage is an Entity from the Db and FormFile is a byte[] , here i am sure that it is a word.</p>

```<code> FileStream file = File.Create("EditedFile");
                        file.Write(formLanguage.FormFile, 0, formLanguage.FormFile.Length);
                        try
                        {
                            var application = new Application();
                            var document = application.Documents.Open(file);

                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);

                        }
</code>```

答:
You can try as:</p>

```<code>byte[] bytesDoc = byteFromDatabase();
var tempFile = Path.Combine(Path.GetTempPath(), formLanguage.FileName);
//Write to a temp file
File.WriteAllBytes(tempFile , bytesDoc );

var app = new Microsoft.Office.Interop.Word.Application();
Document doc = app.Documents.Open(tempFile);

var pageCount = doc.ComputeStatistics(
                   Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages);

doc.Close();
app.Quit();
</code>```

Body:
Is there a way to count the pages of a word file that is currently a byte[].
In the Code you can see what i have so far. The formLanguage is an Entity from the Db and FormFile is a byte[] , here i am sure that it is a word.

 FileStream file = File.Create("EditedFile");
                        file.Write(formLanguage.FormFile, 0, formLanguage.FormFile.Length);
                        try
                        {
                            var application = new Application();
                            var document = application.Documents.Open(file);

                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);

                        }

Body:
You can try as:

byte[] bytesDoc = byteFromDatabase();
var tempFile = Path.Combine(Path.GetTempPath(), formLanguage.FileName);
//Write to a temp file
File.WriteAllBytes(tempFile , bytesDoc );

var app = new Microsoft.Office.Interop.Word.Application();
Document doc = app.Documents.Open(tempFile);

var pageCount = doc.ComputeStatistics(
                   Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages);

doc.Close();
app.Quit();


问:
SVN "Already Locked Error"
When trying to commit a change to a repository ( where I am the only user ) I get an error

```<code>Path
'/trunk/TemplatesLibrary/constraints/templates/TP145210GB01_PersonWithOrganizationUniversal.cs'
is already locked by user 'admin' in filesystem
'/guest/gam/subversion/cdaapi/db'
</code>```

I am the user 'admin'.

I have tried the following, all without success

running a "clean up" from Tortoise SVN

checking out a new copy

using the "repo browser" to break locks, but no locks are shown ( as per SVN file locked by me, now cannot commit it )

I am completely stuck now as I have a repository now that I can not commit any updates to.

Any ideas how I fix this

More Info, as requested :

SVN Status command yields  ( I have made edits to one file )

```<code>        92       77 admin        TP146228GB01_EncompassingEncounter.cs
        92       83 admin        TP145212GB02_WorkgroupUniversal.cs
        92       83 admin        TP146248GB01_ReferenceURL.cs
        92       85 admin        TP145201GB01_PatientUniversal.cs
        92       83 admin        TP145204GB02_RecipientWorkgroupUniversal.cs
        92       83 admin        TP145202GB01_RecipientPersonUniversal.cs
        92       83 admin        TP145203GB02_RecipientOrganizationUniversal.cs
        92       77 admin        TP145205GB01_PersonUniversal.cs
        92       83 admin        TP145202GB02_RecipientPersonUniversal.cs
        92       83 admin        TP145203GB03_RecipientOrganizationUniversal.cs
        92       85 admin        TP145211GB01_HealthCareFacilityUniversal.cs
        92       85 admin        TP145200GB01_AuthorPersonUniversal.cs
        92       83 admin        TP145207GB01_AuthorDeviceUniversal.cs
    M   92       87 admin        TP146226GB02_Consent.cs
        92       85 admin        TP146229GB01_TextSection.cs
        92       83 admin        TP145204GB03_RecipientWorkgroupUniversal.cs
        92       86 admin        TP145018UK03_CustodianOrganizationUniversal.cs
        92       83 admin        TP145208GB01_AuthorNonNamedPersonUniversal.cs
        92       70 admin        TP145214GB01_DocumentParticipantUniversal.cs
        92       85 admin        TP145007UK03_RelatedEntity.cs
        92       80 admin        TP146224GB02_Atachment.cs
        92       83 admin        TP146227GB02_ServiceEvent.cs
        92       77 admin        TP145210GB01_PersonWithOrganizationUniversal.cs
</code>```

A svn commit then yields

```<code>svn commit --message updates
Sending        TP146226GB02_Consent.cs
Transmitting file data .svn: E195022: Commit failed (details follow):
svn: E195022: File    'D:\BENBUN_CODE\WORK\cdaapi\trunk\TemplatesLibrary\constraints\templates\TP146226GB02_Consent.cs' is locked in another working copy
svn: E170007: No lock on path '/subversion/cdaapi/!svn/wrk/3c75d861-8462-b94e-8729-df54843044f9/trunk/TemplatesLibrary/constraints/templates/TP146226GB02_Consent.cs' (Status 423 on PUT Request)
svn: E175002: Server sent unexpected return value (423 Locked) in response to PUT request for '/subversion/cdaapi/!svn/wrk/3c75d861-8462-b94e-8729-df54843044f9/trunk/TemplatesLibrary/constraints/templates/TP146226GB02_Consent.cs'
</code>```

As requested output of SVN st -u is shown below

```<code>>svn st -u
M               92   TP146226GB02_Consent.cs
Status against revision:     92
</code>```

答:
I had the same problem,
It was solved when I checked the below checkbox

Clean up working copy status

Break write locks

Include externals

SVN Cleanup dialog

Title: SVN "Already Locked Error"

Body:
When trying to commit a change to a repository ( where I am the only user ) I get an error

Path
'/trunk/TemplatesLibrary/constraints/templates/TP145210GB01_PersonWithOrganizationUniversal.cs'
is already locked by user 'admin' in filesystem
'/guest/gam/subversion/cdaapi/db'

I am the user 'admin'.

I have tried the following, all without success

running a "clean up" from Tortoise SVN

checking out a new copy

using the "repo browser" to break locks, but no locks are shown ( as per SVN file locked by me, now cannot commit it )

I am completely stuck now as I have a repository now that I can not commit any updates to.

Any ideas how I fix this

More Info, as requested :

SVN Status command yields  ( I have made edits to one file )

        92       77 admin        TP146228GB01_EncompassingEncounter.cs
        92       83 admin        TP145212GB02_WorkgroupUniversal.cs
        92       83 admin        TP146248GB01_ReferenceURL.cs
        92       85 admin        TP145201GB01_PatientUniversal.cs
        92       83 admin        TP145204GB02_RecipientWorkgroupUniversal.cs
        92       83 admin        TP145202GB01_RecipientPersonUniversal.cs
        92       83 admin        TP145203GB02_RecipientOrganizationUniversal.cs
        92       77 admin        TP145205GB01_PersonUniversal.cs
        92       83 admin        TP145202GB02_RecipientPersonUniversal.cs
        92       83 admin        TP145203GB03_RecipientOrganizationUniversal.cs
        92       85 admin        TP145211GB01_HealthCareFacilityUniversal.cs
        92       85 admin        TP145200GB01_AuthorPersonUniversal.cs
        92       83 admin        TP145207GB01_AuthorDeviceUniversal.cs
    M   92       87 admin        TP146226GB02_Consent.cs
        92       85 admin        TP146229GB01_TextSection.cs
        92       83 admin        TP145204GB03_RecipientWorkgroupUniversal.cs
        92       86 admin        TP145018UK03_CustodianOrganizationUniversal.cs
        92       83 admin        TP145208GB01_AuthorNonNamedPersonUniversal.cs
        92       70 admin        TP145214GB01_DocumentParticipantUniversal.cs
        92       85 admin        TP145007UK03_RelatedEntity.cs
        92       80 admin        TP146224GB02_Atachment.cs
        92       83 admin        TP146227GB02_ServiceEvent.cs
        92       77 admin        TP145210GB01_PersonWithOrganizationUniversal.cs

A svn commit then yields

svn commit --message updates
Sending        TP146226GB02_Consent.cs
Transmitting file data .svn: E195022: Commit failed (details follow):
svn: E195022: File    'D:\BENBUN_CODE\WORK\cdaapi\trunk\TemplatesLibrary\constraints\templates\TP146226GB02_Consent.cs' is locked in another working copy
svn: E170007: No lock on path '/subversion/cdaapi/!svn/wrk/3c75d861-8462-b94e-8729-df54843044f9/trunk/TemplatesLibrary/constraints/templates/TP146226GB02_Consent.cs' (Status 423 on PUT Request)
svn: E175002: Server sent unexpected return value (423 Locked) in response to PUT request for '/subversion/cdaapi/!svn/wrk/3c75d861-8462-b94e-8729-df54843044f9/trunk/TemplatesLibrary/constraints/templates/TP146226GB02_Consent.cs'

As requested output of SVN st -u is shown below

>svn st -u
M               92   TP146226GB02_Consent.cs
Status against revision:     92


问:
Postgres count rows where value transitions from : A -> B -> A
I need to find the count of records where position of a person_id changes from 1 -> 2 -> 1
 The transitions needs to be sorted in ascending order depending on the timestamp

Table Structure

```<code>timestamp  | person_id | position
--------------------------------
2020-01-01 | 5         |  1
2020-01-03 | 4         |  2
2020-02-04 | 7         |  1
2020-02-05 | 5         |  2
2020-02-06 | 7         |  2
2020-02-09 | 5         |  1
</code>```

Here, the output will be 1, since person_id:5 transitions from 1 -> 2 -> 1

select count(*)
from table_name t1
join table_name t2
  on t1.person_id = t2.person_id
 and t1.position = 1
 and t2.position = 2
 and t1.timestamp < t2.timestamp;
```

Using this query I can find transition from 1 -> 2
But I can't figure out how to again search for the transition to 1

答:
You can use aggregation.  Here is one method:

```<code>select person_id
from t
where position in (1, 2)
group by person_id
having string_agg(position::text order by timestamp) like '%1,2,1%';
</code>```

Edit:

The above would not find 1 --> 2 --> 2 --> 1.  For this, use:

```<code>having string_agg(position::text order by timestamp) like '%1%2%1%';
</code>```

EDIT II:

Your query is not correct because it counts transitions, not persons.  But it can easily be extended:

```<code>select count(distinct person_id)
from table_name t1 join
     table_name t2
     on t1.person_id = t2.person_id and
        t1.position = 1 and
        t2.position = 2 and
        t1.timestamp < t2.timestamp and
     table_name t12
     on t12.person_id = t2.person_id and
        t12.position = 1 and
        t2.timestamp < t12.timestamp;
</code>```

Body:
I need to find the count of records where position of a person_id changes from 1 -> 2 -> 1
 The transitions needs to be sorted in ascending order depending on the timestamp

Table Structure

timestamp  | person_id | position
--------------------------------
2020-01-01 | 5         |  1
2020-01-03 | 4         |  2
2020-02-04 | 7         |  1
2020-02-05 | 5         |  2
2020-02-06 | 7         |  2
2020-02-09 | 5         |  1

Here, the output will be 1, since person_id:5 transitions from 1 -> 2 -> 1

select count(*)
from table_name t1
join table_name t2
  on t1.person_id = t2.person_id
 and t1.position = 1
 and t2.position = 2
 and t1.timestamp < t2.timestamp;

Using this query I can find transition from 1 -> 2
But I can't figure out how to again search for the transition to 1

Body:
You can use aggregation.  Here is one method:

select person_id
from t
where position in (1, 2)
group by person_id
having string_agg(position::text order by timestamp) like '%1,2,1%';

Edit:

The above would not find 1 --> 2 --> 2 --> 1.  For this, use:

having string_agg(position::text order by timestamp) like '%1%2%1%';

EDIT II:

Your query is not correct because it counts transitions, not persons.  But it can easily be extended:

select count(distinct person_id)
from table_name t1 join
     table_name t2
     on t1.person_id = t2.person_id and
        t1.position = 1 and
        t2.position = 2 and
        t1.timestamp < t2.timestamp and
     table_name t12
     on t12.person_id = t2.person_id and
        t12.position = 1 and
        t2.timestamp < t12.timestamp;


问:
How to prepare a PHP postgreSQL request with 'LIKE' keyword
i'm using Symfony4 and a postgreSQL database. i'm working on a search system. I would like to check if something match with the string i'm sending with ajax in my database. But the SQL query always returns false. How should i do to make this code works ? Thanks for help :)</p>

```<code> public function search(Request $request) : Response {

        if($ajaxRequest = $request->getContent())
        {
            $requestContent = json_decode($ajaxRequest, true);

            $content = $requestContent["content"];

            $connexionParams = "host=localhost port=5432 dbname=mydb user=myuser password=mypassword";

            $db = pg_connect($connexionParams);

            $sql = pg_prepare($db, 'search_query', "SELECT nom, lon, lat, id FROM site WHERE nom LIKE $1 OR id LIKE $2");

            $result = pg_execute($db, 'search_query', array($content, $content));

            var_dump($content, pg_fetch_row($result), $result);

            $results = array();

            while($row = pg_fetch_row($result)) {
                $results[] = $row;
            }

            if(($results)) {
                return new JsonResponse([
                    'result' => true,
                    'results' => json_encode($results),
                ]);
            } else {
                return new JsonResponse([
                    'result' => false,
                ]);
            }
        }
    }
</code>```

答:
false means failure, not empty zero hits as stated here. Most likely there is an error in your SQL Syntax or connection data. Maybe pg_last_error helps to find the mistake:

if ($result === false) {
 echo pg_last_error($db);
}
```

Body:
i'm using Symfony4 and a postgreSQL database. i'm working on a search system. I would like to check if something match with the string i'm sending with ajax in my database. But the SQL query always returns false. How should i do to make this code works ? Thanks for help :)

 public function search(Request $request) : Response {

        if($ajaxRequest = $request->getContent())
        {
            $requestContent = json_decode($ajaxRequest, true);

            $content = $requestContent["content"];

            $connexionParams = "host=localhost port=5432 dbname=mydb user=myuser password=mypassword";

            $db = pg_connect($connexionParams);

            $sql = pg_prepare($db, 'search_query', "SELECT nom, lon, lat, id FROM site WHERE nom LIKE $1 OR id LIKE $2");

            $result = pg_execute($db, 'search_query', array($content, $content));

            var_dump($content, pg_fetch_row($result), $result);

            $results = array();

            while($row = pg_fetch_row($result)) {
                $results[] = $row;
            }

            if(($results)) {
                return new JsonResponse([
                    'result' => true,
                    'results' => json_encode($results),
                ]);
            } else {
                return new JsonResponse([
                    'result' => false,
                ]);
            }
        }
    }


问:
Browser shows < and > instead of <>
I'm creating a very simple HTML page using the Typewriter JavaScript plugin.

The page essentially should type out the code of an elementary Java program in which each declared variable is one of my contact details.

The problem is that if I write List<String> list = Arrays, the browser doesn't display List<String> list = but instead displays List<String> list =.

How can I fix this?

Here is a snippet from the output in the browser (Chrome)

JavaScript below:

```<code>function setupTypewriter(t) {

var HTML = t.innerHTML;

t.innerHTML = "";

var cursorPosition = 0,
    tag = "",
    writingTag = false,
    tagOpen = false,
    typeSpeed = 10,
    tempTypeSpeed = 0;

var type = function() {

    if (writingTag === true) {
        tag += HTML[cursorPosition];
    }

    if (HTML[cursorPosition] === "<") {
        tempTypeSpeed = 0;

        if (tagOpen) {
            tagOpen = false;
            writingTag = true;
        } else {
            tag = "";
            tagOpen = true;
            writingTag = true;
            tag += HTML[cursorPosition];
        }
    }

    if (!writingTag && tagOpen) {
        tag.innerHTML += HTML[cursorPosition];
    }

    if (!writingTag && !tagOpen) {
        if (HTML[cursorPosition] === " ") {
            tempTypeSpeed = 0;
        }
        else {
            tempTypeSpeed = (Math.random() * typeSpeed) + 30;
        }
        t.innerHTML += HTML[cursorPosition];
    }
    if (writingTag === true && HTML[cursorPosition] === ">") {
        tempTypeSpeed = (Math.random() * typeSpeed) + 30;
        writingTag = false;
        if (tagOpen) {
            var newSpan = document.createElement("span");
            t.appendChild(newSpan);
            newSpan.innerHTML = tag;
            tag = newSpan.firstChild;
        }
    }

    cursorPosition += 1;
    if (cursorPosition < HTML.length - 1) {
        setTimeout(type, tempTypeSpeed);
    }

  };

  return {
    type: type
  };
}

var typer = document.getElementById('typewriter');

typewriter = setupTypewriter(typewriter);

typewriter.type();
</code>```

答:
The below code works fine for me.

```<code><span class="standard-highight" id="app"></span>

    <script>
    var app = document.getElementById('app');
    var typewriter = new Typewriter(app, {
        loop: true
});
    typewriter.typeString('<span>List<String> list = Arrays</span>').start();
    </script>
</code>```

Place the string passing to the typeString() function within any html tag and only then the HTML symbols will be rendered by the function.

Title: Browser shows < and > instead of <>

Body:
I'm creating a very simple HTML page using the Typewriter JavaScript plugin.

The page essentially should type out the code of an elementary Java program in which each declared variable is one of my contact details.

The problem is that if I write List<String> list = Arrays, the browser doesn't display List<String> list = but instead displays List<String> list =.

How can I fix this?

Here is a snippet from the output in the browser (Chrome)

JavaScript below:

function setupTypewriter(t) {

var HTML = t.innerHTML;

t.innerHTML = "";

var cursorPosition = 0,
    tag = "",
    writingTag = false,
    tagOpen = false,
    typeSpeed = 10,
    tempTypeSpeed = 0;

var type = function() {

    if (writingTag === true) {
        tag += HTML[cursorPosition];
    }

    if (HTML[cursorPosition] === "<") {
        tempTypeSpeed = 0;

        if (tagOpen) {
            tagOpen = false;
            writingTag = true;
        } else {
            tag = "";
            tagOpen = true;
            writingTag = true;
            tag += HTML[cursorPosition];
        }
    }

    if (!writingTag && tagOpen) {
        tag.innerHTML += HTML[cursorPosition];
    }

    if (!writingTag && !tagOpen) {
        if (HTML[cursorPosition] === " ") {
            tempTypeSpeed = 0;
        }
        else {
            tempTypeSpeed = (Math.random() * typeSpeed) + 30;
        }
        t.innerHTML += HTML[cursorPosition];
    }
    if (writingTag === true && HTML[cursorPosition] === ">") {
        tempTypeSpeed = (Math.random() * typeSpeed) + 30;
        writingTag = false;
        if (tagOpen) {
            var newSpan = document.createElement("span");
            t.appendChild(newSpan);
            newSpan.innerHTML = tag;
            tag = newSpan.firstChild;
        }
    }

    cursorPosition += 1;
    if (cursorPosition < HTML.length - 1) {
        setTimeout(type, tempTypeSpeed);
    }

  };

  return {
    type: type
  };
}

var typer = document.getElementById('typewriter');

typewriter = setupTypewriter(typewriter);

typewriter.type();

Body:
The below code works fine for me.

<span class="standard-highight" id="app"></span>

    <script>
    var app = document.getElementById('app');
    var typewriter = new Typewriter(app, {
        loop: true
});
    typewriter.typeString('<span>List&lt;String&gt; list = Arrays</span>').start();
    </script>

Place the string passing to the typeString() function within any html tag and only then the HTML symbols will be rendered by the function.


问:
Watson IoT: Dashboard graphs cannot retrieve information from cloudant
Continuing with my Watson IoT journey (previous episode), I'm trying to add a line graph to my dashboard in order to view historical data in an easy way. But it seems that, with the recent Extension service removal, it is not possible to view historical information in a widget. This is the message I see in the widget configuration page:

Watson IoT Widget - Cloudant (Image)

"No se han configurado bases de datos en la página de extensiones" -> "No databases have been configured on the extensions page".

I suppose that the configuration option needs to be modified to the new situation, right? Is there any workaround to solve this problem?

Many thanks for your help and I'm sorry for my simple questions, please be patient with me

Best regards,

Aitor

答:
What I learnt from the team and also worked for me is to add a new Forwarding rule on the Swagger UI(OpenAPI spec) as mentioned in the Stackoverflow answer here

The forwarding rule with the corresponding connectorId to be used as a model would be as shown below

```<code>{
 "name": "iot-cloudant-rule",
 "destinationName": "default",
 "type": "event",
 "selector": {
   "deviceType": "*",
   "eventId": "*"
  }
 }
</code>```

If you observe, both the deviceType and eventId should be set to *. Once you execute the forwarding rule, you should see the Cloudant service name

Body:
What I learnt from the team and also worked for me is to add a new Forwarding rule on the Swagger UI(OpenAPI spec) as mentioned in the Stackoverflow answer here

The forwarding rule with the corresponding connectorId to be used as a model would be as shown below

{
 "name": "iot-cloudant-rule",
 "destinationName": "default",
 "type": "event",
 "selector": {
   "deviceType": "*",
   "eventId": "*"
  }
 }

If you observe, both the deviceType and eventId should be set to *. Once you execute the forwarding rule, you should see the Cloudant service name


问:
SqlException Procedure expects parameter Error
I have a simple table which has three fields:

```<code>ID (int)
FormData (xml)
TimeStamp (DateTime).
</code>```

I have created a stored procedure to insert values into the table which is working successfully.  However, in my try catch, it is catching a

System.Data.SqlClient.SqlException: Procedure or function 'spInsertApplication' expects parameter '@formDataDecoded', which was not supplied.

However, the @formDataDecoded parameter is being inserted into the database fine.

Any ideas? I'm not sure where to go from here?

Here's the stored proc:

```<code>ALTER PROCEDURE [dbo].[spInsertApplication]
    -- Add the parameters for the stored procedure here
    @formDataDecoded xml,
    @timestamp DateTime
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    INSERT INTO Applications (formXML, TimeStamp) VALUES (@formDataDecoded, @timestamp)
END
</code>```

Here's the c#:

```<code>string con = ConfigurationManager.AppSettings["umbracoDbDSN"];

using (SqlConnection connection = new SqlConnection(con))
{
    String encodedFormData = HttpUtility.UrlDecode(formData);

    SqlCommand command = connection.CreateCommand();
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "spInsertApplication";
    command.Parameters.AddWithValue("@formDataDecoded", encodedFormData);
    command.Parameters.AddWithValue("@timestamp", DateTime.Now);

    try
    {
        connection.Open();
        command.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        String errorSql = "INSERT INTO ErrorLog(ErrorText) VALUES (@errorText)";
        SqlCommand errorCommand = new SqlCommand(errorSql, connection);
        errorCommand.Parameters.AddWithValue("@errorText", ex.ToString());
        errorCommand.ExecuteNonQuery();
        Response.Redirect("/enterprise-superstars/sounds-like-you-are-already-a-star.aspx");
    }
    finally
    {
        connection.Close();
    }
}
</code>```

And I am getting the formData like this:

```<code>String formData = Request.Form["xmlToVar"];
</code>```

which I pass to the saveApplicationform method.

Thanks in advance.

EDIT

Ran SQL Server Profiler trace on it and it turns out the sproc is being called twice.

The thing is a flash form calls the particular page i will have to get someone to look at the flash code and see how its being posted as I didn't write it.

答:
Try to specify the parameters explicitly:

```<code>command.Parameters.Add("@formDataDecoded", SqlDbType.Xml).Value = encodedFormData;
command.Parameters.Add("@timestamp", SqlDbType.DateTime).Value = DateTime.Now;
</code>```

Also you can try:

```<code>command.CommandText = "exec dbo.spInsertApplication @formDataDecoded, @timestamp";
</code>```

Body:
I have a simple table which has three fields:

ID (int)
FormData (xml)
TimeStamp (DateTime).

I have created a stored procedure to insert values into the table which is working successfully.  However, in my try catch, it is catching a

System.Data.SqlClient.SqlException: Procedure or function 'spInsertApplication' expects parameter '@formDataDecoded', which was not supplied.

However, the @formDataDecoded parameter is being inserted into the database fine.

Any ideas? I'm not sure where to go from here?

Here's the stored proc:

ALTER PROCEDURE [dbo].[spInsertApplication]
    -- Add the parameters for the stored procedure here
    @formDataDecoded xml,
    @timestamp DateTime
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    INSERT INTO Applications (formXML, TimeStamp) VALUES (@formDataDecoded, @timestamp)
END

Here's the c#:

string con = ConfigurationManager.AppSettings["umbracoDbDSN"];

using (SqlConnection connection = new SqlConnection(con))
{
    String encodedFormData = HttpUtility.UrlDecode(formData);

    SqlCommand command = connection.CreateCommand();
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "spInsertApplication";
    command.Parameters.AddWithValue("@formDataDecoded", encodedFormData);
    command.Parameters.AddWithValue("@timestamp", DateTime.Now);

    try
    {
        connection.Open();
        command.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        String errorSql = "INSERT INTO ErrorLog(ErrorText) VALUES (@errorText)";
        SqlCommand errorCommand = new SqlCommand(errorSql, connection);
        errorCommand.Parameters.AddWithValue("@errorText", ex.ToString());
        errorCommand.ExecuteNonQuery();
        Response.Redirect("/enterprise-superstars/sounds-like-you-are-already-a-star.aspx");
    }
    finally
    {
        connection.Close();
    }
}

And I am getting the formData like this:

String formData = Request.Form["xmlToVar"];

which I pass to the saveApplicationform method.

Thanks in advance.

EDIT

Ran SQL Server Profiler trace on it and it turns out the sproc is being called twice.

The thing is a flash form calls the particular page i will have to get someone to look at the flash code and see how its being posted as I didn't write it.

Body:
Try to specify the parameters explicitly:

command.Parameters.Add("@formDataDecoded", SqlDbType.Xml).Value = encodedFormData;
command.Parameters.Add("@timestamp", SqlDbType.DateTime).Value = DateTime.Now;

Also you can try:

command.CommandText = "exec dbo.spInsertApplication @formDataDecoded, @timestamp";