问:
Safely deleting a Django model from the database using a transaction
In my Django application, I have code that deletes a single instance of a model from the database. There is a possibility that two concurrent requests could both try to delete the same model at the same time. In this case, I want one request to succeed and the other to fail. How can I do this?

The problem is that when deleting a instance with delete(), Django doesn't return any information about whether the command was successful or not. This code illustrates the problem:

```<code>b0 = Book.objects.get(id=1)
b1 = Book.objects.get(id=1)
b0.delete()
b1.delete()
</code>```

Only one of these two delete() commands actually deleted the object, but I don't know which one. No exceptions are thrown and nothing is returned to indicate the success of the command. In pure SQL, the command would return the number of rows deleted and if the value was 0, I would know my delete failed.

I am using PostgreSQL with the default Read Commited isolation level. My understanding of this level is that each command (SELECT, DELETE, etc.) sees a snapshot of the database, but that the next command could see a different snapshot of the database. I believe this means I can't do something like this:

```<code># I believe this wont work
@commit_on_success
def view(request):
  try:
    book = Book.objects.get(id=1)
    # Possibility that the instance is deleted by the other request
    # before we get to the next delete()
    book.delete()
  except ObjectDoesntExist:
    # Already been deleted
</code>```

Any ideas?

答:
You can put the constraint right into the SQL DELETE statement by using QuerySet.delete instead of Model.delete:

```<code>Book.objects.filter(pk=1).delete()
</code>```

This will never issue the SELECT query at all, just something along the lines of:

```<code>DELETE FROM Book WHERE id=1;
</code>```

That handles the race condition of two concurrent requests deleting the same record at the same time, but it doesn't let you know whether your delete got there first. For that you would have to get the raw cursor (which django lets you do), .execute() the above DELETE yourself, and then pick up the cursor's rowcount attribute, which will be 0 if you didn't wind up deleting anything.

Body:
In my Django application, I have code that deletes a single instance of a model from the database. There is a possibility that two concurrent requests could both try to delete the same model at the same time. In this case, I want one request to succeed and the other to fail. How can I do this?

The problem is that when deleting a instance with delete(), Django doesn't return any information about whether the command was successful or not. This code illustrates the problem:

b0 = Book.objects.get(id=1)
b1 = Book.objects.get(id=1)
b0.delete()
b1.delete()

Only one of these two delete() commands actually deleted the object, but I don't know which one. No exceptions are thrown and nothing is returned to indicate the success of the command. In pure SQL, the command would return the number of rows deleted and if the value was 0, I would know my delete failed.

I am using PostgreSQL with the default Read Commited isolation level. My understanding of this level is that each command (SELECT, DELETE, etc.) sees a snapshot of the database, but that the next command could see a different snapshot of the database. I believe this means I can't do something like this:

# I believe this wont work
@commit_on_success
def view(request):
  try:
    book = Book.objects.get(id=1)
    # Possibility that the instance is deleted by the other request
    # before we get to the next delete()
    book.delete()
  except ObjectDoesntExist:
    # Already been deleted

Any ideas?

Body:
You can put the constraint right into the SQL DELETE statement by using QuerySet.delete instead of Model.delete:

Book.objects.filter(pk=1).delete()

This will never issue the SELECT query at all, just something along the lines of:

DELETE FROM Book WHERE id=1;

That handles the race condition of two concurrent requests deleting the same record at the same time, but it doesn't let you know whether your delete got there first. For that you would have to get the raw cursor (which django lets you do), .execute() the above DELETE yourself, and then pick up the cursor's rowcount attribute, which will be 0 if you didn't wind up deleting anything.


来源: stackexchange

问:
How to read the new line between multi-valued enumerate that has been turned into a string using ""
I have an enumerate-type multi-valued attribute in the module in which I am working.

The appearance is as follows:

```<code>// as it appears in the attribute column
val1
vals-2
vals3
// below is what is written in my script to turn the contents this attribute
// into a string (for this particular object)
string ovp = o."AttribName" // I have assigned it to a string in this manner
</code>```

If I print the string, it prints out in a column format, like it appears in the attribute column.  How has the new line been defined in this string?

I would like to use the new line definition to put each of the enumerate values into a string array (string arr[size], for clarity as I may not be using the right terms).

I am sure there is a way, but I am only two weeks into using DXL, and am at a loss on how to do this, or if there would be another way to do it that might be easier.

I have searched as much as I am able with the keywords that I know.

Thanks in advance for any help or direction.  I will keep trying in the mean-time and see what I come up with. I assume that if I find an answer, I can update this question with it.

答:
A way that I found works for letters is using Regexp.  First, I also want to note that I pre-declare my string arrays as having a size of 10, I can probably decrease this to 5, because the sets of values never seem to go above 4 at most.  That is beside the point, this is what I found worked for my letters.

```<code>string ovs = o.vs "", ovp = o.vp "", tempstr = ""
Regexp alphabet = regexp"[a-zA-Z]"
int pp, i = 0

for (pp = 0; pp <= length(ovs); pp++) {
    if(alphabet ovs[pp]"")
            tempstr = tempstr "" ovs[pp] ""
    else {
            vsstrarr[i] = tempstr "";
            i++; tempstr = ""
    }
}
</code>```

This does work, but I do not know if multiple Regexp variables would be needed to capture non-alphabet, non '\n' characters.

This was the solution I came up with in the interim, but I accept Balthos' answer as superior.

ContentLicense: CC BY-SA 3.0

Body:
I have an enumerate-type multi-valued attribute in the module in which I am working.

The appearance is as follows:

// as it appears in the attribute column
val1
vals-2
vals3
// below is what is written in my script to turn the contents this attribute
// into a string (for this particular object)
string ovp = o."AttribName" // I have assigned it to a string in this manner

If I print the string, it prints out in a column format, like it appears in the attribute column.  How has the new line been defined in this string?

I would like to use the new line definition to put each of the enumerate values into a string array (string arr[size], for clarity as I may not be using the right terms).

I am sure there is a way, but I am only two weeks into using DXL, and am at a loss on how to do this, or if there would be another way to do it that might be easier.

I have searched as much as I am able with the keywords that I know.

Thanks in advance for any help or direction.  I will keep trying in the mean-time and see what I come up with. I assume that if I find an answer, I can update this question with it.

Body:
A way that I found works for letters is using Regexp.  First, I also want to note that I pre-declare my string arrays as having a size of 10, I can probably decrease this to 5, because the sets of values never seem to go above 4 at most.  That is beside the point, this is what I found worked for my letters.

string ovs = o.vs "", ovp = o.vp "", tempstr = ""
Regexp alphabet = regexp"[a-zA-Z]"
int pp, i = 0

for (pp = 0; pp <= length(ovs); pp++) {
    if(alphabet ovs[pp]"")
            tempstr = tempstr "" ovs[pp] ""
    else {
            vsstrarr[i] = tempstr "";
            i++; tempstr = ""
    }
}

This does work, but I do not know if multiple Regexp variables would be needed to capture non-alphabet, non '\n' characters.

This was the solution I came up with in the interim, but I accept Balthos' answer as superior.


问:
Function for table mathematical calculation
```<code>SNP Ind_1   Ind_2   Ind_3   Ind_4   Ind_5
SNP1     0       0       1       2       0
SNP2     2       0       1       2       1
SNP3     2       0       0       2       1
SNP4     1       1       2       2       2
</code>```

I want to do these following steps

Step 1. Add all SNP row values for Ind_1 and then subtract it by 10 and create a new rowname with score. Ex: Ind_1 = 0 + 2 + 2.....  = 5 and then 10-5=5

Step 2 Repeat the same analysis for Ind_2 to Ind_5`

There are more than 1000 Ind rows and more than 50 SNP columns. Thus a function for that will be a great help. Actual values are not 0, 1 or 2. They are like 1.5, 0.05, 0.001., means between 0 and 2. I just provided this table to look easier

Results should look like this

```<code>SNP Ind_1   Ind_2   Ind_3   Ind_4   Ind_5
SNP1      0       0      1       2       0
SNP2      2       0      1       2       0
SNP3      2       0      0       2       0
SNP4      1       1      2       2       0
SNP5      0       0      0       2       0
Score     5       9      6       0      10
</code>```

`

答:
You can do this in a simple one-liner:</p>

```<code># Your sample data
df <- read.table(text =
    "SNP    Ind_1   Ind_2   Ind_3   Ind_4   Ind_5
     SNP1     0       0       1       2       0
     SNP2     2       0       1       2       1
     SNP3     2       0       0       2       1
     SNP4     1       1       2       2       2", header = T, row.names = 1);

df <- rbind.data.frame(df, score = 10 - colSums(df));
df;
#      Ind_1 Ind_2 Ind_3 Ind_4 Ind_5
#SNP1      0     0     1     2     0
#SNP2      2     0     1     2     1
#SNP3      2     0     0     2     1
#SNP4      1     1     2     2     2
#score     5     9     6     2     6
</code>```

Body:
SNP Ind_1   Ind_2   Ind_3   Ind_4   Ind_5
SNP1     0       0       1       2       0
SNP2     2       0       1       2       1
SNP3     2       0       0       2       1
SNP4     1       1       2       2       2

I want to do these following steps

Step 1. Add all SNP row values for Ind_1 and then subtract it by 10 and create a new rowname with score. Ex: Ind_1 = 0 + 2 + 2.....  = 5 and then 10-5=5

Step 2 Repeat the same analysis for Ind_2 to Ind_5`

There are more than 1000 Ind rows and more than 50 SNP columns. Thus a function for that will be a great help. Actual values are not 0, 1 or 2. They are like 1.5, 0.05, 0.001., means between 0 and 2. I just provided this table to look easier

Results should look like this

SNP Ind_1   Ind_2   Ind_3   Ind_4   Ind_5
SNP1      0       0      1       2       0
SNP2      2       0      1       2       0
SNP3      2       0      0       2       0
SNP4      1       1      2       2       0
SNP5      0       0      0       2       0
Score     5       9      6       0      10

`

Body:
You can do this in a simple one-liner:

# Your sample data
df <- read.table(text =
    "SNP    Ind_1   Ind_2   Ind_3   Ind_4   Ind_5
     SNP1     0       0       1       2       0
     SNP2     2       0       1       2       1
     SNP3     2       0       0       2       1
     SNP4     1       1       2       2       2", header = T, row.names = 1);

df <- rbind.data.frame(df, score = 10 - colSums(df));
df;
#      Ind_1 Ind_2 Ind_3 Ind_4 Ind_5
#SNP1      0     0     1     2     0
#SNP2      2     0     1     2     1
#SNP3      2     0     0     2     1
#SNP4      1     1     2     2     2
#score     5     9     6     2     6


问:
How to set up a dependency between two Scala.js cross-projects in a multi-module build?
Say I have two sub-projects, lib1 and lib2 with build.sbts that look like this:

```<code>lazy val libX = crossProject.in(file(".")).settings(
  ... // a bunch of settings
).jvmSettings(
  ... // a bunch of settings
).jsSettings(
  ... // a bunch of settings
)

lazy val libXJVM = apiClient.jvm
lazy val libXJS = apiClient.js
</code>```

I need to use them in another large multi-module project so that lib2 depends on lib1.

If I try this in the main build.sbt:

```<code>lazy val lib1 = crossProject.in(file("lib1"))

lazy val lib2 = crossProject.in(file("lib2")).dependsOn(lib1)

lazy val lib1JVM = lib1.jvm
...
</code>```

then the project dependency seems to work but the settings from the libraries internal build.sbt files (e.g. libraryDependencies) are completely ignored and the build fails.

If I try this instead:

```<code>lazy val lib1JS = project.in(file("lib1"))
lazy val lib2JS = project.in(file("lib2")).dependsOn(lib1JS)
</code>```

dependsOn is seemingly ignored and lib2 won't compile because it can't import types from lib1.

Is there any way to make this work without duplicating the crossProject settings in the main build file?

答:
If I understand correctly, you are trying to dependsOn (cross) projects that are defined in a completely separate build?

If that is the case, what you need are ProjectRef. There is no direct of CrossProjectRef, so you need to manually use ProjectRefs for the JVM and JS parts. It would look something like:

```<code>lazy val lib1JVM = ProjectRef(file("path/to/other/build", "lib1JVM")
lazy val lib1JS = ProjectRef(file("path/to/other/build", "lib1JS")
</code>```

which you can then depend on with

```<code>lazy val myProject = crossProject
  .jvmConfigure(_.dependsOn(lib1JVM))
  .jsConfigure(_.dependsOn(lib1JS))
</code>```

Note that I do not quite understand what you are trying to do with the lazy val lib2 = crossProject.in(file("lib2")).dependsOn(lib1) part of your question. If lib2 should depend on lib1, that dependency should already have been declared in the build of lib2. In your larger multi-module build that reuses lib1 and lib2, it is too late to add dependencies to lib2 which comes from another build.

Body:
Say I have two sub-projects, lib1 and lib2 with build.sbts that look like this:

lazy val libX = crossProject.in(file(".")).settings(
  ... // a bunch of settings
).jvmSettings(
  ... // a bunch of settings
).jsSettings(
  ... // a bunch of settings
)

lazy val libXJVM = apiClient.jvm
lazy val libXJS = apiClient.js

I need to use them in another large multi-module project so that lib2 depends on lib1.

If I try this in the main build.sbt:

lazy val lib1 = crossProject.in(file("lib1"))

lazy val lib2 = crossProject.in(file("lib2")).dependsOn(lib1)

lazy val lib1JVM = lib1.jvm
...

then the project dependency seems to work but the settings from the libraries internal build.sbt files (e.g. libraryDependencies) are completely ignored and the build fails.

If I try this instead:

lazy val lib1JS = project.in(file("lib1"))
lazy val lib2JS = project.in(file("lib2")).dependsOn(lib1JS)

dependsOn is seemingly ignored and lib2 won't compile because it can't import types from lib1.

Is there any way to make this work without duplicating the crossProject settings in the main build file?

Body:
If I understand correctly, you are trying to dependsOn (cross) projects that are defined in a completely separate build?

If that is the case, what you need are ProjectRef. There is no direct of CrossProjectRef, so you need to manually use ProjectRefs for the JVM and JS parts. It would look something like:

lazy val lib1JVM = ProjectRef(file("path/to/other/build", "lib1JVM")
lazy val lib1JS = ProjectRef(file("path/to/other/build", "lib1JS")

which you can then depend on with

lazy val myProject = crossProject
  .jvmConfigure(_.dependsOn(lib1JVM))
  .jsConfigure(_.dependsOn(lib1JS))

Note that I do not quite understand what you are trying to do with the lazy val lib2 = crossProject.in(file("lib2")).dependsOn(lib1) part of your question. If lib2 should depend on lib1, that dependency should already have been declared in the build of lib2. In your larger multi-module build that reuses lib1 and lib2, it is too late to add dependencies to lib2 which comes from another build.


问:
JAVA GUI - GET and SHOW DATA FROM MYSQL
I am working on a GUI app with MySQL access. When user enters some data in JTextField 'VendorID', I want it to be searched in the database, find the proper line with information and show all the columns in other JtextFields seperately. Actually I wanted this data to be showed in JLabel but unsuccessful, so trying now with JtextFields. Appreciate any help from you.</p>

```<code>public void findVendor() {

        String vatEntered = vendorID.getText();

        try
        {
         String myDriver = "com.mysql.jdbc.Driver";
         String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
         Class.forName(myDriver);
         Connection conn = DriverManager.getConnection(myUrl, "root", "");

         Statement st = conn.createStatement();

         String check = "SELECT * FROM vendorcreation WHERE VAT = 'vatEntered' ";
         ResultSet resultSet = st.executeQuery(check);

         boolean status = true;
         if(resultSet.next()==status){

             nameSelected.setText(resultSet.getString(1));
             adressSelected.setText(resultSet.getString(2));
             countrySelected.setText(resultSet.getString(3));
             vatSelected.setText(resultSet.getString(4));
             ptermsSelected.setText(resultSet.getString(5));

             conn.close();

         }

         else {

             JOptionPane.showMessageDialog(null, "NO DATA FOUND! FIRST YOU MUST CREATE IT", "Inane error",JOptionPane.ERROR_MESSAGE);
             dispose();
             new CreateVendor().setVisible(true);
             }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }
</code>```

答:
From what I'm understanding, you're having trouble executing the statement?
You need to set up the statement as following:

```<code>String check = "SELECT * FROM vendorcreation WHERE VAT = " +vatEntered ;
</code>```

But it is better to use a prepared statement instead.

```<code>String check = "SELECT * FROM vendorcreation WHERE VAT = ?";
PreparedStatement st = conn.prepareStatement(check);
st.setString(1, vatEntered);
ResultSet resultSet = st.executeQuery();
</code>```

As for categorizing data, the order seems to depend on the order that the column is in the database. What you can also do is to manually set the result by changing the statement:

```<code>String check = "SELECT (column1, column2) FROM vendorcreation WHERE VAT = ?"//etc
</code>```

where resultSet.getString(1); would be data from column1.

Title: JAVA GUI - GET and SHOW DATA FROM MYSQL

Body:
I am working on a GUI app with MySQL access. When user enters some data in JTextField 'VendorID', I want it to be searched in the database, find the proper line with information and show all the columns in other JtextFields seperately. Actually I wanted this data to be showed in JLabel but unsuccessful, so trying now with JtextFields. Appreciate any help from you.

public void findVendor() {

        String vatEntered = vendorID.getText();

        try
        {
         String myDriver = "com.mysql.jdbc.Driver";
         String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
         Class.forName(myDriver);
         Connection conn = DriverManager.getConnection(myUrl, "root", "");

         Statement st = conn.createStatement();

         String check = "SELECT * FROM vendorcreation WHERE VAT = 'vatEntered' ";
         ResultSet resultSet = st.executeQuery(check);

         boolean status = true;
         if(resultSet.next()==status){

             nameSelected.setText(resultSet.getString(1));
             adressSelected.setText(resultSet.getString(2));
             countrySelected.setText(resultSet.getString(3));
             vatSelected.setText(resultSet.getString(4));
             ptermsSelected.setText(resultSet.getString(5));

             conn.close();

         }

         else {

             JOptionPane.showMessageDialog(null, "NO DATA FOUND! FIRST YOU MUST CREATE IT", "Inane error",JOptionPane.ERROR_MESSAGE);
             dispose();
             new CreateVendor().setVisible(true);
             }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

Body:
From what I'm understanding, you're having trouble executing the statement?
You need to set up the statement as following:

String check = "SELECT * FROM vendorcreation WHERE VAT = " +vatEntered ;

But it is better to use a prepared statement instead.

String check = "SELECT * FROM vendorcreation WHERE VAT = ?";
PreparedStatement st = conn.prepareStatement(check);
st.setString(1, vatEntered);
ResultSet resultSet = st.executeQuery();

As for categorizing data, the order seems to depend on the order that the column is in the database. What you can also do is to manually set the result by changing the statement:

String check = "SELECT (column1, column2) FROM vendorcreation WHERE VAT = ?"//etc

where resultSet.getString(1); would be data from column1.


问:
Haskell: how to do a loop
I have to read n times and then put it all in a list. I have the following code but it doesn't work. Any Haskell/Functional expert may give me a light?

```<code>replicateIO n a = do y <- a
                 if n < 0
                    then return []
                    else do ys <- (replicateIO n-1 a)
                            return [y:ys]
</code>```

Compile error:

```<code>tres.hs:1:1: error:
    Couldn't match type ‘(->) t0’ with ‘[]’
    Expected type: t -> [[a]]
      Actual type: t -> t0 -> [[a]]
  |
1 | replicateIO n a = if n < 0    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^...
</code>```

答:
Have you tried replicateM?

replicateM n act performs the action n times, gathering the results.

Title: Haskell: how to do a loop

Body:
I have to read n times and then put it all in a list. I have the following code but it doesn't work. Any Haskell/Functional expert may give me a light?

replicateIO n a = do y <- a
                 if n < 0
                    then return []
                    else do ys <- (replicateIO n-1 a)
                            return [y:ys]

Compile error:

tres.hs:1:1: error:
    Couldn't match type ‘(->) t0’ with ‘[]’
    Expected type: t -> [[a]]
      Actual type: t -> t0 -> [[a]]
  |
1 | replicateIO n a = if n < 0    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^...


答:
There are some problems here:

you write [y:ys] as cons, but a cons in Haskell is the (:) :: a -> [a] -> [a] operator, so it is y : ys, or (y : ys) (between brackets). If you write [y:ys], you wrap the result of (y:ys) an a new singleton list;

you perform y <- a n+1 times, since one of the reasons to use Monads can be to use a state (for instance the state of the machine with IO), this can have unintended side effects; and

you use (replicateIO n-1 a) which is interpreted in Haskell as ((replicateIO n)-(1 a)).

But I think the most important aspect is that you write imperative programs in Haskell syntax. Haskell is a functional programming language. This means a different paradigm. I think it would probably be better to write first some programs that do not work with monads (and do notation).

That being said, we can use the above remarks to solve the problem in the question:

```<code>replicateIO n a = if n < 0
                    then return []
                    else do y <- a
                            ys <- replicateIO (n-1) a
                            return (y:ys)
</code>```

Although this fixes the issues, it is not very elegant and Haskell-ish syntax. We can for instance use guards instead of if-then-else:

```<code>replicateIO n a | n < 0 = return []
                | otherwise = do
                      y <- a
                      ys <- replicateIO (n-1) a
                      return (y:ys)
</code>```

We can make some further improvements (and even omit the do notation, but I think it is probably beneficial to first realize that do is actually syntactical sugar for some functions).

Title: Haskell: how to do a loop

Body:
There are some problems here:

you write [y:ys] as cons, but a cons in Haskell is the (:) :: a -> [a] -> [a] operator, so it is y : ys, or (y : ys) (between brackets). If you write [y:ys], you wrap the result of (y:ys) an a new singleton list;

you perform y <- a n+1 times, since one of the reasons to use Monads can be to use a state (for instance the state of the machine with IO), this can have unintended side effects; and

you use (replicateIO n-1 a) which is interpreted in Haskell as ((replicateIO n)-(1 a)).

But I think the most important aspect is that you write imperative programs in Haskell syntax. Haskell is a functional programming language. This means a different paradigm. I think it would probably be better to write first some programs that do not work with monads (and do notation).

That being said, we can use the above remarks to solve the problem in the question:

replicateIO n a = if n < 0
                    then return []
                    else do y <- a
                            ys <- replicateIO (n-1) a
                            return (y:ys)

Although this fixes the issues, it is not very elegant and Haskell-ish syntax. We can for instance use guards instead of if-then-else:

replicateIO n a | n < 0 = return []
                | otherwise = do
                      y <- a
                      ys <- replicateIO (n-1) a
                      return (y:ys)

We can make some further improvements (and even omit the do notation, but I think it is probably beneficial to first realize that do is actually syntactical sugar for some functions).


问:
pandas dataframe drop columns by number of nan
I have a dataframe with some columns containing nan. I'd like to drop those columns with certain number of nan. For example, in the following code, I'd like to drop any column with 2 or more nan. In this case, column 'C' will be dropped and only 'A' and 'B' will be kept. How can I implement it?</p>

```<code>import pandas as pd
import numpy as np

dff = pd.DataFrame(np.random.randn(10,3), columns=list('ABC'))
dff.iloc[3,0] = np.nan
dff.iloc[6,1] = np.nan
dff.iloc[5:8,2] = np.nan

print dff
</code>```

答:
I recommend the drop-method. This is an alternative solution:

```<code>dff.drop(dff.loc[:,len(dff) - dff.isnull().sum() <2], axis=1)
</code>```

Body:
I have a dataframe with some columns containing nan. I'd like to drop those columns with certain number of nan. For example, in the following code, I'd like to drop any column with 2 or more nan. In this case, column 'C' will be dropped and only 'A' and 'B' will be kept. How can I implement it?

import pandas as pd
import numpy as np

dff = pd.DataFrame(np.random.randn(10,3), columns=list('ABC'))
dff.iloc[3,0] = np.nan
dff.iloc[6,1] = np.nan
dff.iloc[5:8,2] = np.nan

print dff

Body:
I recommend the drop-method. This is an alternative solution:

dff.drop(dff.loc[:,len(dff) - dff.isnull().sum() <2], axis=1)


问:
document.querySelectorAll and document.getElementsByClassName event handling
I can't assign an event handler to an element through document.querySelectorAll through a loop of each item in the return result. I don't know what I'm doing wrong. It looks like this:

```<code>// divs to show/hide
const mobileNavOpen = document.querySelector(".mobile-nav-open");
const mobileNavClose = document.querySelector(".mobile-nav-close");

// mobile menu/search overlay
const mobileNavItems = document.getElementById("global-nav--mobile");
const searchOverlay = document.getElementById("search-overlay");

// search unit open/close buttons

// this line I think is broken
const navSearch = document.querySelectorAll(".global-nav__search-icon");

// this one doesn't work either
const navSearch = document.getElementsByClassName("global-nav__search-icon");

const searchCloseButton = document.querySelector(".search-overlay__close");

function mobileOpen(event) {
  event.preventDefault();
  mobileNavItems.classList.add("show");
}

function mobileClose(event) {
  event.preventDefault();
  mobileNavItems.classList.remove("show");
}

function searchOpen(event) {
  event.preventDefault();
  searchOverlay.classList.add("show");
}

function searchClose(event) {
  event.preventDefault();
  searchOverlay.classList.remove("show");
}

mobileNavOpen.addEventListener("click", mobileOpen);
mobileNavClose.addEventListener("click", mobileClose);

for (var i = 0; i < navSearch.length; i++) {
  navSearch.addEventListener("click", searchOpen);
}

searchCloseButton.addEventListener("click", searchClose);
</code>```

Markup:

```<code><nav id="global-nav">
    <a href="#" class="mobile-nav-open">+</a>
    <a class="global-nav__logo" href="/"><img src="/images/logo.png" alt=""></a>
    <img class="global-nav__search-icon mobile-search" src="images/search-icon.png" alt="" style="height: 32px;">
    <ul class="global-nav__items">
      <li><a href="/item1">item 1</a></li>
      <li><a href="/item2">item 2</a></li>
      <li> <a href="#">item 3</a> </li>
      <li> <a href="#">item 4</a> </li>
    </ul>
    <ul class="global-nav__items" id="login-signup">
      <li class="global-nav__search-icon"><img src="images/search-icon.png" alt=""></li>
      <li><a href="#">Log In</a></li>
      <li><a href="#">Sign Up</a></li>
    </ul>
</nav>
</code>```

I found this answer: JS error object has no method addEventListener and am implementing the example but am still having issues.

This is supposed to be easy, what am I doing wrong?

答:
you're missing the index in your loop ([i])

```<code>for (var i = 0; i < navSearch.length; i++) {
    navSearch[i].addEventListener("click", searchOpen);
}
</code>```

Note: querySelectorAll and getElementsByClassName should both do the trick. They return a NodeList or a HTMLCollection (respectively), but both support simple for loops like you did.

Body:
I can't assign an event handler to an element through document.querySelectorAll through a loop of each item in the return result. I don't know what I'm doing wrong. It looks like this:

// divs to show/hide
const mobileNavOpen = document.querySelector(".mobile-nav-open");
const mobileNavClose = document.querySelector(".mobile-nav-close");

// mobile menu/search overlay
const mobileNavItems = document.getElementById("global-nav--mobile");
const searchOverlay = document.getElementById("search-overlay");

// search unit open/close buttons

// this line I think is broken
const navSearch = document.querySelectorAll(".global-nav__search-icon");

// this one doesn't work either
const navSearch = document.getElementsByClassName("global-nav__search-icon");

const searchCloseButton = document.querySelector(".search-overlay__close");

function mobileOpen(event) {
  event.preventDefault();
  mobileNavItems.classList.add("show");
}

function mobileClose(event) {
  event.preventDefault();
  mobileNavItems.classList.remove("show");
}

function searchOpen(event) {
  event.preventDefault();
  searchOverlay.classList.add("show");
}

function searchClose(event) {
  event.preventDefault();
  searchOverlay.classList.remove("show");
}

mobileNavOpen.addEventListener("click", mobileOpen);
mobileNavClose.addEventListener("click", mobileClose);

for (var i = 0; i < navSearch.length; i++) {
  navSearch.addEventListener("click", searchOpen);
}

searchCloseButton.addEventListener("click", searchClose);

Markup:

    +

item 1

item 2

 item 3

 item 4

Log In

Sign Up

I found this answer: JS error object has no method addEventListener and am implementing the example but am still having issues.

This is supposed to be easy, what am I doing wrong?

Body:
you're missing the index in your loop ([i])

for (var i = 0; i < navSearch.length; i++) {
    navSearch[i].addEventListener("click", searchOpen);
}

Note: querySelectorAll and getElementsByClassName should both do the trick. They return a NodeList or a HTMLCollection (respectively), but both support simple for loops like you did.


问:
When I plot the markers in a trace with a symbol, it doesn't show up
I'm trying to generate a scattermapbox using dash and plotly, when I specify a symbol (e.g. "square") inside the marker, it doesn't render when the map is generated.
I'm using a callback function and I tried several symbols, none of which worked, but the circle marker.
Is there something obvious that I'm missing?
Here is a minimal example, to run it you will need a mapbox token.

```<code>import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import datetime as dt

app = dash.Dash()
mapbox_access_token = 'YOUR_MAPBOX_TOKEN_HERE'

app.layout = html.Div(children=[
        html.H1('Dashboard'),
        dcc.DatePickerRange(id='fecha',
                            start_date=dt.datetime.today() - dt.timedelta(days=30),
                            end_date=dt.datetime.today()
                           ),
        html.Center(dcc.Graph(
            id='mapa',
            figure={
                'data': [
                    go.Scattermapbox(
                                    lat=[],
                                    lon=[],
                                )
                        ],
                'layout': go.Layout(
                                    autosize=False,
                                    width=1300,
                                    height=800,
                                    hovermode='closest',
                                    showlegend=False,
                                    mapbox=dict(
                                            accesstoken=mapbox_access_token,
                                            bearing=0,
                                            center=dict(
                                                lat=-32,
                                                lon=-70
                                            ),
                                            pitch=0,
                                            zoom=5,
                                            ),
                                    )
                    })
        ,)
])

@app.callback(
    dash.dependencies.Output('mapa', 'figure'),
     [dash.dependencies.Input('fecha', 'start_date'),
     dash.dependencies.Input('fecha', 'end_date')
    ])
def update_graph(inicio,fin):
    Data = [go.Scattermapbox(
                    name='square',
                    lat=[-31,-30],
                    lon=[-71,-71],
        marker = dict(
            symbol='square',
            size = 8,
            opacity = 0.8,
            color='grey'
            ),
            text = np.array(['square1','square2'])),
           go.Scattermapbox(
                    name='circle',
                    lat=[-31,-30],
                    lon=[-72,-72],
        marker = dict(
            symbol='circle',
            size = 8,
            opacity = 0.8,
            color='grey'
            ),
            text = ['circle1','circle2'])]

    figure={
            'data': Data,
            'layout': go.Layout(
            title='Visitas',
            autosize=False,
            width=1300,
            height=800,
            hovermode='closest',
            showlegend=True,
            mapbox=dict(
                accesstoken=mapbox_access_token,
                bearing=0,
                center=dict(
                    lat=-30.5,
                    lon=-72
                ),
                pitch=0,
                zoom=5,
            ),
    )
    }
    return figure

if __name__ == '__main__':
    app.run_server(host= '0.0.0.0',port=9999)
</code>```

I tried making the same mapbox without dash (i.e. just plotly), and it failed again, so it's not a dash problem, here is how I made the map with plotly (for this you'll need a plotly account):

```<code>import plotly.graph_objs as go
import plotly.plotly as py
mapbox_access_token = 'YOUR_TOKEN_HERE'
Data = [go.Scattermapbox(
                name='square',
                lat=[-31,-30],
                lon=[-71,-71],
    marker = dict(
        symbol='square',
        size = 8,
        opacity = 0.8,
        color='grey'
        ),
        text = ['square1','square2']),
       go.Scattermapbox(
                name='circle',
                lat=[-31,-30],
                lon=[-72,-72],
    marker = dict(
        symbol='circle',
        size = 8,
        opacity = 0.8,
        color='grey'
        ),
        text = ['circle1','circle2'])]

figure={
        'data': Data,
        'layout': go.Layout(
        title='Visitas',
        autosize=False,
        width=1300,
        height=800,
        hovermode='closest',
        showlegend=True,
        mapbox=dict(
            accesstoken=mapbox_access_token,
            bearing=0,
            center=dict(
                lat=-30.5,
                lon=-72
            ),
            pitch=0,
            zoom=5,
        ),
)
}
py.iplot(figure, filename='Broken fig')
</code>```

Thanks in advance, I still don't know if I'm missing something obvious.

答:
I found that the problem was mainly by 2 things:

Mixing in the marker a symbol (square), with a default size and color (this feature is not supported).

The symbol (square) is not supported by Scattermapbox, you can find a list here: Supported Symbols!.

I also opened a github issue where you can find a bit more info github issue

Body:
I'm trying to generate a scattermapbox using dash and plotly, when I specify a symbol (e.g. "square") inside the marker, it doesn't render when the map is generated.
I'm using a callback function and I tried several symbols, none of which worked, but the circle marker.
Is there something obvious that I'm missing?
Here is a minimal example, to run it you will need a mapbox token.

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import datetime as dt

app = dash.Dash()
mapbox_access_token = 'YOUR_MAPBOX_TOKEN_HERE'

app.layout = html.Div(children=[
        html.H1('Dashboard'),
        dcc.DatePickerRange(id='fecha',
                            start_date=dt.datetime.today() - dt.timedelta(days=30),
                            end_date=dt.datetime.today()
                           ),
        html.Center(dcc.Graph(
            id='mapa',
            figure={
                'data': [
                    go.Scattermapbox(
                                    lat=[],
                                    lon=[],
                                )
                        ],
                'layout': go.Layout(
                                    autosize=False,
                                    width=1300,
                                    height=800,
                                    hovermode='closest',
                                    showlegend=False,
                                    mapbox=dict(
                                            accesstoken=mapbox_access_token,
                                            bearing=0,
                                            center=dict(
                                                lat=-32,
                                                lon=-70
                                            ),
                                            pitch=0,
                                            zoom=5,
                                            ),
                                    )
                    })
        ,)
])

@app.callback(
    dash.dependencies.Output('mapa', 'figure'),
     [dash.dependencies.Input('fecha', 'start_date'),
     dash.dependencies.Input('fecha', 'end_date')
    ])
def update_graph(inicio,fin):
    Data = [go.Scattermapbox(
                    name='square',
                    lat=[-31,-30],
                    lon=[-71,-71],
        marker = dict(
            symbol='square',
            size = 8,
            opacity = 0.8,
            color='grey'
            ),
            text = np.array(['square1','square2'])),
           go.Scattermapbox(
                    name='circle',
                    lat=[-31,-30],
                    lon=[-72,-72],
        marker = dict(
            symbol='circle',
            size = 8,
            opacity = 0.8,
            color='grey'
            ),
            text = ['circle1','circle2'])]

    figure={
            'data': Data,
            'layout': go.Layout(
            title='Visitas',
            autosize=False,
            width=1300,
            height=800,
            hovermode='closest',
            showlegend=True,
            mapbox=dict(
                accesstoken=mapbox_access_token,
                bearing=0,
                center=dict(
                    lat=-30.5,
                    lon=-72
                ),
                pitch=0,
                zoom=5,
            ),
    )
    }
    return figure

if __name__ == '__main__':
    app.run_server(host= '0.0.0.0',port=9999)

I tried making the same mapbox without dash (i.e. just plotly), and it failed again, so it's not a dash problem, here is how I made the map with plotly (for this you'll need a plotly account):

import plotly.graph_objs as go
import plotly.plotly as py
mapbox_access_token = 'YOUR_TOKEN_HERE'
Data = [go.Scattermapbox(
                name='square',
                lat=[-31,-30],
                lon=[-71,-71],
    marker = dict(
        symbol='square',
        size = 8,
        opacity = 0.8,
        color='grey'
        ),
        text = ['square1','square2']),
       go.Scattermapbox(
                name='circle',
                lat=[-31,-30],
                lon=[-72,-72],
    marker = dict(
        symbol='circle',
        size = 8,
        opacity = 0.8,
        color='grey'
        ),
        text = ['circle1','circle2'])]

figure={
        'data': Data,
        'layout': go.Layout(
        title='Visitas',
        autosize=False,
        width=1300,
        height=800,
        hovermode='closest',
        showlegend=True,
        mapbox=dict(
            accesstoken=mapbox_access_token,
            bearing=0,
            center=dict(
                lat=-30.5,
                lon=-72
            ),
            pitch=0,
            zoom=5,
        ),
)
}
py.iplot(figure, filename='Broken fig')

Thanks in advance, I still don't know if I'm missing something obvious.


问:
How does the web server locate a file on server through URL?
Has anyone ever tried to implement a web server? Or know something about the underhood of a working web server program? I am wondering what happens exactly from when a URL is received by the web server to a file on the web server is located and sent back as response.

Does the server just keep an internal table to remember the mapping between the URLs it supports and the corresponding local paths? Or is there anything more tricky?

Thanks!

Update

Thanks for your replies. Here's my understanding for now.

I checked with the Microsoft IIS (Internet Information Service), I noticed that IIS can host multiple sites, and foreach site IIS memorize its root path on the local file system. Different sites on the same host share the same host name or IP, and they are differentiated by separate ports. For example:

```<code>http://www.myServer.com:1111/folderA/pageA.htm
</code>```

The web server will use www.myServer.com:1111 part of the URL string to locate which path on its local file system will be used, and then in that local path, it searches for subfolder folderA and then the file pageA.htm.

The web server only need to memorize the following mapping between 2 plain strings:

```<code>"http://www.myServer.com:1111/" <---> "D:\myWebRoot"
</code>```

I don't know where this kind of mapping info is stored, maybe some config files for the Web Server Program in question.

But the result of this mapping granularity is that we could only access content within that mapped local folder. We couldn't do arbitray mapping.

Update - 2 -

I found where the IIS keep the mapping, here's some quotes from applicationHost.config:

```<code><sites>
    <site name="Default Web Site" id="1" serverAutoStart="false">
        <application path="/">
            <virtualDirectory path="/" physicalPath="%SystemDrive%\inetpub\wwwroot" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:80:" />
            <binding protocol="net.tcp" bindingInformation="808:*" />
            <binding protocol="net.pipe" bindingInformation="*" />
            <binding protocol="net.msmq" bindingInformation="localhost" />
            <binding protocol="msmq.formatname" bindingInformation="localhost" />
        </bindings>
    </site>
    <site name="myIISService" id="2" serverAutoStart="true">
        <application path="/" applicationPool="myIISService">
            <virtualDirectory path="/" physicalPath="D:\MySites\MyIISService" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:8022:" />
        </bindings>
    </site>
    <siteDefaults>
        <logFile logFormat="W3C" directory="%SystemDrive%\inetpub\logs\LogFiles" />
        <traceFailedRequestsLogging directory="%SystemDrive%\inetpub\logs\FailedReqLogFiles" />
    </siteDefaults>
    <applicationDefaults applicationPool="DefaultAppPool" />
    <virtualDirectoryDefaults allowSubDirConfig="true" />
</sites>
</code>```

Update - 3 -

After I read foo's reply, my undersanding of a "server" is enlarged. I want to make some comment based on my recent learning of WCF.

No matter what kind of server it is, we could always send messages to them by specifying the protocol, URL, port. For example:

```<code>[http://www.myserver.com:1111/]page.htm

[net.tcp://www.myserver.com/]someService.svc/someMethod

[net.msmq://www.myserver.com/]someService.svc

[net.pipe://localhost/]
</code>```

After the messages arrives at the server program using the parts in square bracket of above URLs, the rest part of the url will send to the server program as input for further processing. And the following behaviour could be as simple as static content feeding or as complex as dynamic content generating.

答: For static files there's usually no means of a mapping. The only what the webserver need to know is the absolute disk file system path to the public web document root which is usually definied somewhere in some deployment configuration file (httpd.conf for Apache HTTPD, server.xml and/or context.xml for Apache Tomcat, etc). The webserver extracts the relevant part from the URL, converts it to an absolute disk file system path based on the path to the web document root, locates the file on disk and streams it.

ContentLicense: CC BY-SA 2.5

Body:
Has anyone ever tried to implement a web server? Or know something about the underhood of a working web server program? I am wondering what happens exactly from when a URL is received by the web server to a file on the web server is located and sent back as response.

Does the server just keep an internal table to remember the mapping between the URLs it supports and the corresponding local paths? Or is there anything more tricky?

Thanks!

Update

Thanks for your replies. Here's my understanding for now.

I checked with the Microsoft IIS (Internet Information Service), I noticed that IIS can host multiple sites, and foreach site IIS memorize its root path on the local file system. Different sites on the same host share the same host name or IP, and they are differentiated by separate ports. For example:

http://www.myServer.com:1111/folderA/pageA.htm

The web server will use www.myServer.com:1111 part of the URL string to locate which path on its local file system will be used, and then in that local path, it searches for subfolder folderA and then the file pageA.htm.

The web server only need to memorize the following mapping between 2 plain strings:

"http://www.myServer.com:1111/" <---> "D:\myWebRoot"

I don't know where this kind of mapping info is stored, maybe some config files for the Web Server Program in question.

But the result of this mapping granularity is that we could only access content within that mapped local folder. We couldn't do arbitray mapping.

Update - 2 -

I found where the IIS keep the mapping, here's some quotes from applicationHost.config:

<sites>
    <site name="Default Web Site" id="1" serverAutoStart="false">
        <application path="/">
            <virtualDirectory path="/" physicalPath="%SystemDrive%\inetpub\wwwroot" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:80:" />
            <binding protocol="net.tcp" bindingInformation="808:*" />
            <binding protocol="net.pipe" bindingInformation="*" />
            <binding protocol="net.msmq" bindingInformation="localhost" />
            <binding protocol="msmq.formatname" bindingInformation="localhost" />
        </bindings>
    </site>
    <site name="myIISService" id="2" serverAutoStart="true">
        <application path="/" applicationPool="myIISService">
            <virtualDirectory path="/" physicalPath="D:\MySites\MyIISService" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:8022:" />
        </bindings>
    </site>
    <siteDefaults>
        <logFile logFormat="W3C" directory="%SystemDrive%\inetpub\logs\LogFiles" />
        <traceFailedRequestsLogging directory="%SystemDrive%\inetpub\logs\FailedReqLogFiles" />
    </siteDefaults>
    <applicationDefaults applicationPool="DefaultAppPool" />
    <virtualDirectoryDefaults allowSubDirConfig="true" />
</sites>

Update - 3 -

After I read foo's reply, my undersanding of a "server" is enlarged. I want to make some comment based on my recent learning of WCF.

No matter what kind of server it is, we could always send messages to them by specifying the protocol, URL, port. For example:

[http://www.myserver.com:1111/]page.htm

[net.tcp://www.myserver.com/]someService.svc/someMethod

[net.msmq://www.myserver.com/]someService.svc

[net.pipe://localhost/]

After the messages arrives at the server program using the parts in square bracket of above URLs, the rest part of the url will send to the server program as input for further processing. And the following behaviour could be as simple as static content feeding or as complex as dynamic content generating.


问:
Using .js file extensions whilst writing scripts that return jsx
I started using react as my ui framework of choice. Upon my adventure through the documentation I noticed that when using the create-react-app script to spin up a new react boilerplate, they used .js file extension on scripts that where returning jsx code. When I asked my buddy he told me that you should use the .jsx extension on scripts that are returning this kind of code.

Im a bit lost here as if both works, wouldn't it just be better to go with the .js extension as at the end of the day its javascript we writing.

Please help me with what is considered best practise. (I kinda have a feeling it would be to use the .jsx extensions on these types of scripts, but I'd love to hear the community's view on this)

Thanks in advance :)

答:
Actually it doesn't matter, is up to you to decide I prefer to use .jsx when I return the mix between HTML and JS and use .js only when I'm using plain JS or ES6.

I recommend you to read about this on this issue on github.


问:
clever way to add nested properties?
```<code>const data = {
  "orders" : [
    { "items" : {"count":3} },
    { "items" : {"count":1} },
    { "items" : {"count":2} }
  ]
}
let total = 0
data.orders.map((order) => order.items.map((item) => (total += item.count)))
console.log(total)
</code>```

Is there a more clever way to do that, where I could say console.log(someoperation(data)) ?

答:
You could use a nested destructuring assignment for the value for counting.

var data = { orders: [{ items: { count: 3 } }, { items: { count: 1 } }, { items: { count: 2 } }] },
    total = data.orders.reduce((s, { items: { count } }) => s + count, 0);

console.log(total);```
</div>
</div>
</p>

<p>Function for a single call with the object</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const getCount = ({ orders }) => orders.reduce((s, { items: { count } }) => s + count, 0);

var data = { orders: [{ items: { count: 3 } }, { items: { count: 1 } }, { items: { count: 2 } }] };

console.log(getCount(data));</code>```

Title: clever way to add nested properties?

Body:
const data = {
  "orders" : [
    { "items" : {"count":3} },
    { "items" : {"count":1} },
    { "items" : {"count":2} }
  ]
}
let total = 0
data.orders.map((order) => order.items.map((item) => (total += item.count)))
console.log(total)

Is there a more clever way to do that, where I could say console.log(someoperation(data)) ?

Body:
You could use a nested destructuring assignment for the value for counting.

var data = { orders: [{ items: { count: 3 } }, { items: { count: 1 } }, { items: { count: 2 } }] },
    total = data.orders.reduce((s, { items: { count } }) => s + count, 0);

console.log(total);

Function for a single call with the object

const getCount = ({ orders }) => orders.reduce((s, { items: { count } }) => s + count, 0);

var data = { orders: [{ items: { count: 3 } }, { items: { count: 1 } }, { items: { count: 2 } }] };

console.log(getCount(data));


问:
Method 'range' of Object '_global' failed error when I am trying to paste
I am trying to copy 12 cells (1 row, 12 columns) and paste it to a different location in the same sheet.

```<code> For j = 1 To 519
For k = 2 To 519
    b = "K" & CStr(k)
    c = "AA" & CStr(k)
    Set x = Range(b)
    Set y = Range(c)
    If x = y Then
        For a = 2 To 519
            d = "M" & CStr(a)
            e = "x" & CStr(a)
            s = "AC" & CStr(a)
            Set dd = Range(d)
            Set ee = Range(e)
            Set ss = Range(s)
            Range("dd:ee").Select
            Selection.copy
            Range("ss").PasteSpecial = xlPasteAll
</code>```

I'm getting an error at the paste section of the code, saying "Method 'range' of Object '_global' failed error."

Can you please help me on this ?

答:
You will need the end if and nexts
J,k, a, b, d, e, and s are all just variables (should be string)</p>

```<code>      For j = 1 To 519
        For k = 2 To 519
         b = "K" & k
         c = "AA" & k
         Set x = Range(b)
         Set y = Range(c)
         If x.value = y.value Then
             For a = 2 To 519
                 d = "M" & a)
                 e = "X" & a
                 s = "AC" & a
                 Range(d & ":" & e).copy Range(s).PasteSpecial
             End If
         Next K
     Next J
</code>```

Body:
I am trying to copy 12 cells (1 row, 12 columns) and paste it to a different location in the same sheet.

 For j = 1 To 519
For k = 2 To 519
    b = "K" & CStr(k)
    c = "AA" & CStr(k)
    Set x = Range(b)
    Set y = Range(c)
    If x = y Then
        For a = 2 To 519
            d = "M" & CStr(a)
            e = "x" & CStr(a)
            s = "AC" & CStr(a)
            Set dd = Range(d)
            Set ee = Range(e)
            Set ss = Range(s)
            Range("dd:ee").Select
            Selection.copy
            Range("ss").PasteSpecial = xlPasteAll

I'm getting an error at the paste section of the code, saying "Method 'range' of Object '_global' failed error."

Can you please help me on this ?

Body:
You will need the end if and nexts
J,k, a, b, d, e, and s are all just variables (should be string)

      For j = 1 To 519
        For k = 2 To 519
         b = "K" & k
         c = "AA" & k
         Set x = Range(b)
         Set y = Range(c)
         If x.value = y.value Then
             For a = 2 To 519
                 d = "M" & a)
                 e = "X" & a
                 s = "AC" & a
                 Range(d & ":" & e).copy Range(s).PasteSpecial
             End If
         Next K
     Next J


问:
Why Erlang is suitable for soft real-time applications, but not for hard real-time?
Or maybe it's good for hard real-time too?</p>

答: Garbage collection can lead to pauses of unpredictable duration; as such, you can't put hard upper bounds on latency. The definition of hard real time is basically that you can set hard bounds on latency, so this is a problem.</p>


问:
db.collection is not a function when using MongoClient v3.0
I have been trying W3schools tutorial on nodeJS with MongoDB.

When I try to implement this example in a nodeJS environment and invoke the function with an AJAX call, I got the error below:

```<code>TypeError: db.collection is not a function
    at c:\Users\user\Desktop\Web Project\WebService.JS:79:14
    at args.push (c:\Users\user\node_modules\mongodb\lib\utils.js:431:72)
    at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:254:5
    at connectCallback (c:\Users\user\node_modules\mongodb\lib\mongo_client.js:933:5)
    at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:794:11
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
</code>```

Please find below my implemented code:

```<code>var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mytestingdb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  db.collection("customers").findOne({}, function(err, result) {
    if (err) throw err;
    console.log(result.name);
    db.close();
  });
});
</code>```

Note that the error occurs whenever the execution hits:

```<code>db.collection("customers").findOne({}, function(err, result) {}
</code>```

Also, note (in case it matters) that I have installed the latest MongoDB package for node JS (npm install mongodb), and the MongoDB version is MongoDB Enterprise 3.4.4, with MongoDB Node.js driver v3.0.0-rc0.

答:
I encountered the same thing. In package.json, change mongodb line to "mongodb": "^2.2.33". You will need to  uninstall mongodb npm by removing MongoDB Driver/ node_modules or etc , then  install npm to install this version.

This resolved the issue for me. Seems to be a bug or docs need to be updated.

Body:
I have been trying W3schools tutorial on nodeJS with MongoDB.

When I try to implement this example in a nodeJS environment and invoke the function with an AJAX call, I got the error below:

TypeError: db.collection is not a function
    at c:\Users\user\Desktop\Web Project\WebService.JS:79:14
    at args.push (c:\Users\user\node_modules\mongodb\lib\utils.js:431:72)
    at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:254:5
    at connectCallback (c:\Users\user\node_modules\mongodb\lib\mongo_client.js:933:5)
    at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:794:11
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

Please find below my implemented code:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mytestingdb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  db.collection("customers").findOne({}, function(err, result) {
    if (err) throw err;
    console.log(result.name);
    db.close();
  });
});

Note that the error occurs whenever the execution hits:

db.collection("customers").findOne({}, function(err, result) {}

Also, note (in case it matters) that I have installed the latest MongoDB package for node JS (npm install mongodb), and the MongoDB version is MongoDB Enterprise 3.4.4, with MongoDB Node.js driver v3.0.0-rc0.

ContentLicense: CC BY-SA 4.0


问:
asp.net dispose inside a class
Before return dt i want destroy sda

How destroy an Object with Dispose - inside the class dbConnect ?

```<code>  public class dbConnect
    {

    // othee code

    public DataTable SetQuery(string constr, DataTable dt, string sSql)
        {
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                //sda = null
                using (MySqlDataAdapter sda = new MySqlDataAdapter())
                    {
                        try
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            sda.Fill(dt);
                        }

                        finally
                        {
                            if (sda != null)
                                sda.Dispose();
                            //why the sda is not = null ?
                        }

                        return dt;
                    }
            }
        }
</code>```

What is the correct procedure for destroy object (not class) ?

答:
Since you make use of the using statement for sda, the Dispose would be called under the hood once you don't need it anymore.

For further info please have look here.

Title: asp.net dispose inside a class

Body:
Before return dt i want destroy sda

How destroy an Object with Dispose - inside the class dbConnect ?

  public class dbConnect
    {

    // othee code

    public DataTable SetQuery(string constr, DataTable dt, string sSql)
        {
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                //sda = null
                using (MySqlDataAdapter sda = new MySqlDataAdapter())
                    {
                        try
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            sda.Fill(dt);
                        }

                        finally
                        {
                            if (sda != null)
                                sda.Dispose();
                            //why the sda is not = null ?
                        }

                        return dt;
                    }
            }
        }

What is the correct procedure for destroy object (not class) ?


问:
Unknown field in panic stack trace
In trying to learn how to debug stack traces from panics, I came across something confusing.

```<code>package main

func F(a int) {
    panic(nil)
}

func main() {
    F(1)
}
</code>```

outputs the following when I run it on the attached play link:

```<code>panic: nil

goroutine 1 [running]:
main.F(0x1, 0x10436000)
    /tmp/sandbox090887108/main.go:4 +0x20
main.main()
    /tmp/sandbox090887108/main.go:8 +0x20
</code>```

I can't decipher what the second number means (the 0x10436000 in main.F(0x1, 0x10436000)).  It doesn't appear if there's a second int argument, or if anything else if passed in as the first argument (can be seen in the second play link).

One arg: https://play.golang.org/p/3iV48xlNFR

Two args: https://play.golang.org/p/4jA7ueI86K

答:
The data printed in the stack trace is the arguments, but the values don't correspond directly to the arguments passed in, it's the raw data printed in pointer-sized values (though usually this is the same as the native word size). The playground is slightly unique, in that it's a 64bit word architecture with 32bit pointers(GOARCH=amd64p32).

In traceback.go you can see that the values are printed by stepping through the arguments based on pointer size;

```<code>for i := uintptr(0); i < frame.arglen/sys.PtrSize; i++ {
</code>```

So because the word size is twice as big as the pointer size in the playground, you will always have an even number of values printed in the frame arguments.

Another example of how the data is presented can be seen in the playground by using smaller types in the function arguments: https://play.golang.org/p/vHZDEHQZLh

```<code>func F(a uint8) {
    panic(nil)
}

// F(1)
// main.F(0x97301, 0x10436000)
</code>```

Only the first 8 bits of the 64bit word are used, which is 0x97301 & 0x0f, or simply 1. The extra 0x97300 from the first value and the entire 0x10436000 are just the remainder of that first 64bit word which is unused by the function.

You can see the same behavior on amd64 systems by using more arguments. This signature for example;

```<code>func F(a, b, c uint32)
</code>```

when called via F(1, 1, 1), it will print a stack trace like:

```<code>main.F(0x100000001, 0xc400000001)
</code>```

because the 3 32bit values take 2 words

The final set of values to note are return values, which are also allocated on the stack. The following function signature:

```<code>func F(a int64) (int, int)
</code>```

on amd64, would show the stack frame arguments like:

```<code>main.F(0xa, 0x1054d60, 0xc420078058)
</code>```

With one word for a, and two more for the (int, int) return values. The return values are not initialized however, so there's not much to me gained here other than to understand why these values are there.

Title: Unknown field in panic stack trace

Body:
In trying to learn how to debug stack traces from panics, I came across something confusing.

package main

func F(a int) {
    panic(nil)
}

func main() {
    F(1)
}

outputs the following when I run it on the attached play link:

panic: nil

goroutine 1 [running]:
main.F(0x1, 0x10436000)
    /tmp/sandbox090887108/main.go:4 +0x20
main.main()
    /tmp/sandbox090887108/main.go:8 +0x20

I can't decipher what the second number means (the 0x10436000 in main.F(0x1, 0x10436000)).  It doesn't appear if there's a second int argument, or if anything else if passed in as the first argument (can be seen in the second play link).

One arg: https://play.golang.org/p/3iV48xlNFR

Two args: https://play.golang.org/p/4jA7ueI86K

Body:
The data printed in the stack trace is the arguments, but the values don't correspond directly to the arguments passed in, it's the raw data printed in pointer-sized values (though usually this is the same as the native word size). The playground is slightly unique, in that it's a 64bit word architecture with 32bit pointers(GOARCH=amd64p32).

In traceback.go you can see that the values are printed by stepping through the arguments based on pointer size;

for i := uintptr(0); i < frame.arglen/sys.PtrSize; i++ {

So because the word size is twice as big as the pointer size in the playground, you will always have an even number of values printed in the frame arguments.

Another example of how the data is presented can be seen in the playground by using smaller types in the function arguments: https://play.golang.org/p/vHZDEHQZLh

func F(a uint8) {
    panic(nil)
}

// F(1)
// main.F(0x97301, 0x10436000)

Only the first 8 bits of the 64bit word are used, which is 0x97301 & 0x0f, or simply 1. The extra 0x97300 from the first value and the entire 0x10436000 are just the remainder of that first 64bit word which is unused by the function.

You can see the same behavior on amd64 systems by using more arguments. This signature for example;

func F(a, b, c uint32)

when called via F(1, 1, 1), it will print a stack trace like:

main.F(0x100000001, 0xc400000001)

because the 3 32bit values take 2 words

The final set of values to note are return values, which are also allocated on the stack. The following function signature:

func F(a int64) (int, int)

on amd64, would show the stack frame arguments like:

main.F(0xa, 0x1054d60, 0xc420078058)

With one word for a, and two more for the (int, int) return values. The return values are not initialized however, so there's not much to me gained here other than to understand why these values are there.


问:
custom Bean Validation not working with multiple bean classes
I'm trying to create a custom beans validation for my REST API, but for some reason the "required = false" validation is not working.

When I send my JSON without the attribute callPosition I get following error.

```<code>{
    "codes": [
        "ValidateString.GSMPLMNRecordModel.transit.callPosition",
        "ValidateString.transit.callPosition",
        "ValidateString.callPosition",
        "ValidateString.java.lang.String",
        "ValidateString"
    ],
    "arguments": [
        {
            "codes": [
                "GSMPLMNRecordModel.transit.callPosition",
                "transit.callPosition"
            ],
            "arguments": null,
            "defaultMessage": "transit.callPosition",
            "code": "transit.callPosition"
        },
        [
            "A",
            "B",
            "C",
            "D"
        ]
    ],
    "defaultMessage": "{com.mycompany.asn.validator.ValidateString.message}",
    "objectName": "GSMPLMNRecordModel",
    "field": "transit.callPosition",
    "rejectedValue": null,
    "bindingFailure": false,
    "code": "ValidateString"
},
</code>```

In my Model:

```<code>@JsonProperty(required = false)
@ValidateString(acceptedValues = {"A","B","C","D"})
private String callPosition;
</code>```

The Annotaion:

```<code>@Documented
@Constraint(validatedBy = StringValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
public @interface ValidateString {
    String[] acceptedValues();

    String message() default "{com.mycompany.validator.ValidateString.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
</code>```

the Validator:

```<code>public class StringValidator implements ConstraintValidator<ValidateString, String> {

    private List<String> valueList;

    @Override
    public void initialize(ValidateString validateString) {
        valueList = new ArrayList<String>();
        for (String val : validateString.acceptedValues()) {
            valueList.add(val.toUpperCase());
        }
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        return value != null && valueList.contains(value.toUpperCase());
    }
}

                                       .
</code>```

Could anyone tell me what is the problem?

答:
All your code looks ok. Using the code provided, I have successfully called the validator using this (using Jersey):

```<code>@POST
public Response getTest(TestRest testRest) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<TestRest>> constraintViolations = validator.validate(testRest);
    System.out.println(constraintViolations.size());

    return Response.status(Response.Status.OK).entity(constraintViolations.size()).build();
}
</code>```

Hope this helps.

Body:
I'm trying to create a custom beans validation for my REST API, but for some reason the "required = false" validation is not working.

When I send my JSON without the attribute callPosition I get following error.

{
    "codes": [
        "ValidateString.GSMPLMNRecordModel.transit.callPosition",
        "ValidateString.transit.callPosition",
        "ValidateString.callPosition",
        "ValidateString.java.lang.String",
        "ValidateString"
    ],
    "arguments": [
        {
            "codes": [
                "GSMPLMNRecordModel.transit.callPosition",
                "transit.callPosition"
            ],
            "arguments": null,
            "defaultMessage": "transit.callPosition",
            "code": "transit.callPosition"
        },
        [
            "A",
            "B",
            "C",
            "D"
        ]
    ],
    "defaultMessage": "{com.mycompany.asn.validator.ValidateString.message}",
    "objectName": "GSMPLMNRecordModel",
    "field": "transit.callPosition",
    "rejectedValue": null,
    "bindingFailure": false,
    "code": "ValidateString"
},

In my Model:

@JsonProperty(required = false)
@ValidateString(acceptedValues = {"A","B","C","D"})
private String callPosition;

The Annotaion:

@Documented
@Constraint(validatedBy = StringValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
public @interface ValidateString {
    String[] acceptedValues();

    String message() default "{com.mycompany.validator.ValidateString.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

the Validator:

public class StringValidator implements ConstraintValidator<ValidateString, String> {

    private List<String> valueList;

    @Override
    public void initialize(ValidateString validateString) {
        valueList = new ArrayList<String>();
        for (String val : validateString.acceptedValues()) {
            valueList.add(val.toUpperCase());
        }
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        return value != null && valueList.contains(value.toUpperCase());
    }
}

                                       .

Could anyone tell me what is the problem?

Body:
All your code looks ok. Using the code provided, I have successfully called the validator using this (using Jersey):

@POST
public Response getTest(TestRest testRest) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<TestRest>> constraintViolations = validator.validate(testRest);
    System.out.println(constraintViolations.size());

    return Response.status(Response.Status.OK).entity(constraintViolations.size()).build();
}

Hope this helps.


问:
PHP Curl - Scraping from data from site that has data in window.open created by Javascript
I am attempting to scrape data from a new window (using Javascript's window.open()) that is generated by the site I am posting to via cUrl, but I am unsure how to go about this.

The target site only generates this needed data when certain parameters are posted to it, and no other way.

The following code simply dumps the result of the cUrl request, but the result does not contain any data that is relevant.

My code:

```<code>//build post data for request
$proofData = array("formula" => $formula,
                     "proof" => $proof,
                    "action" => $action);
$postProofData = http_build_query($proofData);

$ch = curl_init($url); //open connection

//sort curl settings for request
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 3);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postProofData);

//obtain data from LigLab
$result = curl_exec($ch);

//finish connection
curl_close($ch);

echo "forumla: " . $formula;
var_dump($result);
</code>```

The following code is what is generated

Target site's code:

```<code>var proof =  "<?php echo str_replace("\n","|",$annoted_proof) ?>";
var lines = proof.split('|');
proof_window=window.open("","Proof and Justifications","scrollbar=yes,resizable=yes, titlebar=yes,menubar=yes,status=yes,width= 800, height=800, alwaysRaised=yes");

for(var i = 0;i < lines.length;i++){
    proof_window.document.write(lines[i]);
    proof_window.document.write("\n");
}
</code>```

I want to scrape the lines variable but it is generated after page load and after user interaction.

答:
You can't parse processed javascript code with curl.

You have to use a headless browser, which emulates a real browser with events (clicks, hover and javascript code)

you can start here http://www.simpletest.org/en/browser_documentation.html or here PHP Headless Browser?

Body:
I am attempting to scrape data from a new window (using Javascript's window.open()) that is generated by the site I am posting to via cUrl, but I am unsure how to go about this.

The target site only generates this needed data when certain parameters are posted to it, and no other way.

The following code simply dumps the result of the cUrl request, but the result does not contain any data that is relevant.

My code:

//build post data for request
$proofData = array("formula" => $formula,
                     "proof" => $proof,
                    "action" => $action);
$postProofData = http_build_query($proofData);

$ch = curl_init($url); //open connection

//sort curl settings for request
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 3);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postProofData);

//obtain data from LigLab
$result = curl_exec($ch);

//finish connection
curl_close($ch);

echo "forumla: " . $formula;
var_dump($result);

The following code is what is generated

Target site's code:

var proof =  "<?php echo str_replace("\n","|",$annoted_proof) ?>";
var lines = proof.split('|');
proof_window=window.open("","Proof and Justifications","scrollbar=yes,resizable=yes, titlebar=yes,menubar=yes,status=yes,width= 800, height=800, alwaysRaised=yes");

for(var i = 0;i < lines.length;i++){
    proof_window.document.write(lines[i]);
    proof_window.document.write("\n");
}

I want to scrape the lines variable but it is generated after page load and after user interaction.


问:
What is the purpose of ungetc (or ungetch from K&R)?
Can anyone explain to me the purpose of ungetch?
This is from K&R chapter 4 where you create a Reverse Polish Calculator.

I've ran the program without the call to ungetch and in my tests it still works the same.

```<code> int getch(void) /* get a (possibly pushed back) character */
    {
        if (bufp > 0)
        {
            return buf[--bufp];
        }
        else
        {
            return getchar();
        }
    }

    void ungetch(int c) /* push character back on input */
    {
        if (bufp >= BUFSIZE)
        {
            printf("ungetch: too many characters\n");
        }
        else
        {
            buf[bufp++] = c;
        }

}
</code>```

(I've removed the ternary operator in getch to make it clearer.)

答:
It's used a lot for lexical scanners (the part of the compiler that breaks your text into chunks like variable names, constants, operators, etc.).  The function isn't necessary for the scanner, it's just very convenient.

When you're reading a variable name, for example, you don't know when you're done until you read a character that can't be part of the variable name.  But then you have to remember that character and find a way to communicate it to the next chunk of the lexer.  You could create a global variable or something, or pass it to the caller--but then how do you return other things, like error codes?  Instead, you ungetch() the character to put it back into the input stream, do whatever you need to with your variable name and return.  Then when the lexer starts reading the next chunk, it doesn't have to look around for extra characters lying around.

OwnerDisplayName: Tyler

Body:
Can anyone explain to me the purpose of ungetch?
This is from K&R chapter 4 where you create a Reverse Polish Calculator.

I've ran the program without the call to ungetch and in my tests it still works the same.

 int getch(void) /* get a (possibly pushed back) character */
    {
        if (bufp > 0)
        {
            return buf[--bufp];
        }
        else
        {
            return getchar();
        }
    }

    void ungetch(int c) /* push character back on input */
    {
        if (bufp >= BUFSIZE)
        {
            printf("ungetch: too many characters\n");
        }
        else
        {
            buf[bufp++] = c;
        }

}

(I've removed the ternary operator in getch to make it clearer.)


问:
macvim html5 syntax highlighting in erb templates
I am trying to get syntax highlighting for HTML 5 elements in erb templates working.

I have installed newest rails.vim plugin as well as html5.vim and can't seem to get it to work.

Works fine on .html files.

答:
i think its just that it doesn't read that .erb is a HTML file.

BTW @Pasta, vim is really good for productivity if you know how to use it.


问:
Pandas groupby on one column and then filter based on quantile value of another column
I am trying to filter my data down to only those rows in the bottom decile of the data for any given date.  Thus, I need to groupby the date first to get the sub-universe of data and then from there filter that same sub-universe down to only those values falling in the bottom decile.  I then need to aggregate all of the different dates back together to make one large dataframe.

For example, I want to take the following df:

```<code>df = pd.DataFrame([['2017-01-01', 1], ['2017-01-01', 5], ['2017-01-01', 10], ['2018-01-01', 5], ['2018-01-01', 10]], columns=['date', 'value'])
</code>```

and only those rows where the value is in the bottom decile for that date (below 1.8 and 5.5, respectively):

```<code>       date       value
0  '2017-01-01'     1
1  '2018-01-01'     5
</code>```

I can get a series of the bottom decile using df.groupby(['date'], 'value'].quantile(.1), but this would then require me to iterate through the entire df and compare the value to the quantile value in the series, which I'm trying to avoid due to performance issues.

答:
Something like this?

```<code>df.groupby('date').value.apply(lambda x: x[x < x.quantile(.1)]).reset_index(1,drop = True).reset_index()

    date        value
0   2017-01-01      1
1   2018-01-01      5
</code>```

Edit:

```<code>df.loc[df['value'] < df.groupby('date').value.transform(lambda x: x.quantile(.1))]
</code>```

Body:
I am trying to filter my data down to only those rows in the bottom decile of the data for any given date.  Thus, I need to groupby the date first to get the sub-universe of data and then from there filter that same sub-universe down to only those values falling in the bottom decile.  I then need to aggregate all of the different dates back together to make one large dataframe.

For example, I want to take the following df:

df = pd.DataFrame([['2017-01-01', 1], ['2017-01-01', 5], ['2017-01-01', 10], ['2018-01-01', 5], ['2018-01-01', 10]], columns=['date', 'value'])

and only those rows where the value is in the bottom decile for that date (below 1.8 and 5.5, respectively):

       date       value
0  '2017-01-01'     1
1  '2018-01-01'     5

I can get a series of the bottom decile using df.groupby(['date'], 'value'].quantile(.1), but this would then require me to iterate through the entire df and compare the value to the quantile value in the series, which I'm trying to avoid due to performance issues.

Body:
Something like this?

df.groupby('date').value.apply(lambda x: x[x < x.quantile(.1)]).reset_index(1,drop = True).reset_index()

    date        value
0   2017-01-01      1
1   2018-01-01      5

Edit:

df.loc[df['value'] < df.groupby('date').value.transform(lambda x: x.quantile(.1))]


问:
How to yield/resume OpenMP untied tasks correctly?
I wrote a small C program to assess OpenMP's capability to yield to another task when idle time in a task occurs (e.g. wait for communicated data):

#include <stdio.h>
#include <sys/time.h>
#include <omp.h>

#define NTASKS 10

double wallClockTime(void) {

    struct timeval t;

    gettimeofday(&t, NULL);

    return (double)(t.tv_sec + t.tv_usec/1000000.);
}

void printStatus(char *status, int taskNum, int threadNum) {

#pragma omp critical(printStatus)
    {
        int i;
        for (i = 0; i < taskNum; i++) printf("    ");
        printf(" %s%i \n", status, threadNum);
    }
}

void task(int taskNum) {

    // "r"un task
    printStatus("r", taskNum, omp_get_thread_num());
    sleep(1);

    // "s"leeping task that can yield
    printStatus("s", taskNum, omp_get_thread_num());
    double idleStartTime = wallClockTime();
    while (wallClockTime() < idleStartTime + 1) {
#pragma omp taskyield
    }

    // "c"ontinue task
    printStatus("c", taskNum, omp_get_thread_num());
    sleep(1);
}

int main(int argc, char* argv[]) {

#pragma omp parallel
#pragma omp single nowait
    {
        int i;

        printf("thread %d is master\n\n", omp_get_thread_num());
        for (i = 0; i < NTASKS; i++) printf(" %02d ", i);
        printf("\n");

        for (i = 0; i < NTASKS; i++) {

#pragma omp task untied
            task(i);
        }
    }

    return 0;
}
```

<p>I used Intel C compiler 17.0.4. Here is the output from a run with 3 threads:</p>

```thread 0 is master

 00  01  02  03  04  05  06  07  08  09
 r1
                                     r0
     r2
 s1
                                     s0
     s2
                                 r0
 c1
     c2
                                 s0
                             r0
         r1
             r2
                             s0
                         r0
         s1
             s2
                         s0
                     r0
         c1
             c2
                     s0
                 r0
                 s0
                 c0
                     c0
                         c0
                             c0
                                 c0
                                     c0
```

Thread 1 and 2 do not yield at all, but they stick to their assigned task instead. I would also expect threads 1 and 2 to continue on the suspended untied tasks 04 ... 09, but these are only handled by master thread 0 while the other threads are idle.

Do the tasks have to be issued or yielded in a different way, or is Intel's OpenMP runtime not (yet) capable to handle this? Btw., GNU gcc 4.9.2 does not yield from tasks at all.

答:
I think your code is just fine and this is an implementation issue. In fact in the LLVM OpenMP implementation - which is very much related to Intel's - pushed a commit two weeks ago that fixes your issue. In my tests, clang's current libiomp5.so (built from trunk) was compatible with icc 17.0.4 just by setting LD_LIBRARY_PATH and produces the desired result.

```<code>thread 0 is master

 00  01  02  03  04  05  06  07  08  09
                                     r0
 r2
     r1
                                     s0
                                 r0
 s2
         r2
     s1
             r1
                                 s0
                             r0
         s2
                 r2
             s1
                     r1
                             s0
                         r0
                 s2
                     s1
                 c2
                         s0
                     c1
                         c0
         c2
             c1
                             c0
 c2
     c1
                                 c0
                                     c0
</code>```

I can also confirm that gcc does not yield at all, but haven't looked in detail.

I have no idea if and when the change might be merged into library shipped by Intel.

Update: You are right that the behavior is still not optimal. From briefly looking through the code it seems that libiomp supports the notion of tied tasks, but does not requeue the task during a taskwait but instead just executes another task and retains the context of the suspended task on the stack. I suspect a proper support would require more heavy compiler support (continuations of a sort) rather than just generating library calls.

Again, you are doing everything right, but the compiler / runtime is not sophisticated enough to support what the standard allows (the behavior is fully standards compliant). Also note that for the described current behavior of libiomp, the tasks don't even need to be untied, since they are only queue so far. There doesn't seem to be an easy way to get what you want short of splitting up / chaining tasks.

Body:
I wrote a small C program to assess OpenMP's capability to yield to another task when idle time in a task occurs (e.g. wait for communicated data):

#include <stdio.h>
#include <sys/time.h>
#include <omp.h>

#define NTASKS 10

double wallClockTime(void) {

    struct timeval t;

    gettimeofday(&t, NULL);

    return (double)(t.tv_sec + t.tv_usec/1000000.);
}

void printStatus(char *status, int taskNum, int threadNum) {

#pragma omp critical(printStatus)
    {
        int i;
        for (i = 0; i < taskNum; i++) printf("    ");
        printf(" %s%i \n", status, threadNum);
    }
}

void task(int taskNum) {

    // "r"un task
    printStatus("r", taskNum, omp_get_thread_num());
    sleep(1);

    // "s"leeping task that can yield
    printStatus("s", taskNum, omp_get_thread_num());
    double idleStartTime = wallClockTime();
    while (wallClockTime() < idleStartTime + 1) {
#pragma omp taskyield
    }

    // "c"ontinue task
    printStatus("c", taskNum, omp_get_thread_num());
    sleep(1);
}

int main(int argc, char* argv[]) {

#pragma omp parallel
#pragma omp single nowait
    {
        int i;

        printf("thread %d is master\n\n", omp_get_thread_num());
        for (i = 0; i < NTASKS; i++) printf(" %02d ", i);
        printf("\n");

        for (i = 0; i < NTASKS; i++) {

#pragma omp task untied
            task(i);
        }
    }

    return 0;
}

I used Intel C compiler 17.0.4. Here is the output from a run with 3 threads:

thread 0 is master

 00  01  02  03  04  05  06  07  08  09
 r1
                                     r0
     r2
 s1
                                     s0
     s2
                                 r0
 c1
     c2
                                 s0
                             r0
         r1
             r2
                             s0
                         r0
         s1
             s2
                         s0
                     r0
         c1
             c2
                     s0
                 r0
                 s0
                 c0
                     c0
                         c0
                             c0
                                 c0
                                     c0

Thread 1 and 2 do not yield at all, but they stick to their assigned task instead. I would also expect threads 1 and 2 to continue on the suspended untied tasks 04 ... 09, but these are only handled by master thread 0 while the other threads are idle.

Do the tasks have to be issued or yielded in a different way, or is Intel's OpenMP runtime not (yet) capable to handle this? Btw., GNU gcc 4.9.2 does not yield from tasks at all.

Body:
I think your code is just fine and this is an implementation issue. In fact in the LLVM OpenMP implementation - which is very much related to Intel's - pushed a commit two weeks ago that fixes your issue. In my tests, clang's current libiomp5.so (built from trunk) was compatible with icc 17.0.4 just by setting LD_LIBRARY_PATH and produces the desired result.

thread 0 is master

 00  01  02  03  04  05  06  07  08  09
                                     r0
 r2
     r1
                                     s0
                                 r0
 s2
         r2
     s1
             r1
                                 s0
                             r0
         s2
                 r2
             s1
                     r1
                             s0
                         r0
                 s2
                     s1
                 c2
                         s0
                     c1
                         c0
         c2
             c1
                             c0
 c2
     c1
                                 c0
                                     c0

I can also confirm that gcc does not yield at all, but haven't looked in detail.

I have no idea if and when the change might be merged into library shipped by Intel.

Update: You are right that the behavior is still not optimal. From briefly looking through the code it seems that libiomp supports the notion of tied tasks, but does not requeue the task during a taskwait but instead just executes another task and retains the context of the suspended task on the stack. I suspect a proper support would require more heavy compiler support (continuations of a sort) rather than just generating library calls.

Again, you are doing everything right, but the compiler / runtime is not sophisticated enough to support what the standard allows (the behavior is fully standards compliant). Also note that for the described current behavior of libiomp, the tasks don't even need to be untied, since they are only queue so far. There doesn't seem to be an easy way to get what you want short of splitting up / chaining tasks.


问:
Python script not executing properly from Php
I'm trying to run a python script with Php but it's not running properly when I launch it with Php. This script, here "bot.py" interracts with the instagram api and writes the output as a text file in 'bot1.txt'.

Here is the Php code :

shell_exec("python automation/bot.py");```
</div>
</div>
</p>

<p>And here is the python snippet that writes in the file :</p>

```with open('../botlog/bot1.txt', 'a') as the_file:
                    the_file.write('Followed')
```

My problem is that when I launch it with Php the script runs but doesn't write in the file bot1.txt. When I run the python script with the command line everything works perfectly so I don't understand what's the deal here.
I'm working with MAMP on a local server.
Thank you !

答:
Maybe you should specify your path to php.

```<code>$myPHPScriptPath = realpath(dirname(__FILE__));
</code>```

Then specify the relative path to your python script.

Hope it helps

Body:
I'm trying to run a python script with Php but it's not running properly when I launch it with Php. This script, here "bot.py" interracts with the instagram api and writes the output as a text file in 'bot1.txt'.

Here is the Php code :

shell_exec("python automation/bot.py");

And here is the python snippet that writes in the file :

with open('../botlog/bot1.txt', 'a') as the_file:
                    the_file.write('Followed')

My problem is that when I launch it with Php the script runs but doesn't write in the file bot1.txt. When I run the python script with the command line everything works perfectly so I don't understand what's the deal here.
I'm working with MAMP on a local server.
Thank you !

Body:
Maybe you should specify your path to php.

$myPHPScriptPath = realpath(dirname(__FILE__));

Then specify the relative path to your python script.

Hope it helps


问:
How can I make my \n a new Line in HTML
Basically I have a string with \n and I want to display on a editable textbox in html. My problem is that in HTML i get everything in a new line and it's a big mess.

How can I replace the \n with
 or something like that  to make new lines in html??

JAVA GitLab.getProjectFile() Return this string (it's not this but it's the same format):

```<code>blablabla\nblablabla\nbla bla bla\n
</code>```

In HTML I'm calling like this:

```<code><div style="margin-top:20px;">
   <%
        String data = GitLab.getProjectFile();
    %>
    <%=data%>
</div>
</code>```

答:
You can also solve this problem without having to replace any newlines by using CSS. Just add white-space: pre-line; to the style attribute as follows:

```<code><div style="margin-top:20px; white-space: pre-line;">
    <%
        String data = GitLab.getProjectFile();
    %>
    <%=data%>
</div>
</code>```

One of the advantages of this approach is that you won't have to strip
 tags from the text you retrieve in the textbox.

There are other CSS whitespace options if pre-line isn't quite what you're looking for. You can see a description of them here.

Title: How can I make my \n a new Line in HTML

Body:
Basically I have a string with \n and I want to display on a editable textbox in html. My problem is that in HTML i get everything in a new line and it's a big mess.

How can I replace the \n with
 or something like that  to make new lines in html??

JAVA GitLab.getProjectFile() Return this string (it's not this but it's the same format):

blablabla\nblablabla\nbla bla bla\n

In HTML I'm calling like this:

   <%
        String data = GitLab.getProjectFile();
    %>
    <%=data%>

Body:
You can also solve this problem without having to replace any newlines by using CSS. Just add white-space: pre-line; to the style attribute as follows:

<div style="margin-top:20px; white-space: pre-line;">
    <%
        String data = GitLab.getProjectFile();
    %>
    <%=data%>
</div>

One of the advantages of this approach is that you won't have to strip <br/> tags from the text you retrieve in the textbox.

There are other CSS whitespace options if pre-line isn't quite what you're looking for. You can see a description of them here.


问:
Is it good practice to leave MySQL's "auto commit" mode disabled across a web application?
Regarding MySQL and InnoDB tables, is it considered good practice to globally keep the autocommit mode disabled, so that all SQL statements throughout your code have to be explicitly committed? Does this introduce any overhead or other adverse conditions?

答:
It doesn't add any overhead. Every autocommit transaction does the same work as a transaction with explicit begin and commit, but the autocommit transactions commit immediately after each SQL statement is done.

There is no downside to leaving autocommit enabled. If you explicitly start a transaction, this turns off autocommit in that session only until you commit. Then it goes back to autocommit until you explicitly begin another transaction.

The risk of turning off autocommit globally as @Sherry points out, is that you may have code somewhere that doesn't explicitly commit promptly. This leaves the transaction going when you may not have intended to do so. This makes the session keep a hold of locks, possibly blocking other sessions. It also inhibits timely cleanup of the rollback segment.

In my applications, I stick with autocommit, unless I have a specific case where I want multiple statements to be collected into a single transaction. Then I just start a transaction for that specific case. In any case, I leave the global autocommit enabled.