问:
Java webservlet API: HTTP 400 error - bad request
I have an API in JAVA.

This is the form where I call it:

```<code><form action="select_hcp" method="POST">
   <div>
      <textarea rows="4" cols="100" name="data"></textarea>
   </div>
   <div>
      <input type="submit" class="btn btn-info" value="select_hcp" />
   </div>
</form>
</code>```

This is the code of my API webservlet.

```<code>@WebServlet("/select_hcp")

public class select_hcp extends CEFCYServlet {
    private static final long serialVersionUID = 1L;

    public select_hcp() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HashMap<String, String> jsonData;
        // If there was a problem parsing the JSON data
        try {
            if ((jsonData = parseSTJSON(getJSONString(request), response)) == null) {
                return;
            }
            // Get data from json
            String hcp_name = jsonData.get("hcp_name");
            System.out.println(hcp_name);
            // insert data to db
            JSONObject jObj = new select_data().hcp(hcp_name);
            // Auditing
            // Set the success message with the results
            setSuccessMessage(response, jObj);
        } catch (Exception e) {
            System.out.println("error");
            setErrorMessage(response, 400, "Bad Request", "Could not select data. Check the data given as input.");
            return;
        }

    }
}
</code>```

When it goes to JSONObject jObj = new select_data().hcp(hcp_name); I get http 400 error: Bad request.

Method hcp in select_data is the one below. In the code above I have import dbmodule.select_data; in order to see it.

```<code>public JSONObject hcp(String hcp_name) {
        JSONObject obj = null;
        Connection conn = this.getDBMySQLCon();
        ResultSet rs = null;
        String queryString = "{CALL select_hcp(?)}";
        PreparedStatement preparedStmt = null;
        try {
            preparedStmt = conn.prepareCall(queryString);
            preparedStmt.setInt(1, Integer.valueOf(hcp_name));

            boolean results = preparedStmt.execute();
            int rowsAffected = 0;
            // Protects against lack of SET NOCOUNT in stored procedure
            while (results || rowsAffected != -1) {
                if (results) {
                    rs = preparedStmt.getResultSet();
                    break;
                } else {
                    rowsAffected = preparedStmt.getUpdateCount();
                }
                results = preparedStmt.getMoreResults();
            }
            int i = 0;
            obj = new JSONObject();
            while (rs.next()) {
                JSONObject nested_obj = new JSONObject();
                nested_obj.put("hp_name_or_legal_org", rs.getString("hp_name_or_legal_org"));
                nested_obj.put("telephone_no", rs.getString("telephone_no"));
                nested_obj.put("email", rs.getString("email"));
                nested_obj.put("hcp_id", rs.getString("hcp_id"));
                obj.put("hcp" + i, nested_obj);
                i++;
            }
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
        return (obj != null) ? obj : null;
    }
</code>```

CALL select_hcp(?) is a stored procedure in a mysql database. When I run this procedure in phpmyadmin is working properly. The problem is in my java code. I double checked the input json string and is correct.

This is the table hcp in my database, where hcp_is is type INT and all the other are VARCHAR.

Can you help me please?

答:
In the select_hcp servlet, use e.printStackTrace() to get the error + stack trace into log. Just System.out.println("error"); only reports there is a problem, but does not say anything about what and where the problem is.

```<code>  // ...
} catch (Exception e) {
    e.printStackTrace(); // instead of System.out.println("error");
    setErrorMessage(response, 400, "Bad Request", "Could not select data. Check the data given as input.");
    return;
}
</code>```

Body:
I have an API in JAVA.

This is the form where I call it:

<form action="select_hcp" method="POST">

      <textarea rows="4" cols="100" name="data"></textarea>

      <input type="submit" class="btn btn-info" value="select_hcp" />

</form>

This is the code of my API webservlet.

@WebServlet("/select_hcp")

public class select_hcp extends CEFCYServlet {
    private static final long serialVersionUID = 1L;

    public select_hcp() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HashMap<String, String> jsonData;
        // If there was a problem parsing the JSON data
        try {
            if ((jsonData = parseSTJSON(getJSONString(request), response)) == null) {
                return;
            }
            // Get data from json
            String hcp_name = jsonData.get("hcp_name");
            System.out.println(hcp_name);
            // insert data to db
            JSONObject jObj = new select_data().hcp(hcp_name);
            // Auditing
            // Set the success message with the results
            setSuccessMessage(response, jObj);
        } catch (Exception e) {
            System.out.println("error");
            setErrorMessage(response, 400, "Bad Request", "Could not select data. Check the data given as input.");
            return;
        }

    }
}

When it goes to JSONObject jObj = new select_data().hcp(hcp_name); I get http 400 error: Bad request.

Method hcp in select_data is the one below. In the code above I have import dbmodule.select_data; in order to see it.

public JSONObject hcp(String hcp_name) {
        JSONObject obj = null;
        Connection conn = this.getDBMySQLCon();
        ResultSet rs = null;
        String queryString = "{CALL select_hcp(?)}";
        PreparedStatement preparedStmt = null;
        try {
            preparedStmt = conn.prepareCall(queryString);
            preparedStmt.setInt(1, Integer.valueOf(hcp_name));

            boolean results = preparedStmt.execute();
            int rowsAffected = 0;
            // Protects against lack of SET NOCOUNT in stored procedure
            while (results || rowsAffected != -1) {
                if (results) {
                    rs = preparedStmt.getResultSet();
                    break;
                } else {
                    rowsAffected = preparedStmt.getUpdateCount();
                }
                results = preparedStmt.getMoreResults();
            }
            int i = 0;
            obj = new JSONObject();
            while (rs.next()) {
                JSONObject nested_obj = new JSONObject();
                nested_obj.put("hp_name_or_legal_org", rs.getString("hp_name_or_legal_org"));
                nested_obj.put("telephone_no", rs.getString("telephone_no"));
                nested_obj.put("email", rs.getString("email"));
                nested_obj.put("hcp_id", rs.getString("hcp_id"));
                obj.put("hcp" + i, nested_obj);
                i++;
            }
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
        return (obj != null) ? obj : null;
    }

CALL select_hcp(?) is a stored procedure in a mysql database. When I run this procedure in phpmyadmin is working properly. The problem is in my java code. I double checked the input json string and is correct.

This is the table hcp in my database, where hcp_is is type INT and all the other are VARCHAR.

Can you help me please?

Body:
In the select_hcp servlet, use e.printStackTrace() to get the error + stack trace into log. Just System.out.println("error"); only reports there is a problem, but does not say anything about what and where the problem is.

  // ...
} catch (Exception e) {
    e.printStackTrace(); // instead of System.out.println("error");
    setErrorMessage(response, 400, "Bad Request", "Could not select data. Check the data given as input.");
    return;
}


来源: stackexchange

问:
The std::pair in the std::map is returned as const
My example code is

```<code>class A
{
    int a = 0;
public:
    void setA(const int value)
    {
        a = value;
    }
};

std::map<std::string, std::set<A>> Map{{"A", {}}};
Map.rbegin()->second.rbegin()->setA(2);
</code>```

I get the following error: "Member function 'setA' not viable: 'this' argument has type 'const A', but function is not marked const"

My question is why rbegin() returns a const pointer to A? Or why is the std:pair's second a const in the std::map?

答:
All std::set elements are exposed in const fashion. That's because they're both keys and values, and if you could modify keys willy-nilly then you'd ruin the tree structure inside the set.

It is currently not possible to directly modify set elements. You will have to remove then re-insert.

(This has nothing to do with the encapsulating map.)

ContentLicense: CC BY-SA 3.0

Body:
My example code is

class A
{
    int a = 0;
public:
    void setA(const int value)
    {
        a = value;
    }
};

std::map<std::string, std::set> Map{{"A", {}}};
Map.rbegin()->second.rbegin()->setA(2);

I get the following error: "Member function 'setA' not viable: 'this' argument has type 'const A', but function is not marked const"

My question is why rbegin() returns a const pointer to A? Or why is the std:pair's second a const in the std::map?


问:
How do I set a custom Author name in TortoiseSVN locally?
I am using auto props to populate the $Id$ tag with TortoiseSVN but it is using the author name that is the name of the computer, in this case 'Peter'.

I want it to use my name instead of the computer's account name. I am using Vista on this machine. The repo is local to my machine.

Thanks!

答:
TortoiseSVN does not have such a feature. It only asks for a username if the server requests one. Since your repo is local, there is no authentication at all and therefore TSVN doesn't ask for a username/password.
In that case, the windows logon name is used automatically.

Sorry.

ContentLicense: CC BY-SA 2.5


问:
Using Linq to filter an array with bool properties true in to another array
I have an array of type Brick with each brick having an isBroken bool property. How can I use Linq to filter all bricks with isBroken = true into a new array?

答:
I hope this example will explain things more clearly, Let the definition of your class will be like the following:

```<code>public class Brick
{
  public string Name;
  public bool isBroken ;
}
</code>```

And the Array of it's objects is defined like this:

```<code>Brick[] BrickArray =new Brick[]{
                    new Brick(){Name="A",isBroken=true},
                    new Brick(){Name="B",isBroken=true},
                    new Brick(){Name="C",isBroken=false}};
</code>```

Then you can use the .Where to filter the collection like the following:

```<code>var selectedBriks = BrickArray.Where(x=>x.isBroken).ToList();
</code>```

Now the selectedBriks will contains the items with name A and B

Body:
I hope this example will explain things more clearly, Let the definition of your class will be like the following:

public class Brick
{
  public string Name;
  public bool isBroken ;
}

And the Array of it's objects is defined like this:

Brick[] BrickArray =new Brick[]{
                    new Brick(){Name="A",isBroken=true},
                    new Brick(){Name="B",isBroken=true},
                    new Brick(){Name="C",isBroken=false}};

Then you can use the .Where to filter the collection like the following:

var selectedBriks = BrickArray.Where(x=>x.isBroken).ToList();

Now the selectedBriks will contains the items with name A and B


问:
Change text from input id
I'm trying to change the text of whatever is existing with whatever is typed in the input. I try to take it from the id="text" but it doesn't work and just displays text.</p>

```<code><input type="text" class="form-control" id="text" placeholder="Type your text here.....">

<div class="form-group">
    <button>submit</button>
</div>
<div class="form-group" id="response">
    ```Type some text in the above text field, then log the text out here on button click```
</div>

<script>
    $('button').click(function() {
        $("#response").text("#text");
    });
</script>
</code>```

答:
<input type="text" class="form-control" id="text" placeholder="Type your text here.....">

    <button>submit</button>

    ```Type some text in the above text field, then log the text out here on button click```

```

Use $("#text").val() to get value from input

Title: Change text from input id

Body:
I'm trying to change the text of whatever is existing with whatever is typed in the input. I try to take it from the id="text" but it doesn't work and just displays text.

<input type="text" class="form-control" id="text" placeholder="Type your text here.....">

    <button>submit</button>

Type some text in the above text field, then log the text out here on button click

Body:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" id="text" placeholder="Type your text here.....">

  <div class="form-group">
    <button>submit</button>
  </div>
  <div class="form-group" id="response">
    <pre>Type some text in the above text field, then log the text out here on button click</pre>
  </div>

<script>
  $('button').click(function() {
    $("#response").text($("#text").val());
});
</script>

Use $("#text").val() to get value from input


问:
How can I save a directory tree to an array in PHP?
I'm trying to take a directory with the structure:

```<code>top
    folder1
        file1
    folder2
        file1
        file2
</code>```

And save it into an array like:

```<code>array
(
    'folder1' => array('file1'),
    'folder2' => array('file1', 'file2')
)
</code>```

This way, I can easily resuse the tree throughout my site. I've been playing around with this code but it's still not doing what I want:

```<code>private function get_tree()
{
    $uploads  = __RELPATH__ . DS . 'public' . DS . 'uploads';
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads), RecursiveIteratorIterator::SELF_FIRST);
    $output   = array();

    foreach($iterator as $file)
    {
        $relativePath = str_replace($uploads . DS, '', $file);

        if ($file->isDir())
        {
            if (!in_array($relativePath, $output))
                $output[$relativePath] = array();
        }
    }

    return $output;
}
</code>```

答:
Im horrible with recursive functions. But i managed to come up with this..not sure it's what you're looking for

```<code>function tree($path, $top) {
    $ignore = array('cgi-bin', '.', '..' );
    $handle = opendir($path);

    while( ($file = readdir($handle)) !== false ) {

        if( !in_array( $file, $ignore ) ){
            if( is_dir("$path/$file") ) {
                $top[$file] = @ tree("$path/$file", $top[$file]);
            } else {
                $top[] = $file;
            }
        }

    }

    closedir( $handle );
    return $top;
}
</code>```

Assuming your directory tree is

it outputs

```<code>Array
(
    [a] => Array
        (
            [aa] => Array
                (
                    [0] => aa.txt
                )

        )

    [b] => Array
        (
            [0] => bb.txt
        )

    [c] => Array
        (
            [0] => cc.txt
        )

)
</code>```

But, take a break and go watch the eclipse that happens every 300 and something years. You dont want to say 'no' when your kids, grandkids, great-grandkids ask you 'did you know you were alive when the winter solstice eclipse occurred?? did you see it?????"

:)

Body:
I'm trying to take a directory with the structure:

top
    folder1
        file1
    folder2
        file1
        file2

And save it into an array like:

array
(
    'folder1' => array('file1'),
    'folder2' => array('file1', 'file2')
)

This way, I can easily resuse the tree throughout my site. I've been playing around with this code but it's still not doing what I want:

private function get_tree()
{
    $uploads  = __RELPATH__ . DS . 'public' . DS . 'uploads';
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploads), RecursiveIteratorIterator::SELF_FIRST);
    $output   = array();

    foreach($iterator as $file)
    {
        $relativePath = str_replace($uploads . DS, '', $file);

        if ($file->isDir())
        {
            if (!in_array($relativePath, $output))
                $output[$relativePath] = array();
        }
    }

    return $output;
}

Body:
Im horrible with recursive functions. But i managed to come up with this..not sure it's what you're looking for

function tree($path, $top) {
    $ignore = array('cgi-bin', '.', '..' );
    $handle = opendir($path);

    while( ($file = readdir($handle)) !== false ) {

        if( !in_array( $file, $ignore ) ){
            if( is_dir("$path/$file") ) {
                $top[$file] = @ tree("$path/$file", $top[$file]);
            } else {
                $top[] = $file;
            }
        }

    }

    closedir( $handle );
    return $top;
}

Assuming your directory tree is

it outputs

Array
(
    [a] => Array
        (
            [aa] => Array
                (
                    [0] => aa.txt
                )

        )

    [b] => Array
        (
            [0] => bb.txt
        )

    [c] => Array
        (
            [0] => cc.txt
        )

)

But, take a break and go watch the eclipse that happens every 300 and something years. You dont want to say 'no' when your kids, grandkids, great-grandkids ask you 'did you know you were alive when the winter solstice eclipse occurred?? did you see it?????"

:)


问:
Can i add an ActionListener() inside a main method or any method?
```<code>public void Message() {
@Override
public void actionPerformed(ActionEvent e) {
    JOptionPane.showMessageDialog(null, "Hello it is working");
}

}
</code>```

<p>//Message() is a method inside a class.</p>

答:
All methods must be declared inside a class separately. In simple terms, methods are something the object of a certain class can do, and defining them inside another method does not make sense. So in your case,

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

}
@Override
public void actionPerformed(ActionEvent e){
    JOptionPane.showMessageDialog(null, "Hello it is working");
}
</code>```

Edit: This post is worth a read. I have no knowledge about lambda expressions, but it could be what you're looking for :)
Does Java support inner / local / sub methods?

Body:
public void Message() {
@Override
public void actionPerformed(ActionEvent e) {
    JOptionPane.showMessageDialog(null, "Hello it is working");
}

}

//Message() is a method inside a class.

Body:
All methods must be declared inside a class separately. In simple terms, methods are something the object of a certain class can do, and defining them inside another method does not make sense. So in your case,

public void Message (){

}
@Override
public void actionPerformed(ActionEvent e){
    JOptionPane.showMessageDialog(null, "Hello it is working");
}

Edit: This post is worth a read. I have no knowledge about lambda expressions, but it could be what you're looking for :)
Does Java support inner / local / sub methods?


问:
Covariance Matrix showing covariance between each value in vectors
Is there a python function that allows me to compute a n*n auto covariance matrix, displaying the covariance between each combination of the entries in a vector [a1,a2,a3...an]? I can't get np.cov to do that...
I want it to look like this:

```<code>    cov(a1,a1) cov(a1,a2)... cov(a1,an)
    cov(a2,a1) cov(a2,a2)...
    ...
    cov(an,a1) ...           cov(an,an)
</code>```

Any help is appreciated!
Cheers,
Lena

答:
You could use the pandas package.
http://pandas.pydata.org/

Dataframes have a covariance method that computes the covariances between all columns in the DataFrame.

This should roughly be the workflow.

```<code>import pandas as pd
df = pd.DataFrame(your_vector)
cov = df.cov()
</code>```

Cov is now a dataframe that contains the covariences between all the columns in your vector. You can than do what ever analysis you want on the resulting dataframe.

Body:
Is there a python function that allows me to compute a n*n auto covariance matrix, displaying the covariance between each combination of the entries in a vector [a1,a2,a3...an]? I can't get np.cov to do that...
I want it to look like this:

    cov(a1,a1) cov(a1,a2)... cov(a1,an)
    cov(a2,a1) cov(a2,a2)...
    ...
    cov(an,a1) ...           cov(an,an)

Any help is appreciated!
Cheers,
Lena

Body:
You could use the pandas package.
http://pandas.pydata.org/

Dataframes have a covariance method that computes the covariances between all columns in the DataFrame.

This should roughly be the workflow.

import pandas as pd
df = pd.DataFrame(your_vector)
cov = df.cov()

Cov is now a dataframe that contains the covariences between all the columns in your vector. You can than do what ever analysis you want on the resulting dataframe.


问:
Check if specific record exists in one to many tables
I have two tables with one-to-many relation with such structure:

```<code>meeting              meeting_person
+--+------------+    +--+----------+-----------+---------+
|id|meeting_type|    |id|meeting_id|person_type|person_id|
+--+------------+    +--+----------+-----------+---------+
|1 |          1 |    |1 |         1|          1|     100 |
|2 |          2 |    |2 |         1|          1|     101 |
+--+------------+    |3 |         1|          2|     102 |
                     |4 |         2|          3|     103 |
                     +--+----------+-----------+---------+
</code>```

What I want to do is check whether the specific record exists before inserting, and if so warn user about it.

The thing is I need to check whether a meeting with such meeting_type and person_id with person_type exists, and that for all persons.

For example, if with given data I wanted to insert meeting with meeting_type = 1 and such meeting_persons:

person_type = 1 and person_id = 100

person_type = 1 and person_id = 101

person_type = 2 and person_id = 102

then user should see warning.

But if I wanted to insert meeting with meeting_type = 1 and such meeting_persons:

person_type = 1 and person_id = 100

then user should not see warning and records should be inserted.

I just cannot think of way, how to check this.

答:
As phrased, you need to use a trigger for this.  I might suggest changing the data structure to include meeting_type in meeting_person.  Yes, I know that violates normal form.  But if you had it, you could enforce your logic with a simple constraint:

```<code>alter table meeting_person add constraint unq_meetingperson_person_type
    unique (person_id, meeting_type);
</code>```

How can you do this safely?  Use foreign key relationships:

```<code>alter table meeting add constraint unq_meeting_type_id
    unique (type, id);

alter table meeting_person add constraint fk_meetingperson_meetingtype_id
    foreign key (meeting_type, id) references meeting(meeting_type, id);
</code>```

This does incur extra space for the additional (unnecessary) indexes.  It does require including one extra column in meeting_type.  But it does allow you to implement this logic without using triggers.

Body:
I have two tables with one-to-many relation with such structure:

meeting              meeting_person
+--+------------+    +--+----------+-----------+---------+
|id|meeting_type|    |id|meeting_id|person_type|person_id|
+--+------------+    +--+----------+-----------+---------+
|1 |          1 |    |1 |         1|          1|     100 |
|2 |          2 |    |2 |         1|          1|     101 |
+--+------------+    |3 |         1|          2|     102 |
                     |4 |         2|          3|     103 |
                     +--+----------+-----------+---------+

What I want to do is check whether the specific record exists before inserting, and if so warn user about it.

The thing is I need to check whether a meeting with such meeting_type and person_id with person_type exists, and that for all persons.

For example, if with given data I wanted to insert meeting with meeting_type = 1 and such meeting_persons:

person_type = 1 and person_id = 100

person_type = 1 and person_id = 101

person_type = 2 and person_id = 102

then user should see warning.

But if I wanted to insert meeting with meeting_type = 1 and such meeting_persons:

person_type = 1 and person_id = 100

then user should not see warning and records should be inserted.

I just cannot think of way, how to check this.

Body:
As phrased, you need to use a trigger for this.  I might suggest changing the data structure to include meeting_type in meeting_person.  Yes, I know that violates normal form.  But if you had it, you could enforce your logic with a simple constraint:

alter table meeting_person add constraint unq_meetingperson_person_type
    unique (person_id, meeting_type);

How can you do this safely?  Use foreign key relationships:

alter table meeting add constraint unq_meeting_type_id
    unique (type, id);

alter table meeting_person add constraint fk_meetingperson_meetingtype_id
    foreign key (meeting_type, id) references meeting(meeting_type, id);

This does incur extra space for the additional (unnecessary) indexes.  It does require including one extra column in meeting_type.  But it does allow you to implement this logic without using triggers.


问:
Pandas: How to find a particular pattern in a dataframe column?
I'd like to find a particular pattern in a pandas dataframe column, and return the corresponding index values in order to subset the dataframe.

Here's a sample dataframe with a possible pattern:

Snippet to produce dataframe:

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

Observations = 10
Columns = 2
np.random.seed(123)
df = pd.DataFrame(np.random.randint(90,110,size=(Observations, Columns)),
                  columns = ['ColA','ColB'])
datelist = pd.date_range(pd.datetime(2017, 7, 7).strftime('%Y-%m-%d'),
                         periods=Observations).tolist()
df['Dates'] = datelist
df = df.set_index(['Dates'])

pattern = [100,90,105]
print(df)
</code>```

Dataframe:

```<code>            ColA  ColB
Dates
2017-07-07   103    92
2017-07-08    92    96
2017-07-09   107   109
2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99
2017-07-13    90   104
2017-07-14    90   105
2017-07-15   109   104
2017-07-16    94    90
</code>```

Here, the pattern of interest occurs in Column A on the dates 2017-07-10 to 2017-07-12, and that's what I'd like to end up with:

Desired output:

```<code>2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99
</code>```

If the same pattern occurs several times, I would like to subset the dataframe the same way, and also count how many times the pattern occurs, but I hope that's more straight forward as long as I get the first step sorted out.

Thank you for any suggestions!

答:
Using the magic of list comprehensions:</p>

```<code>[df.index[i - len(pattern)] # Get the datetime index
 for i in range(len(pattern), len(df)) # For each 3 consequent elements
 if all(df['ColA'][i-len(pattern):i] == pattern)] # If the pattern matched

# [Timestamp('2017-07-10 00:00:00')]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to find a particular pattern in a pandas dataframe column, and return the corresponding index values in order to subset the dataframe.

Here's a sample dataframe with a possible pattern:

Snippet to produce dataframe:

import pandas as pd
import numpy as np

Observations = 10
Columns = 2
np.random.seed(123)
df = pd.DataFrame(np.random.randint(90,110,size=(Observations, Columns)),
                  columns = ['ColA','ColB'])
datelist = pd.date_range(pd.datetime(2017, 7, 7).strftime('%Y-%m-%d'),
                         periods=Observations).tolist()
df['Dates'] = datelist
df = df.set_index(['Dates'])

pattern = [100,90,105]
print(df)

Dataframe:

            ColA  ColB
Dates
2017-07-07   103    92
2017-07-08    92    96
2017-07-09   107   109
2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99
2017-07-13    90   104
2017-07-14    90   105
2017-07-15   109   104
2017-07-16    94    90

Here, the pattern of interest occurs in Column A on the dates 2017-07-10 to 2017-07-12, and that's what I'd like to end up with:

Desired output:

2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99

If the same pattern occurs several times, I would like to subset the dataframe the same way, and also count how many times the pattern occurs, but I hope that's more straight forward as long as I get the first step sorted out.

Thank you for any suggestions!

Body:
Using the magic of list comprehensions:

[df.index[i - len(pattern)] # Get the datetime index
 for i in range(len(pattern), len(df)) # For each 3 consequent elements
 if all(df['ColA'][i-len(pattern):i] == pattern)] # If the pattern matched

# [Timestamp('2017-07-10 00:00:00')]


问:
Move layouts up when soft keyboard is shown?
I have a few elements in a RelativeView with the align bottom attribute set, when the soft keyboard comes up the elements are hidden by the soft keyboard.

I would like them to move up so that if there is enough screen space they are shown above the keyboard, or to make the section above the keyboard scrollable so the user can still see the elements.

Any ideas on how to approach this?

答:
if you are in fragments then you  have to add the below code to your onCreate on your activity it solves issue for me</p>

```<code>getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
</code>```

Body:
if you are in fragments then you  have to add the below code to your onCreate on your activity it solves issue for me

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);


问:
For loop within a foreach loop java
So i have this code segment. searchStudentWith2RUCode() returns an Arraylist of Student objects. Student objects have various attributes such as forename, lastname, cprnumber, gpa etc.

```<code> public void assignStudents() throws ClassNotFoundException, SQLException {
     ArrayList<Student> notYetAssignedStudents = searchStudentsWith2RUCode();
     ArrayList<Student> assignedStudents = new ArrayList<>()
          for (Education edu : eduList) {

               for (int i = 0; i < edu.getAmountOfFreeSpacesInEdu(); i++) {
                  assignedStudents.add(notAssignedStudents.get(i));
                  setAssignedStudentsAdmitted(assignedStudents.get(i).getCPR, assignedStudents.get(i).getPrio, assignedStudents.get(i).eduNumber)
        }
    }
}
</code>```

setAssignedStudentsAdmitted updates my database and should set the field "sagsbehandling" in my table "students" as "Optaget" at each admitted student. However this doesnt work.
Im suspecting my for loops, but Im lost, i can't figure out why it doesn't work.

Here is my setAssignedStudentsAdmitted method:

```<code> public void setAssignedStudentsAdmitted(String CPR, int prio, int eduNumber) throws ClassNotFoundException, SQLException {

    //Declare a UPDATE statement
    String updateStmt
            = "UPDATE Students SET sagsbehandling='Optaget' WHERE cprnr ='" + CPR + "' AND prio='" + prio + "' AND eduNumber='" + eduNumber + "';";

    //Execute UPDATE operation
    try {
        DatabaseController.dbExecuteUpdate(updateStmt);
    } catch (SQLException e) {
        System.out.print("Error occurred while DELETE Operation: " + e);
        throw e;
    }
}
</code>```

}

And here is my dbExecuteUpdate method that is called in setAssignedStudentsAdmitted

```<code>    public static void dbExecuteUpdate(String sqlStmt) throws SQLException, ClassNotFoundException {
    //Declare statement as null
    Statement stmt = null;
    try {
        //Connect to DB (Establish Postgres Connection)
        databaseConnect();
        //Create Statement
        stmt = conn.createStatement();
        //Run executeUpdate operation with given sql statement
        stmt.executeUpdate(sqlStmt);
    } catch (SQLException e) {
        System.out.println("Problem occurred at executeUpdate operation : " + e);
        throw e;
    } finally {
        if (stmt != null) {
            //Close statement
            stmt.close();
        }
        //Close connection
        databaseDisconnect();
    }
}
</code>```

It builds succesfully, but changes nothing in my Database.

答:
```<code>//Declare a UPDATE statement
    String updateStmt
            = "UPDATE Students SET sagsbehandling='Optaget' WHERE cprnr ='" + CPR + "' AND prio='" + prio + "' AND eduNumber='" + eduNumber + "';";
</code>```

The scope updateStmt is within setAssignedStudentsAdmitted method. So, how are you passing it in below method call ?

```<code> public static void dbExecuteUpdate(String sqlStmt)
         throws SQLException, ClassNotFoundException {
</code>```

Title: For loop within a foreach loop java

Body:
So i have this code segment. searchStudentWith2RUCode() returns an Arraylist of Student objects. Student objects have various attributes such as forename, lastname, cprnumber, gpa etc.

 public void assignStudents() throws ClassNotFoundException, SQLException {
     ArrayList<Student> notYetAssignedStudents = searchStudentsWith2RUCode();
     ArrayList<Student> assignedStudents = new ArrayList<>()
          for (Education edu : eduList) {

               for (int i = 0; i < edu.getAmountOfFreeSpacesInEdu(); i++) {
                  assignedStudents.add(notAssignedStudents.get(i));
                  setAssignedStudentsAdmitted(assignedStudents.get(i).getCPR, assignedStudents.get(i).getPrio, assignedStudents.get(i).eduNumber)
        }
    }
}

setAssignedStudentsAdmitted updates my database and should set the field "sagsbehandling" in my table "students" as "Optaget" at each admitted student. However this doesnt work.
Im suspecting my for loops, but Im lost, i can't figure out why it doesn't work.

Here is my setAssignedStudentsAdmitted method:

 public void setAssignedStudentsAdmitted(String CPR, int prio, int eduNumber) throws ClassNotFoundException, SQLException {

    //Declare a UPDATE statement
    String updateStmt
            = "UPDATE Students SET sagsbehandling='Optaget' WHERE cprnr ='" + CPR + "' AND prio='" + prio + "' AND eduNumber='" + eduNumber + "';";

    //Execute UPDATE operation
    try {
        DatabaseController.dbExecuteUpdate(updateStmt);
    } catch (SQLException e) {
        System.out.print("Error occurred while DELETE Operation: " + e);
        throw e;
    }
}

}

And here is my dbExecuteUpdate method that is called in setAssignedStudentsAdmitted

    public static void dbExecuteUpdate(String sqlStmt) throws SQLException, ClassNotFoundException {
    //Declare statement as null
    Statement stmt = null;
    try {
        //Connect to DB (Establish Postgres Connection)
        databaseConnect();
        //Create Statement
        stmt = conn.createStatement();
        //Run executeUpdate operation with given sql statement
        stmt.executeUpdate(sqlStmt);
    } catch (SQLException e) {
        System.out.println("Problem occurred at executeUpdate operation : " + e);
        throw e;
    } finally {
        if (stmt != null) {
            //Close statement
            stmt.close();
        }
        //Close connection
        databaseDisconnect();
    }
}

It builds succesfully, but changes nothing in my Database.

Body:
//Declare a UPDATE statement
    String updateStmt
            = "UPDATE Students SET sagsbehandling='Optaget' WHERE cprnr ='" + CPR + "' AND prio='" + prio + "' AND eduNumber='" + eduNumber + "';";

The scope updateStmt is within setAssignedStudentsAdmitted method. So, how are you passing it in below method call ?

 public static void dbExecuteUpdate(String sqlStmt)
         throws SQLException, ClassNotFoundException {


问:
Left circular shift in Matlab for each row of a matrix of a different number of positions
I have a matrix A in Matlab of dimension mxn composed of zeros and ones, and a matrix J of dimension mx1 reporting some integers from {1,...,n}.

I want to construct a matrix B of dimension mxn such that for

(1) B(1,:)=A(1,:)

(2) for i=2,...,m, B(i,:) is obtained by shifting A(i,:) LEFT circular of a number of positions equal to (J(1)-1)+ (J(2)-1)+...+ (J(i-1)-1)

This code does what I want

```<code>m=4;
n=5;
A=[1 0 1 1 0; ...
   0 1 0 0 1; ...
   1 1 0 0 0; ...
   0 0 0 0 1;
J=[2;1;5;8];
B=zeros(m,n);
B(1,:)=A(1,:);

foridx=cumsum(J); %mx1
shift=foridx-(1:1:m).'; %mx1
v=shift(1:m-1); %(m-1)x1

for i=2:m
    B(i,:)=(circshift((A(i,:)).', -v(i-1),1)).';
end
</code>```

I would like to avoid the final loop. I like the answer here by Divakar but it is for a right circular shift.

```<code>Arelevant=A(2:end,:);
idx0 = mod(bsxfun(@plus,n-v(:),1:n)-1,n);
out = Arelevant(bsxfun(@plus,(idx0*(m-1)),(1:(m-1))'));
B(2:end,:)=out;
</code>```

Could you help me to have something similar for a left circular shift?

答:
Here is a little trick to perform this operation without loop.

I use an fft in order to shift each line.

```<code>m=4;
n=5;
A=[1 0 1 1 0; ...
   0 1 0 0 1; ...
   1 1 0 0 0; ...
   0 0 0 0 1;]
J=[2;1;5;8];

foridx=cumsum(J); %mx1
shift=foridx-(1:1:m).'; %mx1
v=[0;shift(1:m-1)]; %(m-1)x1
L=real(round(ifft(fft(A,[],2) .* exp(2i*pi/n*v*(0:m)) ,[],2))) %left shift
R=real(round(ifft(fft(A,[],2) .* exp(-2i*pi/n*v*(0:m)) ,[],2))) %right shift
</code>```

Body:
I have a matrix A in Matlab of dimension mxn composed of zeros and ones, and a matrix J of dimension mx1 reporting some integers from {1,...,n}.

I want to construct a matrix B of dimension mxn such that for

(1) B(1,:)=A(1,:)

(2) for i=2,...,m, B(i,:) is obtained by shifting A(i,:) LEFT circular of a number of positions equal to (J(1)-1)+ (J(2)-1)+...+ (J(i-1)-1)

This code does what I want

m=4;
n=5;
A=[1 0 1 1 0; ...
   0 1 0 0 1; ...
   1 1 0 0 0; ...
   0 0 0 0 1;
J=[2;1;5;8];
B=zeros(m,n);
B(1,:)=A(1,:);

foridx=cumsum(J); %mx1
shift=foridx-(1:1:m).'; %mx1
v=shift(1:m-1); %(m-1)x1

for i=2:m
    B(i,:)=(circshift((A(i,:)).', -v(i-1),1)).';
end

I would like to avoid the final loop. I like the answer here by Divakar but it is for a right circular shift.

Arelevant=A(2:end,:);
idx0 = mod(bsxfun(@plus,n-v(:),1:n)-1,n);
out = Arelevant(bsxfun(@plus,(idx0*(m-1)),(1:(m-1))'));
B(2:end,:)=out;

Could you help me to have something similar for a left circular shift?

Body:
Here is a little trick to perform this operation without loop.

I use an fft in order to shift each line.

m=4;
n=5;
A=[1 0 1 1 0; ...
   0 1 0 0 1; ...
   1 1 0 0 0; ...
   0 0 0 0 1;]
J=[2;1;5;8];

foridx=cumsum(J); %mx1
shift=foridx-(1:1:m).'; %mx1
v=[0;shift(1:m-1)]; %(m-1)x1
L=real(round(ifft(fft(A,[],2) .* exp(2i*pi/n*v*(0:m)) ,[],2))) %left shift
R=real(round(ifft(fft(A,[],2) .* exp(-2i*pi/n*v*(0:m)) ,[],2))) %right shift


问:
How do I display either body or file from content
I am a new in Drupal. I want your help for doing this please help

I have created one Content type with fields( Title, Body, File) and also added content through this content type. But Some of the content didn't have file filed and some of the content having the only file. In the view, I want to show both either body or file. if suppose file field is empty then it should display the body of the same content.

Thanks.

答:
You could do this by creating a custom node template for particular content type. So if you have a content type 'news', for example, the you can create a node template for this content type and customized the front-end display of the content. See below how it would work.

As per the Drupal theme suggestions, create a node template, named, node--news.tpl.php (copying the existing node.tpl.php file) in your custom (active) theme directory under the templates folder. On this template, you will be able to access the $node object variable, containing complete node information including fields and data.

Suppose your fields are field_image and body then replace your template's code print render($content); with the following lines:

```<code>if(!empty($content['body']){
print render($content['body']);
} else {
print render($content['field_image']);
}
</code>```

For more details: https://www.drupal.org/node/1323842
Hope this help!

Body:
You could do this by creating a custom node template for particular content type. So if you have a content type 'news', for example, the you can create a node template for this content type and customized the front-end display of the content. See below how it would work.

As per the Drupal theme suggestions, create a node template, named, node--news.tpl.php (copying the existing node.tpl.php file) in your custom (active) theme directory under the templates folder. On this template, you will be able to access the $node object variable, containing complete node information including fields and data.

Suppose your fields are field_image and body then replace your template's code print render($content); with the following lines:

if(!empty($content['body']){
print render($content['body']);
} else {
print render($content['field_image']);
}

For more details: https://www.drupal.org/node/1323842
Hope this help!


问:
Why can't I find the ID using the mgo library of golang?
I am using mgo library for mongo operationg in golang and here is my code :

```<code>session.SetMode(mgo.Monotonic, true)
coll := session.DB("aaaw_web").C("cron_emails")
var result Result
fmt.Printf("%v", message.ID)
err = coll.FindId(bson.ObjectId(message.ID)).One(&result)
fmt.Printf("%v", result)
fmt.Println(err)
</code>```

I am getting this output :

```<code>595f2c1a6edcba0619073263
{ObjectIdHex("") 0   0  0    0 {         0    false 0    } 0 0 0  0 0 0 0}
ObjectIDs must be exactly 12 bytes long (got 24)
not found
</code>```

But I checked, document exists in mongo, but getting here no result, any idea what am i missing ...

答:
As the error message hints, an object id is exactly 12 bytes long (12 bytes of data). The 24 char long ID you see printed is the hexadecimal representation of the 12 bytes of the ID (1 byte => 2 hexa digits).

Use the bson.ObjectIdHex() function to obtain a value of bson.ObjectId if the hex representation is available.

```<code>err = coll.FindId(bson.ObjectIdHex(message.ID)).One(&result)
</code>```

For the reverse direction, you may use the ObjectId.Hex() method, detailed in this answer: Obtain ObjectIdHex value from mgo query

What you did in your code is a simple type conversion (given that message.ID is of type string), and the syntax is valid because the underlying type of bson.ObjectId is string, so that basically interprets the 24 characters as bson.ObjectId type, but it is an invalid ObjectId value because it will be 24 bytes and not 12.

Body:
I am using mgo library for mongo operationg in golang and here is my code :

session.SetMode(mgo.Monotonic, true)
coll := session.DB("aaaw_web").C("cron_emails")
var result Result
fmt.Printf("%v", message.ID)
err = coll.FindId(bson.ObjectId(message.ID)).One(&result)
fmt.Printf("%v", result)
fmt.Println(err)

I am getting this output :

595f2c1a6edcba0619073263
{ObjectIdHex("") 0   0  0    0 {         0    false 0    } 0 0 0  0 0 0 0}
ObjectIDs must be exactly 12 bytes long (got 24)
not found

But I checked, document exists in mongo, but getting here no result, any idea what am i missing ...

Body:
As the error message hints, an object id is exactly 12 bytes long (12 bytes of data). The 24 char long ID you see printed is the hexadecimal representation of the 12 bytes of the ID (1 byte => 2 hexa digits).

Use the bson.ObjectIdHex() function to obtain a value of bson.ObjectId if the hex representation is available.

err = coll.FindId(bson.ObjectIdHex(message.ID)).One(&result)

For the reverse direction, you may use the ObjectId.Hex() method, detailed in this answer: Obtain ObjectIdHex value from mgo query

What you did in your code is a simple type conversion (given that message.ID is of type string), and the syntax is valid because the underlying type of bson.ObjectId is string, so that basically interprets the 24 characters as bson.ObjectId type, but it is an invalid ObjectId value because it will be 24 bytes and not 12.


问:
Symfony2 LiipImagineBundle path cache probleme
I've setup a LiipImagineBundle configuration on a linux computer (xubuntu 14.10) :

routing.yml

```<code>_liip_imagine:
    resource: "@LiipImagineBundle/Resources/config/routing.xml"
</code>```

config.yml

```<code>liip_imagine:
    resolvers:
       default:
          web_path: ~

    filter_sets:
        cache: ~
        dashboard_thumb:
            quality: 75
            filters:
                thumbnail: { size: [60, 60], mode: outbound }
</code>```

and in my twig template :

```<code><img src="{{ asset(company.logo.getPath) | imagine_filter('dashboard_thumb') }}">
</code>```

All sources images are under web/uploads path
This was working fine, image thumbnails are generated under web/media/cache/dashboard_thumb/uploads/

My source files are stored under an USB stick, and i lanch server with server:run commande (so under 127.0.0.1:8000)

But recently, i lanched the server under another computer (linux mint 17) and then, image cache are not generated anymore.

when i look at the generated html source, file path for images are :

```<code>http://127.0.0.1:8000/media/cache/resolve/dashboard_thumb/uploads/myimage.png
</code>```

so i dont know why there is a 'resolve' in the path

Other thing, if i launch the command :

```<code>liip:imagine:cache:resolve uploads/myimage.png
</code>```

the path and image web/media/cache/dashboard_thumb/uploads/myimage.png are well created

why this doesnt work automatically?

Thanks.

答:
... so i dont know why there is a 'resolve' in the path

If You do not have a cache for your image, LiipImagineBundle (imagine_filter in your case) generates a route according this rule

```<code>liip_imagine_filter:
    path: /media/cache/resolve/{filter}/{path}
    defaults:
        _controller: '%liip_imagine.controller.filter_action%'
    methods:
        - GET
    requirements:
        filter: '[A-z0-9_-]*'
        path: .+
</code>```

, and your request handles by ImagineController  https://github.com/liip/LiipImagineBundle/blob/1.0/Controller/ImagineController.php

So, You see not image path, but route. Controller generates the cache and your second request to this image will give you actually path to image.

There is a problem, if your need to attach image to mail message, You have to resolve image before attaching this one.

Also if cache not generates anymore, the problem maybe in your web server configuration. Imagine that Your Nginx decides that web/media/cache/*   is static content, so, the route web/media/cache/resolve just not working.

Body:
I've setup a LiipImagineBundle configuration on a linux computer (xubuntu 14.10) :

routing.yml

_liip_imagine:
    resource: "@LiipImagineBundle/Resources/config/routing.xml"

config.yml

liip_imagine:
    resolvers:
       default:
          web_path: ~

    filter_sets:
        cache: ~
        dashboard_thumb:
            quality: 75
            filters:
                thumbnail: { size: [60, 60], mode: outbound }

and in my twig template :

All sources images are under web/uploads path
This was working fine, image thumbnails are generated under web/media/cache/dashboard_thumb/uploads/

My source files are stored under an USB stick, and i lanch server with server:run commande (so under 127.0.0.1:8000)

But recently, i lanched the server under another computer (linux mint 17) and then, image cache are not generated anymore.

when i look at the generated html source, file path for images are :

http://127.0.0.1:8000/media/cache/resolve/dashboard_thumb/uploads/myimage.png

so i dont know why there is a 'resolve' in the path

Other thing, if i launch the command :

liip:imagine:cache:resolve uploads/myimage.png

the path and image web/media/cache/dashboard_thumb/uploads/myimage.png are well created

why this doesnt work automatically?

Thanks.

Body:
... so i dont know why there is a 'resolve' in the path

If You do not have a cache for your image, LiipImagineBundle (imagine_filter in your case) generates a route according this rule

liip_imagine_filter:
    path: /media/cache/resolve/{filter}/{path}
    defaults:
        _controller: '%liip_imagine.controller.filter_action%'
    methods:
        - GET
    requirements:
        filter: '[A-z0-9_-]*'
        path: .+

, and your request handles by ImagineController  https://github.com/liip/LiipImagineBundle/blob/1.0/Controller/ImagineController.php

So, You see not image path, but route. Controller generates the cache and your second request to this image will give you actually path to image.

There is a problem, if your need to attach image to mail message, You have to resolve image before attaching this one.

Also if cache not generates anymore, the problem maybe in your web server configuration. Imagine that Your Nginx decides that web/media/cache/*   is static content, so, the route web/media/cache/resolve just not working.


问:
Azure Data Warehouse Insert to Huge Table
The agreed pattern to insert new data into an already existing table in Azure Data Warehouse seems to be...

```<code>create table dbo.MyTable_New
with (distribution = round_robin)
as

select
    Col1
    ,Col2
from dbo.MyTable

union all

select
    Col1
    ,Col2
from dbo.MyNewStuff;
</code>```

Now, what we are seeing is that on really large tables this will degrade over time, and it's obvious why you are reading everything you have already, and re-inserting it.. this seems sub-optimal to me...

Does anyone have any alternative approaches that they have seen work for them, i am thinking of things like partition switching for example...

答:
Agreed with who?  CTAS can be an effective option, but it really depends on your data volumes, SLAs, business processes etc.  If you are inserting small volumes into an already large table for example, I'm not sure CTAS makes sense, why not INSERT?  You can use partition switching in Azure SQL Data Warehouse (eg here).  Other options include Azure Data Factory, SSIS (which now supports Azure SQL Data Warehouse), Polybase, plain INSERT etc

Please review the following article which offers a number of strategies for loading data into Azure SQL Data Warehouse:

https://blogs.msdn.microsoft.com/sqlcat/2017/05/17/azure-sql-data-warehouse-loading-patterns-and-strategies/

Body:
The agreed pattern to insert new data into an already existing table in Azure Data Warehouse seems to be...

create table dbo.MyTable_New
with (distribution = round_robin)
as

select
    Col1
    ,Col2
from dbo.MyTable

union all

select
    Col1
    ,Col2
from dbo.MyNewStuff;

Now, what we are seeing is that on really large tables this will degrade over time, and it's obvious why you are reading everything you have already, and re-inserting it.. this seems sub-optimal to me...

Does anyone have any alternative approaches that they have seen work for them, i am thinking of things like partition switching for example...


问:
How Google App Engine limit Python?
Does anybody know, how GAE limit Python interpreter? For example, how they block IO operations, or URL operations.

Shared hosting also do it in some way?

答:
I found this site

that has some pretty decent information.  What exactly are you trying to do?

Here

FRESH!

Look here: http://code.google.com/appengine/docs/python/runtime.html

Your IO Operations are limited as follows (beyond disabled modules):

App Engine records how much of each resource an application uses in a calendar day, and considers the resource depleted when this amount reaches the app's quota for the resource. A calendar day is a period of 24 hours beginning at midnight, Pacific Time. App Engine resets all resource measurements at the beginning of each day, except for Stored Data which always represents the amount of datastore storage in use.

When an app consumes all of an allocated resource, the resource becomes unavailable until the quota is replenished. This may mean that your app will not work until the quota is replenished.

An application can determine how much CPU time the current request has taken so far by calling the Quota API. This is useful for profiling CPU-intensive code, and finding places where CPU efficiency can be improved for greater cost savings. You can measure the CPU used for the entire request, or call the API before and after a section of code then subtract to determine the CPU used between those two points.

Resource|   Free Default Quota| Billing Enabled Default Quota
Blobstore |Stored Data| 1 GB|   1 GB free; no maximum
Resource    |Billing Enabled| Default Quota
Daily Limit|    Maximum Rate
Blobstore API Calls |140,000,000 calls| 72,000 calls/minute

Hmm my table isn't that good, but hopefully still readable.

EDIT:  OK, I understand.  But sir, you did not have to use the "f" word.  :)  And you know, it's kinda like the whole 'teach a man to fish' scenario.  Google is who I always ask and that's why I'm answering questions here for fun.

EDIT AGAIN:  OK that made more sense before the comment was tooked.  So I went and answered the question a little more.  I hope it helps.

Title: How Google App Engine limit Python?


问:
Heroku keys add command does not add keys
Was trying to deploy a python app on heroku using heroku git and I had a public key error so I tried to create a new one from scratch using

```<code>heroku keys:add
</code>```

And it returned this error

```<code>EACCES: spawn EACCES
</code>```

At first I thought this was a permission problem so I went with sudo, but this also did nothing. Nothing has happened even after fiddling a bit with granting user with write access in the ~/.ssh folder. Does anyone know what's the proper procedure to solve this?

答:
On Ubuntu I fixed this problem by removing it via snap

sudo snap remove heroku

and installing it using second way (ubuntu-12-and-below)

wget -qO- https://cli-assets.heroku.com/install-ubuntu.sh | sh

Body:
Was trying to deploy a python app on heroku using heroku git and I had a public key error so I tried to create a new one from scratch using

heroku keys:add

And it returned this error

EACCES: spawn EACCES

At first I thought this was a permission problem so I went with sudo, but this also did nothing. Nothing has happened even after fiddling a bit with granting user with write access in the ~/.ssh folder. Does anyone know what's the proper procedure to solve this?


问:
Is it possible to combine NEAR and FORMSOF together in a fulltext search?
I have this:

SELECT * FROM AwesomePeople WHERE CONTAINS(Name, 'NEAR(("Nathan", "Fillion"), MAX, TRUE)')

But I want to combine it so it uses my thesaurus of words to look at alternatives for Nathan and Fillion.

I can do this:

SELECT * FROM AwesomePeople WHERE CONTAINS(Name, 'FORMSOF (THESAURUS, "Nathan"))

But I don't know how to search for 2 words, or make it do FORMSOF and NEAR together in a single query. I have tried a few combinations but am out of luck.

Any ideas?

答:
Following will work great. It is more powerful.</p>

```<code>SELECT  * FROM AwesomePeople AS C INNER JOIN
CONTAINSTABLE(AwesomePeople ,name, 'ISABOUT (
    FORMSOF(Thesaurus, "Nathan"),
    FORMSOF(Thesaurus, "Fillion"))') AS K
ON C.ID = K.[KEY];
</code>```

Body:
Following will work great. It is more powerful.

SELECT  * FROM AwesomePeople AS C INNER JOIN
CONTAINSTABLE(AwesomePeople ,name, 'ISABOUT (
    FORMSOF(Thesaurus, "Nathan"),
    FORMSOF(Thesaurus, "Fillion"))') AS K
ON C.ID = K.[KEY];


问:
How to create a circular progress bar over a image with only css?
I´m trying to create a circular progress bar over a image, like the image attached.

I´d like when 100%, hide progress. Any help?

答:
There's a plugin that's capable of doing it: jQuery.knob.

$(function() {
  $(".knob").knob();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-Knob/1.2.13/jquery.knob.min.js"></script>
<input class="knob" data-width="150" data-width="100" data-displayInput="false" data-displayPrevious="true" data-fgColor="#87ceeb" data-skin="tron" data-thickness="15" value="75" /></code>```

If you want it animated, you can change the value of the input! Just take your mouse over the knob and use your mouse wheel to scroll it. Or see it animated here: jQuery Knob update value with animate

Body:
There's a plugin that's capable of doing it: jQuery.knob.

$(function() {
  $(".knob").knob();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-Knob/1.2.13/jquery.knob.min.js"></script>
<input class="knob" data-width="150" data-width="100" data-displayInput="false" data-displayPrevious="true" data-fgColor="#87ceeb" data-skin="tron" data-thickness="15" value="75" />

If you want it animated, you can change the value of the input! Just take your mouse over the knob and use your mouse wheel to scroll it. Or see it animated here: jQuery Knob update value with animate


问:
How can I put an async function inside a function?
This is the code I'm using. It doesn't work because client.getPosts is async. So my question is, how can I make it work? client.getPosts is from the wordpress npm module so I cannot change it.</p>

```<code>// FUNCTIONS

function getAllPosts() {
    return client
        .getPosts( {type: 'post', status : 'publish', number : 222} , ['title','id'] , (error, posts) => {
        return posts
            .map((item) => {
            return item.title
            })
        })
}

// MAIN

console.log(getAllPosts());
</code>```

答:
You can simply pass the callback function to  getAllPosts.

```<code>getAllPosts(cb){
return client
    .getPosts( {type: 'post', status : 'publish', number : 222} , ['title','id'] , (error, posts) => {
    cb(posts
        .map((item) => {
        return item.title
        }))
    })
}

getAllPosts(function(posts){
   console.log(posts)
})
</code>```

Body:
This is the code I'm using. It doesn't work because client.getPosts is async. So my question is, how can I make it work? client.getPosts is from the wordpress npm module so I cannot change it.

// FUNCTIONS

function getAllPosts() {
    return client
        .getPosts( {type: 'post', status : 'publish', number : 222} , ['title','id'] , (error, posts) => {
        return posts
            .map((item) => {
            return item.title
            })
        })
}

// MAIN

console.log(getAllPosts());

Body:
You can simply pass the callback function to  getAllPosts.

getAllPosts(cb){
return client
    .getPosts( {type: 'post', status : 'publish', number : 222} , ['title','id'] , (error, posts) => {
    cb(posts
        .map((item) => {
        return item.title
        }))
    })
}

getAllPosts(function(posts){
   console.log(posts)
})


问:
Automate VMware Snapshots and remove snapshots older than 5 days
I have 3 VMware exi 6.5 hosts each running 4 virtual machines.

In Powershell using PowerCLI, I would like a script that connects to a VMware esxi 6.5 host, executes a snapshot (excluding memory) of each VM, naming it the Day and Time, then removing / consolidating snapshots older than 2 days. The plan is to run the script everyday, to have a quick rollback point, should ransom-ware infect the server.

Thank you very much, your help is greatly appreciated.

答:
Below is a PowerShell function that I use for VMWare Workstation. You will need to research the vmrun command to find out more details of how to adapt it to your needs for ESX; this will get you on the right track. I realize this is not leveraging PowerShellCLI.

```<code>function Execute-VMRunCmd{
    param(
        [Parameter(Mandatory=$true)]
        [string]$args = $(Throw "Args parameter is required.")
    )
    WriteToLog -msg "VMRun Args: $args"
    pushd $sourcePath
    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName = $vmwareRun
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.Arguments = "$args"
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    $p.Start() | Out-Null
    $p.WaitForExit()
    $stdout = $p.StandardOutput.ReadToEnd()
    $stderr = $p.StandardError.ReadToEnd()
    $procExitCode = [string]$p.ExitCode
    popd
    WriteToLog -msg "stdout: $stdout, stderr: $stderr, ExitCode: $procExitCode"
    return $stdout
}
</code>```

WriteToLog is a function that I created to handle logging that inserts a timestamp, but it is a simple $fullMsg | Out-File -FilePath $logFile -Append -NoClobber call.

$sourcepath is the folder path to the vmx file, for ESX you will need to modify this. I switch to the directory for some of the calls to work. For ESX I suspect that this will not be required.

$vmwareRun is the path to your vmrun executable.

Vmrun command line documentation is found here: "https://www.vmware.com/support/developer/vix-api/vix112_vmrun_command.pdf"

I can use the above command to automate the vmrun command. I also return the $stdout value in case you need to evaluate the output of things like listsnapshots

Below is an example of how I utilize this function.

```<code>function Update-Snapshot{
    $snapshotName="WeeklyUpdate"

    [string]$allSnapshots = Execute-VMRunCmd -args "listSnapshots $fqp_source"
    if ($allSnapshots.Contains($snapshotName)){
        Start-Sleep -Seconds 60
        Execute-VMRunCmd -args "deleteSnapshot $fqp_source $snapshotName"
    }
    Execute-VMRunCmd -args "snapshot `"$fqp_source`" $snapshotName"
}
</code>```

Note that I had to insert an arbitrary sleep command. For some reason I was getting host not available error when trying to delete a snapshot without it. I have not figured out why yet.

Read through the documentation for VMRun. Hopefully this is helpful for you.

Body:
Below is a PowerShell function that I use for VMWare Workstation. You will need to research the vmrun command to find out more details of how to adapt it to your needs for ESX; this will get you on the right track. I realize this is not leveraging PowerShellCLI.

function Execute-VMRunCmd{
    param(
        [Parameter(Mandatory=$true)]
        [string]$args = $(Throw "Args parameter is required.")
    )
    WriteToLog -msg "VMRun Args: $args"
    pushd $sourcePath
    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName = $vmwareRun
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.Arguments = "$args"
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    $p.Start() | Out-Null
    $p.WaitForExit()
    $stdout = $p.StandardOutput.ReadToEnd()
    $stderr = $p.StandardError.ReadToEnd()
    $procExitCode = [string]$p.ExitCode
    popd
    WriteToLog -msg "stdout: $stdout, stderr: $stderr, ExitCode: $procExitCode"
    return $stdout
}

WriteToLog is a function that I created to handle logging that inserts a timestamp, but it is a simple $fullMsg | Out-File -FilePath $logFile -Append -NoClobber call.

$sourcepath is the folder path to the vmx file, for ESX you will need to modify this. I switch to the directory for some of the calls to work. For ESX I suspect that this will not be required.

$vmwareRun is the path to your vmrun executable.

Vmrun command line documentation is found here: "https://www.vmware.com/support/developer/vix-api/vix112_vmrun_command.pdf"

I can use the above command to automate the vmrun command. I also return the $stdout value in case you need to evaluate the output of things like listsnapshots

Below is an example of how I utilize this function.

function Update-Snapshot{
    $snapshotName="WeeklyUpdate"

    [string]$allSnapshots = Execute-VMRunCmd -args "listSnapshots $fqp_source"
    if ($allSnapshots.Contains($snapshotName)){
        Start-Sleep -Seconds 60
        Execute-VMRunCmd -args "deleteSnapshot $fqp_source $snapshotName"
    }
    Execute-VMRunCmd -args "snapshot `"$fqp_source`" $snapshotName"
}

Note that I had to insert an arbitrary sleep command. For some reason I was getting host not available error when trying to delete a snapshot without it. I have not figured out why yet.

Read through the documentation for VMRun. Hopefully this is helpful for you.


问:
CSS translate not working in IE11 on SVG g
I want to move a group of svg elements using a <g> tag, but it isn't working in IE, even the latest version, although it works in all the other browsers.

Do I need to use some other way of moving a group of elements in an svg?

svg {
  width: 20px;
  height: 20px;
}

g {
  transform: translate(10px, 0);
  -ms-transform: translate(10px, 0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewbox="0 0 20 20">
    <g>
        <circle cx=10 cy=10 r=10 />
    </g>
</svg></code>```

答:
if someone still needs this with jQuery this worked for me:</p>

```<code>jQuery("g").each(function(){
        transform = jQuery(this).css('transform');
        console.log(transform);
        jQuery(this).attr('transform',transform);
    });
</code>```

Body:
I want to move a group of svg elements using a <g> tag, but it isn't working in IE, even the latest version, although it works in all the other browsers.

Do I need to use some other way of moving a group of elements in an svg?

svg {
  width: 20px;
  height: 20px;
}

g {
  transform: translate(10px, 0);
  -ms-transform: translate(10px, 0);
}

<svg viewbox="0 0 20 20">
    <g>
        <circle cx=10 cy=10 r=10 />
    </g>
</svg>

Body:
if someone still needs this with jQuery this worked for me:

jQuery("g").each(function(){
        transform = jQuery(this).css('transform');
        console.log(transform);
        jQuery(this).attr('transform',transform);
    });


问:
the title prop of a button must be a string - react native
while run on device getting error like this "the title prop of a button must be a string - react native"

```<code>import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
Button,
View
} from 'react-native';

export default class sample extends Component {

render() {
return (
    <Button
      style={{fontSize: 20, color: 'green'}}
      styleDisabled={{color: 'red'}}
      onPress={() => this._handlePress()}>
      title="Press Me"
    </Button>
);
}

_handlePress() {
  console.log('Pressed!');
}
}

AppRegistry.registerComponent('sample', () => sample);
</code>```

答:
Button name should be written with title keyword

Example :

```<code><Button
  style={{fontSize: 20, color: 'green'}}
  styleDisabled={{color: 'red'}}
  onPress={() => this._handlePress()}
  title="Press Me"
>
</Button>
</code>```

title="Press Me" inside Button tag

Body:
while run on device getting error like this "the title prop of a button must be a string - react native"

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
Button,
View
} from 'react-native';

export default class sample extends Component {

render() {
return (
    <Button
      style={{fontSize: 20, color: 'green'}}
      styleDisabled={{color: 'red'}}
      onPress={() => this._handlePress()}>
      title="Press Me"
    </Button>
);
}

_handlePress() {
  console.log('Pressed!');
}
}

AppRegistry.registerComponent('sample', () => sample);

Body:
Button name should be written with title keyword

Example :

<Button
  style={{fontSize: 20, color: 'green'}}
  styleDisabled={{color: 'red'}}
  onPress={() => this._handlePress()}
  title="Press Me"
>
</Button>

title="Press Me" inside Button tag


问:
Hidden Features of Xcode
With a huge influx of newbies to Xcode, I'm sure there are lots of Xcode tips and tricks to be shared.

What are yours?

答:
Cmd + ~ (tilde - looks weird  on the button...)

To switch between any open Xcode window - also when multiple projects are open.

OwnerDisplayName: schwa

Title: Hidden Features of Xcode

LastEditorDisplayName: Ned Batchelder


问:
Antlr4 - no viable alternative at input
I am trying to create a simple HOCON parser (started from the existing JSON one).

The grammar is defined as:

```<code>/** Taken from "The Definitive ANTLR 4 Reference" by Terence Parr */

// Derived from http://json.org
grammar HOCON;

hocon
   : value
   | pair
   ;

obj
   : object_begin pair (','? pair)* object_end
   | object_begin object_end
   ;

pair
   : STRING KV? value {fmt.Println("pairstr",$STRING.GetText())}
   | KEY KV? value {fmt.Println("pairkey",$KEY.GetText())}
   ;

array
   : array_begin value (',' value)* array_end
   | array_begin array_end
   ;

value
   : STRING {fmt.Println($STRING.GetText())}
   | REFERENCE {fmt.Println($REFERENCE.GetText())}
   | RAWSTRING {fmt.Println($RAWSTRING.GetText())}
   | NUMBER {fmt.Println($NUMBER.GetText())}
   | obj
   | array
   | 'true'
   | 'false'
   | 'null'
   ;

COMMENT
   : '#' ~( '\r' | '\n' )* -> skip
   ;

STRING
   : '"' (ESC | ~ ["\\])* '"'
   | '\'' (ESC | ~ ['\\])* '\''
   ;

RAWSTRING
   : (ESC | ALPHANUM)+
   ;

KEY
   : ( '.' | ALPHANUM | '-')+
   ;

REFERENCE
   : '${' (ALPHANUM|'.')+ '}'
   ;

fragment ESC
   : '\\' (["\\/bfnrt] | UNICODE)
   ;

fragment UNICODE
   : 'u' HEX HEX HEX HEX
   ;

fragment ALPHANUM
   : [0-9a-zA-Z]
   ;

fragment HEX
   : [0-9a-fA-F]
   ;

KV
   : [=:]
   ;

array_begin
   : '[' { fmt.Println("BEGIN [") }
   ;

array_end
   : ']' { fmt.Println("] END") }
   ;

object_begin
   : '{' { fmt.Println("OBJ {") }
   ;

object_end
   : '}' { fmt.Println("} OBJ") }
   ;

NUMBER
   : '-'? INT '.' [0-9] + EXP? | '-'? INT EXP | '-'? INT
   ;

fragment INT
   : '0' | [1-9] [0-9]*
   ;

// no leading zeros

fragment EXP
   : [Ee] [+\-]? INT
   ;

// \- since - means "range" inside [...]

WS
   : [ \t\n\r] + -> skip
   ;
</code>```

the error is:

```<code>line 2:2 no viable alternative at input '{journal'
pairkey akka.persistence
</code>```

the sample input that gives the error is:

```<code>akka.persistence {
  journal {
    # Absolute path to the journal plugin configuration entry used by
    # persistent actor or view by default.
    # Persistent actor or view can override `journalPluginId` method
    # in order to rely on a different journal plugin.
    plugin = ""
  }
}
</code>```

however if I will update it to use quoted strings:

```<code>akka.persistence {
  'journal' {
    # Absolute path to the journal plugin configuration entry used by
    # persistent actor or view by default.
    # Persistent actor or view can override `journalPluginId` method
    # in order to rely on a different journal plugin.
    'plugin' = ""
  }
}
</code>```

everything works as expected.

Looks like I miss something in the KEY definition, but I can't really find out what exactly.

The Go code to test it out is:

```<code>package main

import (
    "github.com/antlr/antlr4/runtime/Go/antlr"
    "go-hocon/parser"
)

func main() {
    is, _ := antlr.NewFileStream("test/simple1.conf")

    lex := parser.NewHOCONLexer(is)
    p := parser.NewHOCONParser(antlr.NewCommonTokenStream(lex, 0))
    p.BuildParseTrees = true
    p.Hocon()
}
</code>```

答:
Your first input makes journal lex as a RAWSTRING.

```<code>[@0,0:15='akka.persistence',<KEY>,1:0]
[@1,17:17='{',<'{'>,1:17]
[@2,22:28='journal',<RAWSTRING>,2:2]
[@3,30:30='{',<'{'>,2:10]
[@4,277:282='plugin',<RAWSTRING>,7:4]
[@5,284:284='=',<KV>,7:11]
[@6,286:287='""',<STRING>,7:13]
[@7,292:292='}',<'}'>,8:2]
[@8,295:295='}',<'}'>,9:0]
[@9,298:297='<EOF>',<EOF>,10:0]
line 2:2 no viable alternative at input '{journal'
</code>```

On the other hand, 'journal' lexes as a string, but has those single quotes which you clearly don't want:

```<code>[@0,0:15='akka.persistence',<KEY>,1:0]
[@1,17:17='{',<'{'>,1:17]
[@2,22:30=''journal'',<STRING>,2:2]  <-- now it's a string implicit token
[@3,32:32='{',<'{'>,2:12]
[@4,279:284='plugin',<RAWSTRING>,7:4]
[@5,286:286='=',<KV>,7:11]
[@6,288:289='""',<STRING>,7:13]
[@7,294:294='}',<'}'>,8:2]
[@8,297:297='}',<'}'>,9:0]
[@9,300:299='<EOF>',<EOF>,10:0]
line 7:4 no viable alternative at input '{plugin'
line 8:2 mismatched input '}' expecting {'true', 'false', 'null', '[', '{', STRING, RAWSTRING, REFERENCE, KV, NUMBER}
</code>```

Why?  Because lexer rules bind in the following way:
1. Match longest input first.
2. Match implicit tokens (like 'journal')
3. If length of input match is equal, match based on the order of the lexer rules.

In your case, putting 'journal' makes it match as an implicit token, so it seems to work okay.  But only because of those single quotes, which makes it match per rule 2 above  Without the quotes, these two tokens are being matched as RAWSTRING, which doesn't fit the rule

```<code>pair
   : STRING KV? value //{fmt.Println("pairstr",$STRING.GetText())}
</code>```

Hence the error.

How to fix?  Well, I reversed the lexer rules:

```<code>RAWSTRING
   : (ESC | ALPHANUM)+
   ;

STRING
   : '"' (ESC | ~ ["\\])* '"'
   | '\'' (ESC | ~ ['\\])* '\''
   ;
</code>```

And changed pair:

```<code>pair
   : RAWSTRING KV? value //{fmt.Println("pairstr",$STRING.GetText())}
</code>```

Now it parses fine:

```<code>[@0,0:15='akka.persistence',<KEY>,1:0]
[@1,17:17='{',<'{'>,1:17]
[@2,22:28='journal',<RAWSTRING>,2:2]
[@3,30:30='{',<'{'>,2:10]
[@4,277:282='plugin',<RAWSTRING>,7:4]
[@5,284:284='=',<KV>,7:11]
[@6,286:287='""',<STRING>,7:13]
[@7,292:292='}',<'}'>,8:2]
[@8,295:295='}',<'}'>,9:0]
[@9,298:297='<EOF>',<EOF>,10:0]
</code>```

Title: Antlr4 - no viable alternative at input

Body:
I am trying to create a simple HOCON parser (started from the existing JSON one).

The grammar is defined as:

/** Taken from "The Definitive ANTLR 4 Reference" by Terence Parr */

// Derived from http://json.org
grammar HOCON;

hocon
   : value
   | pair
   ;

obj
   : object_begin pair (','? pair)* object_end
   | object_begin object_end
   ;

pair
   : STRING KV? value {fmt.Println("pairstr",$STRING.GetText())}
   | KEY KV? value {fmt.Println("pairkey",$KEY.GetText())}
   ;

array
   : array_begin value (',' value)* array_end
   | array_begin array_end
   ;

value
   : STRING {fmt.Println($STRING.GetText())}
   | REFERENCE {fmt.Println($REFERENCE.GetText())}
   | RAWSTRING {fmt.Println($RAWSTRING.GetText())}
   | NUMBER {fmt.Println($NUMBER.GetText())}
   | obj
   | array
   | 'true'
   | 'false'
   | 'null'
   ;

COMMENT
   : '#' ~( '\r' | '\n' )* -> skip
   ;

STRING
   : '"' (ESC | ~ ["\\])* '"'
   | '\'' (ESC | ~ ['\\])* '\''
   ;

RAWSTRING
   : (ESC | ALPHANUM)+
   ;

KEY
   : ( '.' | ALPHANUM | '-')+
   ;

REFERENCE
   : '${' (ALPHANUM|'.')+ '}'
   ;

fragment ESC
   : '\\' (["\\/bfnrt] | UNICODE)
   ;

fragment UNICODE
   : 'u' HEX HEX HEX HEX
   ;

fragment ALPHANUM
   : [0-9a-zA-Z]
   ;

fragment HEX
   : [0-9a-fA-F]
   ;

KV
   : [=:]
   ;

array_begin
   : '[' { fmt.Println("BEGIN [") }
   ;

array_end
   : ']' { fmt.Println("] END") }
   ;

object_begin
   : '{' { fmt.Println("OBJ {") }
   ;

object_end
   : '}' { fmt.Println("} OBJ") }
   ;

NUMBER
   : '-'? INT '.' [0-9] + EXP? | '-'? INT EXP | '-'? INT
   ;

fragment INT
   : '0' | [1-9] [0-9]*
   ;

// no leading zeros

fragment EXP
   : [Ee] [+\-]? INT
   ;

// \- since - means "range" inside [...]

WS
   : [ \t\n\r] + -> skip
   ;

the error is:

line 2:2 no viable alternative at input '{journal'
pairkey akka.persistence

the sample input that gives the error is:

akka.persistence {
  journal {
    # Absolute path to the journal plugin configuration entry used by
    # persistent actor or view by default.
    # Persistent actor or view can override `journalPluginId` method
    # in order to rely on a different journal plugin.
    plugin = ""
  }
}

however if I will update it to use quoted strings:

akka.persistence {
  'journal' {
    # Absolute path to the journal plugin configuration entry used by
    # persistent actor or view by default.
    # Persistent actor or view can override `journalPluginId` method
    # in order to rely on a different journal plugin.
    'plugin' = ""
  }
}

everything works as expected.

Looks like I miss something in the KEY definition, but I can't really find out what exactly.

The Go code to test it out is:

package main

import (
    "github.com/antlr/antlr4/runtime/Go/antlr"
    "go-hocon/parser"
)

func main() {
    is, _ := antlr.NewFileStream("test/simple1.conf")

    lex := parser.NewHOCONLexer(is)
    p := parser.NewHOCONParser(antlr.NewCommonTokenStream(lex, 0))
    p.BuildParseTrees = true
    p.Hocon()
}

Body:
Your first input makes journal lex as a RAWSTRING.

[@0,0:15='akka.persistence',<KEY>,1:0]
[@1,17:17='{',<'{'>,1:17]
[@2,22:28='journal',<RAWSTRING>,2:2]
[@3,30:30='{',<'{'>,2:10]
[@4,277:282='plugin',<RAWSTRING>,7:4]
[@5,284:284='=',<KV>,7:11]
[@6,286:287='""',<STRING>,7:13]
[@7,292:292='}',<'}'>,8:2]
[@8,295:295='}',<'}'>,9:0]
[@9,298:297='<EOF>',<EOF>,10:0]
line 2:2 no viable alternative at input '{journal'

On the other hand, 'journal' lexes as a string, but has those single quotes which you clearly don't want:

[@0,0:15='akka.persistence',<KEY>,1:0]
[@1,17:17='{',<'{'>,1:17]
[@2,22:30=''journal'',<STRING>,2:2]  <-- now it's a string implicit token
[@3,32:32='{',<'{'>,2:12]
[@4,279:284='plugin',<RAWSTRING>,7:4]
[@5,286:286='=',<KV>,7:11]
[@6,288:289='""',<STRING>,7:13]
[@7,294:294='}',<'}'>,8:2]
[@8,297:297='}',<'}'>,9:0]
[@9,300:299='<EOF>',<EOF>,10:0]
line 7:4 no viable alternative at input '{plugin'
line 8:2 mismatched input '}' expecting {'true', 'false', 'null', '[', '{', STRING, RAWSTRING, REFERENCE, KV, NUMBER}

Why?  Because lexer rules bind in the following way:
1. Match longest input first.
2. Match implicit tokens (like 'journal')
3. If length of input match is equal, match based on the order of the lexer rules.

In your case, putting 'journal' makes it match as an implicit token, so it seems to work okay.  But only because of those single quotes, which makes it match per rule 2 above  Without the quotes, these two tokens are being matched as RAWSTRING, which doesn't fit the rule

pair
   : STRING KV? value //{fmt.Println("pairstr",$STRING.GetText())}

Hence the error.

How to fix?  Well, I reversed the lexer rules:

RAWSTRING
   : (ESC | ALPHANUM)+
   ;

STRING
   : '"' (ESC | ~ ["\\])* '"'
   | '\'' (ESC | ~ ['\\])* '\''
   ;

And changed pair:

pair
   : RAWSTRING KV? value //{fmt.Println("pairstr",$STRING.GetText())}

Now it parses fine:

[@0,0:15='akka.persistence',<KEY>,1:0]
[@1,17:17='{',<'{'>,1:17]
[@2,22:28='journal',<RAWSTRING>,2:2]
[@3,30:30='{',<'{'>,2:10]
[@4,277:282='plugin',<RAWSTRING>,7:4]
[@5,284:284='=',<KV>,7:11]
[@6,286:287='""',<STRING>,7:13]
[@7,292:292='}',<'}'>,8:2]
[@8,295:295='}',<'}'>,9:0]
[@9,298:297='<EOF>',<EOF>,10:0]


问:
Safety of ptrace on x86_64
From Wikipedia:

long: Long signed integer type. Capable of containing at least the [−2,147,483,647, +2,147,483,647] range; thus, it is at least 32 bits in size.

From man ptrace:

```<code>long ptrace(enum __ptrace_request request, pid_t pid,
            void *addr, void *data);
</code>```

Remember that signed overflow is undefined behavior in C. The registers on x86_64 store 64-bit values.

Is it thus unsafe to read the contents of the registers (e.g. ORIG_RAX) with ptrace on x86_64?

答:
When you something like ptrace you are not talking about the C standard. You have fixed the target/platform/architecture(/compiler). These things fix the implementation.

Under this implementation, the behavior happening is defined and is safe(because it uses 64 bit size for long).

So no, it is not unsafe. But it would be unsafe if you just copied the compiled binaries and used on another target.

Title: Safety of ptrace on x86_64

Body:
From Wikipedia:

long: Long signed integer type. Capable of containing at least the [−2,147,483,647, +2,147,483,647] range; thus, it is at least 32 bits in size.

From man ptrace:

long ptrace(enum __ptrace_request request, pid_t pid,
            void *addr, void *data);

Remember that signed overflow is undefined behavior in C. The registers on x86_64 store 64-bit values.

Is it thus unsafe to read the contents of the registers (e.g. ORIG_RAX) with ptrace on x86_64?


问:
two network card, which card 127.0.0.1 represent?
If there is one network card, we can access this card's corresponding port through 127.0.0.1:port. But if there are two network cards and they are monitoring the same port(such as 6000), which card will be accessed when I access 127.0.0.1:6000? If you think they are independent, what relation between them? I think there must be some relation between them, because "If there is one network card, we can access this card's corresponding port through 127.0.0.1:port.".</p>

答:
None of them. 127.0.0.1 is the loopback interface. It exists even if you don't have network cards.
The network cards will have their own different ip address.

On Un*x systems you can list your netowrk intrfaces with ifconfig -a

On Windows you can do the same with ipconfig /all


问:
how to handles empty lines when reading CSV files in javascript
I'm using KnockoutJS in my MVc Project to load a csv file &  provide a simple validation for import mechanism

The workflow is as follows:

User selects a CSV file (sample provided).

User clicks a button (weehoo...).

Client-side code takes the CSV, parses it, and loads it into KnockoutJS array.
All is working Perfect i can upload the file but the problem that my Code Load The Empty line in csv files, I dont want that the user remove the empty lines manual before importing the file

this is an example of csv Lines :

```<code>Account_id,External_id,Amount,Transaction_Date,Office_date,Bank,Receipt_nbr,Type,statement,receipt,

0559394,,5,6/20/2017,7/7/2017,Cash,1729002903597,PNL,172900290,3597,

0099952,,19,6/20/2017,7/7/2017,Cash,1729002903653,PNL,172900290,3653,

,,,,,,,,,,

,,,,,,,,,,

,,,,,,,,,,
</code>```

Here my code used to Upload file :

```<code>$('#lnkUpload').click(function () {
    var FileToRead = document.getElementById('UserFile');
    if (FileToRead.files.length > 0) {
        var reader = new FileReader();
        // assign function to the OnLoad event of the FileReader
        // non synchronous event, therefore assign to other method
        reader.onload = Load_CSVData;
        // call the reader to capture the file
        reader.readAsText(FileToRead.files.item(0));
    }
    self.userModel.removeAll();

});

 function Load_CSVData(e) {
    self.userModel.removeAll();

    CSVLines = e.target.result.split(/\r\n|\n/);
    $CSVLines = CSVLines.slice(1);
    $.each($CSVLines, function (i, item) {

        var element = item.split(","); // builds an array from comma delimited items
        var LAccount_id = (element[0] == undefined) ? "" : element[0].trim();
        var LExternal_id = (element[1] == undefined) ? "" : element[1].trim();
        var LAmount = (element[2] == undefined) ? "" : element[2].trim();
        var LTransaction_date = (element[3] == undefined) ? "" : element[3].trim();
        var LOffice_date = (element[4] == undefined) ? "" : element[4].trim();
        var LBank = (element[5] == undefined) ? "" : element[5].trim();
        var LReceipt_nbr = (element[6] == undefined) ? "" : element[6].trim();
        var LType = (element[7] == undefined) ? "" : element[7].trim();
        var Lstatement = (element[8] == undefined) ? "" : element[8].trim();
        var Lreceipt = (element[9] == undefined) ? "" : element[9].trim();

        self.userModel.push(new userModel()
            .Account_id(LAccount_id)
            .External_id(LExternal_id)
            .Amount(LAmount)
            .Transaction_date(LTransaction_date)
            .Office_date(LOffice_date)
            .Bank(LBank)
            .Receipt_nbr(LReceipt_nbr)
            .Type(LType)
            .statement(Lstatement)
            .receipt(Lreceipt))

    });

}
</code>```

how can i update the code to Ignore and skip over empty Lines or treat them as the end of the input file or any other suggestion

答:
You can detect if the current line is a newline character.

```<code>if(item == "\n") { continue; }
</code>```

EDIT:

As matt pointed out, if the whitespace is made up of spaces the above solution will not work. Simply erase any spaces to detect if the row is made up of spaces.

```<code>if(item == "\n" || item.trim().length == 0) { continue; }
</code>```

Body:
I'm using KnockoutJS in my MVc Project to load a csv file &  provide a simple validation for import mechanism

The workflow is as follows:

User selects a CSV file (sample provided).

User clicks a button (weehoo...).

Client-side code takes the CSV, parses it, and loads it into KnockoutJS array.
All is working Perfect i can upload the file but the problem that my Code Load The Empty line in csv files, I dont want that the user remove the empty lines manual before importing the file

this is an example of csv Lines :

Account_id,External_id,Amount,Transaction_Date,Office_date,Bank,Receipt_nbr,Type,statement,receipt,

0559394,,5,6/20/2017,7/7/2017,Cash,1729002903597,PNL,172900290,3597,

0099952,,19,6/20/2017,7/7/2017,Cash,1729002903653,PNL,172900290,3653,

,,,,,,,,,,

,,,,,,,,,,

,,,,,,,,,,

Here my code used to Upload file :

$('#lnkUpload').click(function () {
    var FileToRead = document.getElementById('UserFile');
    if (FileToRead.files.length > 0) {
        var reader = new FileReader();
        // assign function to the OnLoad event of the FileReader
        // non synchronous event, therefore assign to other method
        reader.onload = Load_CSVData;
        // call the reader to capture the file
        reader.readAsText(FileToRead.files.item(0));
    }
    self.userModel.removeAll();

});

 function Load_CSVData(e) {
    self.userModel.removeAll();

    CSVLines = e.target.result.split(/\r\n|\n/);
    $CSVLines = CSVLines.slice(1);
    $.each($CSVLines, function (i, item) {

        var element = item.split(","); // builds an array from comma delimited items
        var LAccount_id = (element[0] == undefined) ? "" : element[0].trim();
        var LExternal_id = (element[1] == undefined) ? "" : element[1].trim();
        var LAmount = (element[2] == undefined) ? "" : element[2].trim();
        var LTransaction_date = (element[3] == undefined) ? "" : element[3].trim();
        var LOffice_date = (element[4] == undefined) ? "" : element[4].trim();
        var LBank = (element[5] == undefined) ? "" : element[5].trim();
        var LReceipt_nbr = (element[6] == undefined) ? "" : element[6].trim();
        var LType = (element[7] == undefined) ? "" : element[7].trim();
        var Lstatement = (element[8] == undefined) ? "" : element[8].trim();
        var Lreceipt = (element[9] == undefined) ? "" : element[9].trim();

        self.userModel.push(new userModel()
            .Account_id(LAccount_id)
            .External_id(LExternal_id)
            .Amount(LAmount)
            .Transaction_date(LTransaction_date)
            .Office_date(LOffice_date)
            .Bank(LBank)
            .Receipt_nbr(LReceipt_nbr)
            .Type(LType)
            .statement(Lstatement)
            .receipt(Lreceipt))

    });

}

how can i update the code to Ignore and skip over empty Lines or treat them as the end of the input file or any other suggestion

Body:
You can detect if the current line is a newline character.

if(item == "\n") { continue; }

EDIT:

As matt pointed out, if the whitespace is made up of spaces the above solution will not work. Simply erase any spaces to detect if the row is made up of spaces.

if(item == "\n" || item.trim().length == 0) { continue; }


问:
Programmatically create an attribute map for custom fields on the lead/contact entities
So I have a CRM integration that adds two fields to the lead and contact. An integer and a Boolean. When we convert a lead into a contact I want those custom fields from the lead to carry over to the new contact. We have over 700 instances using our product so this needs to be a programmatic solution. And thats where the problem lies. I haven't been able to wrap my head around the CreateAttributeMappings class and was hoping someone here could enlighten me and show me where I'm being dumb...

Right now I've got something like this:

```<code>var parentEntityMapId = new v4.Sdk.Lookup();
parentEntityMapId.name = "lead";
parentEntityMapId.Value = Guid.NewGuid();

var entityMapId = new v4.Sdk.Lookup();
entityMapId.name = "contact";
//entityMapId.Value = new Guid("608861bc-50a4-4c5f-a02c-21fe1943e2cf");
entityMapId.Value = Guid.NewGuid();

var attributeMapId = new v4.Sdk.Key();
attributeMapId.Value = Guid.NewGuid();

var attributeMap = new v4.SdkTypeProxy.attributemap();
attributeMap.attributemapid = attributeMapId;
attributeMap.entitymapid = entityMapId;
attributeMap.sourceattributename = fieldNameFrom;
attributeMap.targetattributename = fieldNameTo;
//parentEntityMapId.Value = new Guid("DC6574CB-92CE-446C-A5D6-885A75107D52");
attributeMap.parentattributemapid = parentEntityMapId;

var targetAttributeMap = new v4.SdkTypeProxy.TargetCreateAttributeMap();

targetAttributeMap.AttributeMap = attributeMap;

var attributeMapCreateRequest = new v4.SdkTypeProxy.CreateRequest();
attributeMapCreateRequest.Target = targetAttributeMap;

var response = this.CrmService.Execute(attributeMapCreateRequest);
</code>```

However this gives me this error message:

0x80046203
  Invalid mapping. Either an attribute is not mappable, or attributes are of different types, or the size of the target attribute is smaller than the size of the source attribute.
  Platform

Any help or insight you could give me would be greatly appreciated.

答:
We could do this using PowerShell:</p>

```<code>Import-Module Microsoft.Xrm.Data.Powershell

function Get-EntitymapDetails() {
    param(
        [Parameter(Mandatory)]
        [string] $SourceEntityName,
        [Parameter(Mandatory)]
        [string] $TargetEntityName
    )

    $fetchxml = @"
        <fetch>
          <entity name="entitymap" >
            <attribute name="sourceentityname" />
            <attribute name="targetentityname" />
            <attribute name="entitymapidunique" />
            <attribute name="entitymapid" />
            <filter>
              <condition attribute="sourceentityname" operator="eq" value="lead" />
              <condition attribute="targetentityname" operator="eq" value="contact" />
            </filter>
          </entity>
        </fetch>
"@

    $relMappings = (Get-CrmRecordsByFetch -Fetch $fetchxml -AllRows).CrmRecords

    if($relMappings.Count -ne 1) {
        throw "Expected single entity-map - found $($relMappings)"
    }

    $relMappings
}

function Test-AttributeMappingExists() {
    param(
        [Parameter(Mandatory)]
        [Guid] $EntityMapId,
        [Parameter(Mandatory)]
        [string] $SourceAttribute,
        [Parameter(Mandatory)]
        [string] $TargetAttribute
    )

    $fetchxml = @"
        <fetch >
          <entity name="attributemap" >
            <attribute name="attributemapid" />
            <filter>
              <condition attribute="entitymapid" operator="eq" value="$EntityMapId" />
              <condition attribute="sourceattributename" operator="eq" value="$SourceAttribute" />
              <condition attribute="targetattributename" operator="eq" value="$TargetAttribute" />
            </filter>
          </entity>
        </fetch>
"@

    $attrMappings = (Get-CrmRecordsByFetch -Fetch $fetchxml)

    return ($attrMappings.CrmRecords.Count -gt 0)
}

function Setup-AttributeMapping() {
   param(
        [Parameter(Mandatory)]
        [Guid] $EntityMapId,
        [Parameter(Mandatory)]
        [string] $SourceAttribute,
        [Parameter(Mandatory)]
        [string] $TargetAttribute
    )

    ## verify that this attribute mapping is not already defined
    $attrMappingExits = Test-AttributeMappingExists `
                            -EntityMapId $entityMap.entitymapid `
                            -SourceAttribute $SourceAttribute `
                            -TargetAttribute $TargetAttribute

    if($attrMappingExits){

        Write-Host "Attribute-Mapping for '$sourceAttr' -> '$targetAttr' is already defined"
        return
    }

    $response = New-CrmRecord -EntityLogicalName 'attributemap' -Fields @{
        entitymapid = New-CrmEntityReference -EntityLogicalName 'entitymap' -Id $EntityMapId
        sourceattributename = $SourceAttribute;
        targetattributename = $TargetAttribute;
    }

    if($response -eq $null) {
        throw $conn.LastCrmError
    }

    Write-Host "Created new attribute-mapping"

}

$conn = Get-CrmConnection -InteractiveMode

$sourceAttr = 'parentaccountid'
$targetAttr = 'parentcustomerid'

$entityMap = Get-EntitymapDetails -SourceEntityName 'lead' -TargetEntityName 'contact'

Setup-AttributeMapping `
    -EntityMapId $entityMap.entitymapid `
    -SourceAttribute $sourceAttr `
    -TargetAttribute $targetAttr
</code>```

Body:
So I have a CRM integration that adds two fields to the lead and contact. An integer and a Boolean. When we convert a lead into a contact I want those custom fields from the lead to carry over to the new contact. We have over 700 instances using our product so this needs to be a programmatic solution. And thats where the problem lies. I haven't been able to wrap my head around the CreateAttributeMappings class and was hoping someone here could enlighten me and show me where I'm being dumb...

Right now I've got something like this:

var parentEntityMapId = new v4.Sdk.Lookup();
parentEntityMapId.name = "lead";
parentEntityMapId.Value = Guid.NewGuid();

var entityMapId = new v4.Sdk.Lookup();
entityMapId.name = "contact";
//entityMapId.Value = new Guid("608861bc-50a4-4c5f-a02c-21fe1943e2cf");
entityMapId.Value = Guid.NewGuid();

var attributeMapId = new v4.Sdk.Key();
attributeMapId.Value = Guid.NewGuid();

var attributeMap = new v4.SdkTypeProxy.attributemap();
attributeMap.attributemapid = attributeMapId;
attributeMap.entitymapid = entityMapId;
attributeMap.sourceattributename = fieldNameFrom;
attributeMap.targetattributename = fieldNameTo;
//parentEntityMapId.Value = new Guid("DC6574CB-92CE-446C-A5D6-885A75107D52");
attributeMap.parentattributemapid = parentEntityMapId;

var targetAttributeMap = new v4.SdkTypeProxy.TargetCreateAttributeMap();

targetAttributeMap.AttributeMap = attributeMap;

var attributeMapCreateRequest = new v4.SdkTypeProxy.CreateRequest();
attributeMapCreateRequest.Target = targetAttributeMap;

var response = this.CrmService.Execute(attributeMapCreateRequest);

However this gives me this error message:

0x80046203
  Invalid mapping. Either an attribute is not mappable, or attributes are of different types, or the size of the target attribute is smaller than the size of the source attribute.
  Platform

Any help or insight you could give me would be greatly appreciated.

Body:
We could do this using PowerShell:

Import-Module Microsoft.Xrm.Data.Powershell

function Get-EntitymapDetails() {
    param(
        [Parameter(Mandatory)]
        [string] $SourceEntityName,
        [Parameter(Mandatory)]
        [string] $TargetEntityName
    )

    $fetchxml = @"
        <fetch>
          <entity name="entitymap" >
            <attribute name="sourceentityname" />
            <attribute name="targetentityname" />
            <attribute name="entitymapidunique" />
            <attribute name="entitymapid" />
            <filter>
              <condition attribute="sourceentityname" operator="eq" value="lead" />
              <condition attribute="targetentityname" operator="eq" value="contact" />
            </filter>
          </entity>
        </fetch>
"@

    $relMappings = (Get-CrmRecordsByFetch -Fetch $fetchxml -AllRows).CrmRecords

    if($relMappings.Count -ne 1) {
        throw "Expected single entity-map - found $($relMappings)"
    }

    $relMappings
}

function Test-AttributeMappingExists() {
    param(
        [Parameter(Mandatory)]
        [Guid] $EntityMapId,
        [Parameter(Mandatory)]
        [string] $SourceAttribute,
        [Parameter(Mandatory)]
        [string] $TargetAttribute
    )

    $fetchxml = @"
        <fetch >
          <entity name="attributemap" >
            <attribute name="attributemapid" />
            <filter>
              <condition attribute="entitymapid" operator="eq" value="$EntityMapId" />
              <condition attribute="sourceattributename" operator="eq" value="$SourceAttribute" />
              <condition attribute="targetattributename" operator="eq" value="$TargetAttribute" />
            </filter>
          </entity>
        </fetch>
"@

    $attrMappings = (Get-CrmRecordsByFetch -Fetch $fetchxml)

    return ($attrMappings.CrmRecords.Count -gt 0)
}

function Setup-AttributeMapping() {
   param(
        [Parameter(Mandatory)]
        [Guid] $EntityMapId,
        [Parameter(Mandatory)]
        [string] $SourceAttribute,
        [Parameter(Mandatory)]
        [string] $TargetAttribute
    )

    ## verify that this attribute mapping is not already defined
    $attrMappingExits = Test-AttributeMappingExists `
                            -EntityMapId $entityMap.entitymapid `
                            -SourceAttribute $SourceAttribute `
                            -TargetAttribute $TargetAttribute

    if($attrMappingExits){

        Write-Host "Attribute-Mapping for '$sourceAttr' -> '$targetAttr' is already defined"
        return
    }

    $response = New-CrmRecord -EntityLogicalName 'attributemap' -Fields @{
        entitymapid = New-CrmEntityReference -EntityLogicalName 'entitymap' -Id $EntityMapId
        sourceattributename = $SourceAttribute;
        targetattributename = $TargetAttribute;
    }

    if($response -eq $null) {
        throw $conn.LastCrmError
    }

    Write-Host "Created new attribute-mapping"

}

$conn = Get-CrmConnection -InteractiveMode

$sourceAttr = 'parentaccountid'
$targetAttr = 'parentcustomerid'

$entityMap = Get-EntitymapDetails -SourceEntityName 'lead' -TargetEntityName 'contact'

Setup-AttributeMapping `
    -EntityMapId $entityMap.entitymapid `
    -SourceAttribute $sourceAttr `
    -TargetAttribute $targetAttr