答:
You should associate it to the element to the elementRef

```<code>@ViewChild('foo') foo: TemplateRef;

<div #foo>
    <h2>Hello {{name}}</h2>
</div>
    {{foo.clientWidth}}
</code>```

LIVE DEMO

Title: How to get width of absolute positioned element in Angular

Body:
You should associate it to the element to the elementRef

@ViewChild('foo') foo: TemplateRef;

<div #foo>
    <h2>Hello {{name}}</h2>
</div>
    {{foo.clientWidth}}

LIVE DEMO


来源: stackexchange

问:
How do you make a string in PHP with a backslash in it?
I need a backslash to be a part of a string. How can I do it?</p>

答:
Short answer:

Use two backslashes.

Long answer:

You can sometimes use a single backslash, but sometimes you need two. When you can use a single backslash depends on two things:

whether your string is surrounded by single quotes or double quotes and

the character immediately following the backslash.

If you have a double quote string the backslash is treated as an escape character in many cases so it is best to always escape the backslash with another backslash:

```<code>$s = "foo\\bar"
</code>```

In a single quoted string backslashes will be literal unless they are followed by either a single quote or another backslash. So to output a single backslash with a single quoted string you can normally write this:

```<code>$s = 'foo\bar'
</code>```

But to output two backslashes in a row you need this:

```<code>$s = 'foo\\\\bar'
</code>```

If you always use two backslashes you will never be wrong.

ContentLicense: CC BY-SA 3.0

Body:
Short answer:

Use two backslashes.

Long answer:

You can sometimes use a single backslash, but sometimes you need two. When you can use a single backslash depends on two things:

whether your string is surrounded by single quotes or double quotes and

the character immediately following the backslash.

If you have a double quote string the backslash is treated as an escape character in many cases so it is best to always escape the backslash with another backslash:

$s = "foo\\bar"

In a single quoted string backslashes will be literal unless they are followed by either a single quote or another backslash. So to output a single backslash with a single quoted string you can normally write this:

$s = 'foo\bar'

But to output two backslashes in a row you need this:

$s = 'foo\\\\bar'

If you always use two backslashes you will never be wrong.

ContentLicense: CC BY-SA 2.5


问:
Is it possible to run two or more Azure functions simultanously?
I have function app(by default it is consumption plan) which is created by visual studio and has multiple functions including timer trigger and HTTP trigger. So am having some confusion how azure function runs?

does timer trigger stop execution of other function when any other function runs?

Example: When HTTP trigger runs which takes long time to process if in between my timer trigger runs(which runs for every 5 minutes) it is stopping execution of HTTP trigger for 5 minutes.

Does any azure function runs one by one or two functions at a time?.

If I go app service plan for function app. will the same happens while execution of azure function ?

答:
Yes, many functions can run at the same time.

Functions run independently from each other, except they consume shared resources (CPU / memory). The status of the timer triggered function should have no effect on whether HTTP function is triggered.


问:
Is PowerBI available with SQL Server 2016(Standard OR Enterprise) edition
Please help me in understand that,

Is PowerBI part of SQL Server 2016(Standard OR Enterprise) edition or PowerBI is separate setup that needs to installed for reports?

Best Regards,
Arayn

答: Power BI is a separate package and is not included in the MS SQL Server Package. But SSRS comes along with SQL Server Installer package. you can also use that for creating reports. otherwise, download Power BI from the Official Website</p>


问:
how to get record from 'and' operation with 'in' and is null clause
how do i get record which is containing both null value and some value using 'and' operation between 'in' and 'is null' clause in mysql query?

query:
select * from table1 where column in (value1,value2) or column is null;(works fine).
but when i use and instead of or I am getting empty set;

答:
The conditions in the WHERE clause are applied to each row.

```<code> FROM bar WHERE foo IN ('a','b','c') AND foo IS NULL
</code>```

is guaranteed to never evaluate to TRUE for any row in bar.  A row has a single value for column foo. That value can be NULL, or it can be non-NULL, one or the other.  The value of foo cannot be NULL and non-NULL at the same time, when the conditions are being evaluated.

By definition,  WHERE foo IS NOT NULL AND foo IS NULL will never evaluate to true. We are guaranteed that there are no rows that satisfy that condition.

Body:
The conditions in the WHERE clause are applied to each row.

 FROM bar WHERE foo IN ('a','b','c') AND foo IS NULL

is guaranteed to never evaluate to TRUE for any row in bar.  A row has a single value for column foo. That value can be NULL, or it can be non-NULL, one or the other.  The value of foo cannot be NULL and non-NULL at the same time, when the conditions are being evaluated.

By definition,  WHERE foo IS NOT NULL AND foo IS NULL will never evaluate to true. We are guaranteed that there are no rows that satisfy that condition.


问:
value is not returning from another class
Hi I'm making a game where the player is met with a robot and the robot asks it to guess a number between 1-10. The player has three tries or they die. I've written all my code and the guessing works fine but whenever the play gets it right he still dies. I added a couple of print statements to see what value my code was returning and it seems to be returning the wrong value. Can someone help me out? Thanks.

Goes from this class

```<code>if (choice != -1) {
if (john[choice] != null) {
if (john[choice].compPlayerAttack()) {
 System.out.print("IT'S GAME OVER MAN!\n");
    System.exit(0);
}
else {
  System.out.println("Robot appears. Guess a number between 1-10. Get it right and you can pass, or you die. You have three chances.\"");
      int answer = 0;
      john[choice].toPass(answer);
      if (answer== 1) {
         System.out.println(answer);
          map[x][y].removeJohnPlayer();
         }
      else { System.out.println(answer);
        System.out.print("IT'S GAME OVER MAN!\n");
  System.exit(0);
  }
</code>```

To this class

```<code>public int toPass(int right){

    int hiddenNum = numram.nextInt(MAX_NUMBER);

    Scanner input = new Scanner(System.in);

    int numOfGuesses = 0;
    int a = right;

    do {
        System.out.println("Enter a number by guessing: ");

        int guessedNum = input.nextInt();
        numOfGuesses++;

        if (guessedNum == hiddenNum) {
            System.out.println("Darn! Your number is matched. You may live.");
            System.out.println("You have made " + numOfGuesses + " attempts to find the number!");

            a = 1;
             break;

        } else if (guessedNum < hiddenNum) {
            System.out.println("Try a bigger number");

        } else if (guessedNum > hiddenNum) {
            System.out.println("Try a smaller number");

        }

}   while (numOfGuesses < 3);
System.out.println(a);
return a;
</code>```

}

答:
Here

```<code>john[choice].toPass(answer);
</code>```

you are ignoring the value returned by your toPass method.

Change it to:

```<code>answer = john[choice].toPass(answer);
</code>```

BTW, there's no reason to pass an argument to your toPass method, since it makes no use of it, and it can't change it (since Java is a pass by value language). A return value is enough.

i.e. change your method to public int toPass().

Another change you should make is to change the return type to boolean. Returning true or false is more readable than returning 1 or 0.

Body:
Hi I'm making a game where the player is met with a robot and the robot asks it to guess a number between 1-10. The player has three tries or they die. I've written all my code and the guessing works fine but whenever the play gets it right he still dies. I added a couple of print statements to see what value my code was returning and it seems to be returning the wrong value. Can someone help me out? Thanks.

Goes from this class

if (choice != -1) {
if (john[choice] != null) {
if (john[choice].compPlayerAttack()) {
 System.out.print("IT'S GAME OVER MAN!\n");
    System.exit(0);
}
else {
  System.out.println("Robot appears. Guess a number between 1-10. Get it right and you can pass, or you die. You have three chances.\"");
      int answer = 0;
      john[choice].toPass(answer);
      if (answer== 1) {
         System.out.println(answer);
          map[x][y].removeJohnPlayer();
         }
      else { System.out.println(answer);
        System.out.print("IT'S GAME OVER MAN!\n");
  System.exit(0);
  }

To this class

public int toPass(int right){

    int hiddenNum = numram.nextInt(MAX_NUMBER);

    Scanner input = new Scanner(System.in);

    int numOfGuesses = 0;
    int a = right;

    do {
        System.out.println("Enter a number by guessing: ");

        int guessedNum = input.nextInt();
        numOfGuesses++;

        if (guessedNum == hiddenNum) {
            System.out.println("Darn! Your number is matched. You may live.");
            System.out.println("You have made " + numOfGuesses + " attempts to find the number!");

            a = 1;
             break;

        } else if (guessedNum < hiddenNum) {
            System.out.println("Try a bigger number");

        } else if (guessedNum > hiddenNum) {
            System.out.println("Try a smaller number");

        }

}   while (numOfGuesses < 3);
System.out.println(a);
return a;

}

Body:
Here

john[choice].toPass(answer);

you are ignoring the value returned by your toPass method.

Change it to:

answer = john[choice].toPass(answer);

BTW, there's no reason to pass an argument to your toPass method, since it makes no use of it, and it can't change it (since Java is a pass by value language). A return value is enough.

i.e. change your method to public int toPass().

Another change you should make is to change the return type to boolean. Returning true or false is more readable than returning 1 or 0.


Title: How to mask specific slices for each row in a tensor

Body:
I'd like to modify specific vectors in a 3D tensor, according to a list of positions (indices):

#indices: 1D vector of positions, indices.shape: (k)

mask = np.zeros(k, n, m)
for i in range(k):
  mask[i][indices[i]] = 1

This mask will be applied to another 3D tensor (same shape), where I want to preserve specific vectors, and zero out the rest.

What's the best way to construct such a mask in TensorFlow? I can do it with a loop using an assign op, but I'd like to find a more elegant solution. Perhaps using tf.scatter_nd?

EDIT: example:

>>> mask_before
array([[[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]]])

>>> indices
array([2, 1, 4])

>>> mask_after
array([[[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 1.,  1.,  1.,  1.]]])

Body:
Here's the corresponding TF code for Divakar's answer:

indices = tf.constant([2,1,4])
a1 = tf.expand_dims(indices, axis=1)
a1 = tf.expand_dims(a1, axis=1)
a2 = tf.range(5)
a2 = tf.expand_dims(a2, axis=1)
a3 = tf.equal(a1, a2)
mask = tf.tile(a3, [1,1,4])

>>> tf.cast(mask, dtype=tf.int8)
<tf.Tensor: id=55, shape=(3, 5, 4), dtype=int8, numpy=
array([[[0, 0, 0, 0],
    [0, 0, 0, 0],
    [1, 1, 1, 1],
    [0, 0, 0, 0],
    [0, 0, 0, 0]],

   [[0, 0, 0, 0],
    [1, 1, 1, 1],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0]],

   [[0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [1, 1, 1, 1]]], dtype=int8)>


答: You have to escape all backslashes like "c:\\windows\\".

Title: How do you make a string in PHP with a backslash in it?

Body: I need a backslash to be a part of a string. How can I do it?


问:
java.lang.ClassNotFoundException: org.apache.jasper.runtime.JspApplicationContextImpl | jetty:run
I am getting

```<code>java.lang.ClassNotFoundException: org.apache.jasper.runtime.JspApplicationContextImpl
</code>```

while using jetty:run plugin on a web project.

The issue is occurring only on some machines while working on some !

Java Version Used : 7
Maven Version : 3.1

Relevant dependencies and plugins:-

答:
you can use this configuration in pom.xml in ide->idea

```<code><properties>
    <jdk.version>1.7</jdk.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
    <plugins>
        <!-- resource plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <configuration>
                <encoding>${project.build.sourceEncoding}</encoding>
            </configuration>
        </plugin>
        <!-- compiler plugin, set JDK version -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>${jdk.version}</source>
                <target>${jdk.version}</target>
                <compilerArguments>
                    <verbose />
                    <bootclasspath>${java.home}/lib/rt.jar${path.separator}${java.home}/lib/jce.jar</bootclasspath>
                </compilerArguments>
            </configuration>
        </plugin>
        <!-- deploye plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-deploy-plugin</artifactId>
            <version>2.7</version>
            <configuration>
                <skip>false</skip>
            </configuration>
        </plugin>
        <!-- war plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.2</version>
        </plugin>

        <!-- jetty plugin -->
        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>maven-jetty-plugin</artifactId>
            <version>6.1.26</version>
            <configuration>
                <systemProperties>
                    <systemProperty>
                        <name>tomcat.port</name>
                        <value>8098</value>
                    </systemProperty>
                </systemProperties>
                <webApp>${basedir}/target/${project.artifactId}.war</webApp>
                <connectors>
                    <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                        <port>8088</port>
                    </connector>
                </connectors>
                <scanIntervalSeconds>5</scanIntervalSeconds>
                <webAppConfig>
                    <contextPath>/</contextPath>
                </webAppConfig>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

Body:
I am getting

java.lang.ClassNotFoundException: org.apache.jasper.runtime.JspApplicationContextImpl

while using jetty:run plugin on a web project.

The issue is occurring only on some machines while working on some !

Java Version Used : 7
Maven Version : 3.1

Relevant dependencies and plugins:-

Body:
you can use this configuration in pom.xml in ide->idea

<properties>
    <jdk.version>1.7</jdk.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
    <plugins>
        <!-- resource plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <configuration>
                <encoding>${project.build.sourceEncoding}</encoding>
            </configuration>
        </plugin>
        <!-- compiler plugin, set JDK version -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>${jdk.version}</source>
                <target>${jdk.version}</target>
                <compilerArguments>
                    <verbose />
                    <bootclasspath>${java.home}/lib/rt.jar${path.separator}${java.home}/lib/jce.jar</bootclasspath>
                </compilerArguments>
            </configuration>
        </plugin>
        <!-- deploye plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-deploy-plugin</artifactId>
            <version>2.7</version>
            <configuration>
                <skip>false</skip>
            </configuration>
        </plugin>
        <!-- war plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.2</version>
        </plugin>

        <!-- jetty plugin -->
        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>maven-jetty-plugin</artifactId>
            <version>6.1.26</version>
            <configuration>
                <systemProperties>
                    <systemProperty>
                        <name>tomcat.port</name>
                        <value>8098</value>
                    </systemProperty>
                </systemProperties>
                <webApp>${basedir}/target/${project.artifactId}.war</webApp>
                <connectors>
                    <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                        <port>8088</port>
                    </connector>
                </connectors>
                <scanIntervalSeconds>5</scanIntervalSeconds>
                <webAppConfig>
                    <contextPath>/</contextPath>
                </webAppConfig>
            </configuration>
        </plugin>
    </plugins>
</build>


问:
SSAS Processing Slow - SQL Server 2012
I have two SQL Server Agent jobs that run XMLA to process SSAS objects in a SQL 2012 SSAS server.

ProcessCubeFull This runs after the related SQL database has been reloaded from scratch, this is a weekly job. This job does the following:

1. Process Dimensions, ProcessFull, uses  MaxParallel="4", Time: 20 minutes

2. Process Partitions, ProcessFull, uses  MaxParallel="4", Time: 85 minutes

3. Process Cubes, ProcessFull, uses  MaxParallel="4", Time: 100 minutes

ProcessCubeUpdate This runs after the related SQL database had its daily update, this is a daily job. This job does the following:

1. Process Dimensions, ProcessUpdate, uses  MaxParallel="4",Time: 100 minutes

2. Process Partitions, ProcessData, uses  MaxParallel="4", ,Time: 15 minutes

3. Process Indexes, ProcessIndexes, uses  MaxParallel="4", Time: 55 minutes

4. Processes Cubes, ProcessDefault, uses  MaxParallel="4", Time: 1 minute

The performance of these jobs is very slow and getting slower.
It also seems odd that for the dimensions ProcessFull is a lot faster than ProcessUpdate.

I would like to know how I can speed these jobs up, or if they need some additional steps?

答: If your processing time is reasonable from your data size, I suggest you use multiple partitions for your objects</p>

Title: SSAS Processing Slow - SQL Server 2012


问:
GAS - Authentication w/ UrlFetchApp - Form to Spreadsheet
I am testing the functionality of UrlFetchApp and passing data from a Form and its Spreadsheet. I know it's possible to do this another way, however I am testing the functionality of UrlFetchApp (first time using it) within google scripts themselves, and want to get it to work with this method.

Here's the scenario I got, add a bound script to a Form App as so:

```<code>function makeRequest()
{
  var webAppUrl = "https://script.google.com/macros/s/WebAppID/exec";

  var auth = ScriptApp.getOAuthToken();
  var header = { 'Authorization': 'Bearer ' +  auth };
  var options = { 'method':'post', 'headers':header };

  var resp = UrlFetchApp.fetch(webAppUrl, options);

  Logger.log(resp);
}
</code>```

Add a bound script to the attached spreadsheet:

```<code>function doPost()
{
  var ss = SpreadsheetApp.openById('ssID');
  var name = ss.getName();
  return ContentService.createTextOutput(name);
}
</code>```

And then publish this second script attached to the sheet as a web app with only myself to have access.

Currently the above code does not work. The following error appears on the Form side of the script:

Request failed for
  https://script.google.com/macros/s/WebAppID/exec
  returned code 401. Truncated server response:
  Unauthorized
Unauthorized

Error 401

   (use muteHttpExceptions option to examine full response) (line
  12, file "Code")

Fails on the UrlFetchApp line of code.

However, if I remove the header option, then publish the web app for public use, this works just fine. Obviously this is not wanted.

What am I missing regarding authentication between scripts that I own?

Side Notes:

Anyone know why SpreadsheetApp.getActiveSheet() doesn't work when run in this fashion? That script is directly bound to a google sheet, so kind of odd.

答:
You need to get the 'Spreadsheet' object first.

```<code>SpeadsheetApp.getActive().getActiveSheet()
</code>```

However, if you are creating an add-on menu you can use 'SpreadsheetApp.getActiveSheet()'

```<code>function myFunction() {
  var lastRow = SpreadsheetApp.getActiveSheet().getLastRow();
  var range = SpreadsheetApp.getActiveSheet().getRange(lastRow, 1, 1, 26);
  SpreadsheetApp.setActiveRange(range);
}

function onOpen(e) {
  SpreadsheetApp.getUi().createAddonMenu()
      .addItem('showLastRow', 'myFunction')
      .addToUi();
}
</code>```

Body:
I am testing the functionality of UrlFetchApp and passing data from a Form and its Spreadsheet. I know it's possible to do this another way, however I am testing the functionality of UrlFetchApp (first time using it) within google scripts themselves, and want to get it to work with this method.

Here's the scenario I got, add a bound script to a Form App as so:

function makeRequest()
{
  var webAppUrl = "https://script.google.com/macros/s/WebAppID/exec";

  var auth = ScriptApp.getOAuthToken();
  var header = { 'Authorization': 'Bearer ' +  auth };
  var options = { 'method':'post', 'headers':header };

  var resp = UrlFetchApp.fetch(webAppUrl, options);

  Logger.log(resp);
}

Add a bound script to the attached spreadsheet:

function doPost()
{
  var ss = SpreadsheetApp.openById('ssID');
  var name = ss.getName();
  return ContentService.createTextOutput(name);
}

And then publish this second script attached to the sheet as a web app with only myself to have access.

Currently the above code does not work. The following error appears on the Form side of the script:

Request failed for
  https://script.google.com/macros/s/WebAppID/exec
  returned code 401. Truncated server response:
  Unauthorized
Unauthorized

Error 401

   (use muteHttpExceptions option to examine full response) (line
  12, file "Code")

Fails on the UrlFetchApp line of code.

However, if I remove the header option, then publish the web app for public use, this works just fine. Obviously this is not wanted.

What am I missing regarding authentication between scripts that I own?

Side Notes:

Anyone know why SpreadsheetApp.getActiveSheet() doesn't work when run in this fashion? That script is directly bound to a google sheet, so kind of odd.

Body:
You need to get the 'Spreadsheet' object first.

SpeadsheetApp.getActive().getActiveSheet()

However, if you are creating an add-on menu you can use 'SpreadsheetApp.getActiveSheet()'

function myFunction() {
  var lastRow = SpreadsheetApp.getActiveSheet().getLastRow();
  var range = SpreadsheetApp.getActiveSheet().getRange(lastRow, 1, 1, 26);
  SpreadsheetApp.setActiveRange(range);
}

function onOpen(e) {
  SpreadsheetApp.getUi().createAddonMenu()
      .addItem('showLastRow', 'myFunction')
      .addToUi();
}


问:
python using wald test to test the predictors significance
I need to do logistic regression for some data, I have obtained some user features such as their post types, number of friends, number of posts, number of uploaded photos and etc, and have clustered these  users into several clusters, now, I want to do wald test to test which predictors (from these user features) are significant for predicting the cluster these users belong to, using binary logistic regression, for example, for users in cluster 1, if the user belongs to cluster 1, the cluster_label is 1, and other users' cluster_label is zero, I need to use wald_test to choose which predictors are significant for predicting the cluster label, for example, for predicting users in cluster 1, by doing wald test, the number of friends and the number of uploaded photos have the highest wald score, therefore, these two features are significant for predicting users cluster type in cluster 1; maybe for users who are in cluster 2, by doing wald test, the number of posts and the number of shared news are significant for predicting these users cluster label

the pandas dataframe of these data are illustrated as follows, for predicting users in user cluster 1:

```<code>NoPosts... Friends ...  postCluster0_ratio... postCluster4_ratio  cluster_label
 24     ...   89    ...       0.35         ...        0.3              1
 ...
 ...
 81     ...  161    ...       0.2          ...        0.15              0
 ...
 ...
</code>```

when cluster_label is 1, it means that this user belongs to user cluster 1, when cluster_label is 0, it means that this user does not belong to cluster 1,and I'd like to by doing wald test to decide which predictors(from NoPosts, Frineds...postcluster0_ratio...) are significant for predicting users cluater label, but from

http://www.statsmodels.org/dev/generated/statsmodels.regression.linear_model.OLSResults.wald_test.html#statsmodels.regression.linear_model.OLSResults.wald_test
there are no examples for wald_test in python, I do not know what is the required input for wald_test, how to fit, in one word, I do not know how to use wald_test for my case, could you please help me how to use wald_test, it is better for providing me the code

答:
For individual tests (not joint hypothesis) you can use the t_test which is a special case of the Wald test http://www.statsmodels.org/dev/generated/statsmodels.regression.linear_model.OLSResults.t_test.html

The pvalues for the tests whether the parameters are statistically significant from zero are in summary() and are precomputed, see pvalues in http://www.statsmodels.org/dev/generated/statsmodels.regression.linear_model.RegressionResults.html

wald_test is the more general version of the f_test for joint hypothesis which has some examples that work in the same way for wald_test
http://www.statsmodels.org/dev/generated/statsmodels.regression.linear_model.OLSResults.f_test.html

Body:
I need to do logistic regression for some data, I have obtained some user features such as their post types, number of friends, number of posts, number of uploaded photos and etc, and have clustered these  users into several clusters, now, I want to do wald test to test which predictors (from these user features) are significant for predicting the cluster these users belong to, using binary logistic regression, for example, for users in cluster 1, if the user belongs to cluster 1, the cluster_label is 1, and other users' cluster_label is zero, I need to use wald_test to choose which predictors are significant for predicting the cluster label, for example, for predicting users in cluster 1, by doing wald test, the number of friends and the number of uploaded photos have the highest wald score, therefore, these two features are significant for predicting users cluster type in cluster 1; maybe for users who are in cluster 2, by doing wald test, the number of posts and the number of shared news are significant for predicting these users cluster label

the pandas dataframe of these data are illustrated as follows, for predicting users in user cluster 1:

NoPosts... Friends ...  postCluster0_ratio... postCluster4_ratio  cluster_label
 24     ...   89    ...       0.35         ...        0.3              1
 ...
 ...
 81     ...  161    ...       0.2          ...        0.15              0
 ...
 ...

when cluster_label is 1, it means that this user belongs to user cluster 1, when cluster_label is 0, it means that this user does not belong to cluster 1,and I'd like to by doing wald test to decide which predictors(from NoPosts, Frineds...postcluster0_ratio...) are significant for predicting users cluater label, but from

http://www.statsmodels.org/dev/generated/statsmodels.regression.linear_model.OLSResults.wald_test.html#statsmodels.regression.linear_model.OLSResults.wald_test
there are no examples for wald_test in python, I do not know what is the required input for wald_test, how to fit, in one word, I do not know how to use wald_test for my case, could you please help me how to use wald_test, it is better for providing me the code


问:
groupby in Pandas -Python
I am getting an error message when I try to perform an operation in a groupby object which I do not understand.

For a reproducible example consider the following:

```<code>import pandas as pd

species_plots_types

 record_id  plot_id plot_type   species_id
    0       1   2   Control NL
    2194    2   3   Long-term Krat Exclosure    NL
    1       3   2   Control DM
    4022    4   7   Rodent Exclosure    DM
    2195    5   3   Long-term Krat Exclosure    DM
    4838    6   1   Spectab exclosure   PF
    2       7   2   Control PE
    4839    8   1   Spectab exclosure   DM
    4840    9   1   Spectab exclosure   DM
    6833    10  6   Short-term Krat Exclosure   PF
    8415    11  5   Rodent Exclosure    DS
    4023    12  7   Rodent Exclosure    DM
    2196    13  3   Long-term Krat Exclosure    DM
    9609    14  8   Control DM
    6834    15  6   Short-term Krat Exclosure   DM

species_plots_types.groupby["plot_type"].size().to_frame()

TypeError: 'method' object is not subscriptable

species_plots_types.groupby["plot_type"].count()

TypeError: 'method' object is not subscriptable
</code>```

Your advice will be appreciated.

答:
You need ():

```<code>species_plots_types.groupby("plot_type").size().to_frame()
</code>```

Or:

```<code>species_plots_types.groupby("plot_type").count()
</code>```

Explanation:

groupby["plot_type"] means you call __getitem__ on groupby, but since this method isn't defined, you get a TypeError: 'type' object is not subscriptable. Check python documentation for getitem for more details.

Title: groupby in Pandas -Python

Body:
I am getting an error message when I try to perform an operation in a groupby object which I do not understand.

For a reproducible example consider the following:

import pandas as pd

species_plots_types

 record_id  plot_id plot_type   species_id
    0       1   2   Control NL
    2194    2   3   Long-term Krat Exclosure    NL
    1       3   2   Control DM
    4022    4   7   Rodent Exclosure    DM
    2195    5   3   Long-term Krat Exclosure    DM
    4838    6   1   Spectab exclosure   PF
    2       7   2   Control PE
    4839    8   1   Spectab exclosure   DM
    4840    9   1   Spectab exclosure   DM
    6833    10  6   Short-term Krat Exclosure   PF
    8415    11  5   Rodent Exclosure    DS
    4023    12  7   Rodent Exclosure    DM
    2196    13  3   Long-term Krat Exclosure    DM
    9609    14  8   Control DM
    6834    15  6   Short-term Krat Exclosure   DM

species_plots_types.groupby["plot_type"].size().to_frame()

TypeError: 'method' object is not subscriptable

species_plots_types.groupby["plot_type"].count()

TypeError: 'method' object is not subscriptable

Your advice will be appreciated.

Body:
You need ():

species_plots_types.groupby("plot_type").size().to_frame()

Or:

species_plots_types.groupby("plot_type").count()

Explanation:

groupby["plot_type"] means you call __getitem__ on groupby, but since this method isn't defined, you get a TypeError: 'type' object is not subscriptable. Check python documentation for getitem for more details.


问:
Stop reading bytes from serial port (Python/RPi/UART)
This problem is quite complicated. Seemingly I have simple two-way communication beetwen 2 devices where reading side is Raspberry pi 3. I'm trying to transfer file. I'm sending it part by part (5kb part). It looks like:

1) Sending side send first 5kb part (exactly 5136 bytes where first 16 bytes are ID/SIZE/ADD_INFO/CRC)

2) RPi3 read 5136 bytes, and calculate CRC for chunk.

3) RPi3 compare CRC received from sending side and calculated by RPi

4a) If CRC doesn't match I switch lanes from RX to TX line using Dual Bus Buffer Gate With 3-State Outputs and set High State at TX line (I keep it for 30ms).

4b) If CRC match I just wait for next chunk of file

5) Sending side switch lanes too and read my TX state if state is HIGH/1 (when CRC doesn't match) it sends same chunk (retransmission) if state is LOW/0 sends another chunk. (changing state take 10 ms)

On osciloscope it looks like this (4a):

and this (4b):

Beetwen 5136 chunk there is free time to calculate CRC then we have on RPi3 side changing state if we have to because CRC doesn't match (red lines at 4a) and reading TX side from Sending side.

Ok now some simplified code from RPi:

```<code>def recv():
    while True:
        #Set line to low because I want to read data
        GPIO.output(16, GPIO.LOW)
        ID = ser.read(4)
        SIZE = ser.read(4)
        ADD_INFO = ser.read(4)
        CRC = ser.read(4)
        #get crc from sending side
        crc_chunk = int.from_bytes(CRC, byteorder='little')
        data = ser.read(5120)
        #calculating CRC from chunk
        rpiCRC = crcSTM(data)

        while True:
             <--- here I wait about 20ms to calculate CRC
            if rpiCRC != crc_chunk:
                #Crc doesn't match I want retransmission
                GPIO.output(16, GPIO.HIGH)
                <--- keep it HIGH for about 30ms
                break

            else:
                #keep it low because crc match and we are waiting for next chunk
                GPIO.output(16, GPIO.HIGH)
                break
</code>```

All this looks legit but to the point. I always get only first chunk after that RPi just stop reading bytes. It only happen in case '4b' I get first chunk properly and I'm waiting for next one and then RPi just stop reading bytes or give me just some scratches from time to time. I test what If i get first chunk properly and set retransmission thing but everything looks great and I was getting all the time retransmission of first chunk and get it all the time. I came to this that changing line on sending side when I have LOW/1 state affects on RPi and it just stop reading bytes properly. Don't know why it's messing it and don't know how to fight it. I tryied  flushing buffer, closing port before sending side chaning line and open it after it changes line again but all this just do nothing what can I do more ?

P.S This waiting things i do in my own timer but there is no need to put here code like code from sending side because problem is on RPi side.
P.S sorry for chaotic language but I was trying do explane it as simply as i can

答: Ok I fight it. I have enabled option "Would you like a login shell to be accessible over serial" in sudo raspi-congif. Don't know why this was messing everything but disabling this fix it. This is quite strange because I'm playing with raspberry and serial some time and there was no problem if RPi3 was sending something via uart or when it was just reading without changing lines etc :)

Body:
This problem is quite complicated. Seemingly I have simple two-way communication beetwen 2 devices where reading side is Raspberry pi 3. I'm trying to transfer file. I'm sending it part by part (5kb part). It looks like:

1) Sending side send first 5kb part (exactly 5136 bytes where first 16 bytes are ID/SIZE/ADD_INFO/CRC)

2) RPi3 read 5136 bytes, and calculate CRC for chunk.

3) RPi3 compare CRC received from sending side and calculated by RPi

4a) If CRC doesn't match I switch lanes from RX to TX line using Dual Bus Buffer Gate With 3-State Outputs and set High State at TX line (I keep it for 30ms).

4b) If CRC match I just wait for next chunk of file

5) Sending side switch lanes too and read my TX state if state is HIGH/1 (when CRC doesn't match) it sends same chunk (retransmission) if state is LOW/0 sends another chunk. (changing state take 10 ms)

On osciloscope it looks like this (4a):

and this (4b):

Beetwen 5136 chunk there is free time to calculate CRC then we have on RPi3 side changing state if we have to because CRC doesn't match (red lines at 4a) and reading TX side from Sending side.

Ok now some simplified code from RPi:

def recv():
    while True:
        #Set line to low because I want to read data
        GPIO.output(16, GPIO.LOW)
        ID = ser.read(4)
        SIZE = ser.read(4)
        ADD_INFO = ser.read(4)
        CRC = ser.read(4)
        #get crc from sending side
        crc_chunk = int.from_bytes(CRC, byteorder='little')
        data = ser.read(5120)
        #calculating CRC from chunk
        rpiCRC = crcSTM(data)

        while True:
             <--- here I wait about 20ms to calculate CRC
            if rpiCRC != crc_chunk:
                #Crc doesn't match I want retransmission
                GPIO.output(16, GPIO.HIGH)
                <--- keep it HIGH for about 30ms
                break

            else:
                #keep it low because crc match and we are waiting for next chunk
                GPIO.output(16, GPIO.HIGH)
                break

All this looks legit but to the point. I always get only first chunk after that RPi just stop reading bytes. It only happen in case '4b' I get first chunk properly and I'm waiting for next one and then RPi just stop reading bytes or give me just some scratches from time to time. I test what If i get first chunk properly and set retransmission thing but everything looks great and I was getting all the time retransmission of first chunk and get it all the time. I came to this that changing line on sending side when I have LOW/1 state affects on RPi and it just stop reading bytes properly. Don't know why it's messing it and don't know how to fight it. I tryied  flushing buffer, closing port before sending side chaning line and open it after it changes line again but all this just do nothing what can I do more ?

P.S This waiting things i do in my own timer but there is no need to put here code like code from sending side because problem is on RPi side.
P.S sorry for chaotic language but I was trying do explane it as simply as i can


问:
Pandas ParserError EOF character when reading multiple csv files to HDF5
Using Python3, Pandas 0.12

I'm trying to write multiple csv files (total size is 7.9 GB) to a HDF5 store to process later onwards. The csv files contain around a million of rows each, 15 columns and data types are mostly strings, but some floats. However when I'm trying to read the csv files I get the following error:

```<code>Traceback (most recent call last):
  File "filter-1.py", line 38, in <module>
    to_hdf()
  File "filter-1.py", line 31, in to_hdf
    for chunk in reader:
  File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 578, in __iter__
    yield self.read(self.chunksize)
  File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 608, in read
    ret = self._engine.read(nrows)
  File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 1028, in read
    data = self._reader.read(nrows)
  File "parser.pyx", line 706, in pandas.parser.TextReader.read (pandas\parser.c:6745)
  File "parser.pyx", line 740, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:7146)
  File "parser.pyx", line 781, in pandas.parser.TextReader._read_rows (pandas\parser.c:7568)
  File "parser.pyx", line 768, in pandas.parser.TextReader._tokenize_rows (pandas\parser.c:7451)
  File "parser.pyx", line 1661, in pandas.parser.raise_parser_error (pandas\parser.c:18744)
pandas.parser.CParserError: Error tokenizing data. C error: EOF inside string starting at line 754991
Closing remaining open files: ta_store.h5... done
</code>```

Edit:

I managed to find a file that produced this problem. I think it's reading an EOF character. However I have no clue to overcome this problem. Given the large size of the combined files I think it's too cumbersome to check each single character in each string. (Even then I would still not be sure what to do.) As far as I checked, there are no strange characters in the csv files that could raise the error.
I also tried passing error_bad_lines=False to pd.read_csv(), but the error persists.

My code is the following:

```<code># -*- coding: utf-8 -*-

import pandas as pd
import os
from glob import glob

def list_files(path=os.getcwd()):
    ''' List all files in specified path '''
    list_of_files = [f for f in glob('2013-06*.csv')]
    return list_of_files

def to_hdf():
    """ Function that reads multiple csv files to HDF5 Store """
    # Defining path name
    path = 'ta_store.h5'
    # If path exists delete it such that a new instance can be created
    if os.path.exists(path):
        os.remove(path)
    # Creating HDF5 Store
    store = pd.HDFStore(path)

    # Reading csv files from list_files function
    for f in list_files():
        # Creating reader in chunks -- reduces memory load
        reader = pd.read_csv(f, chunksize=50000)
        # Looping over chunks and storing them in store file, node name 'ta_data'
        for chunk in reader:
            chunk.to_hdf(store, 'ta_data', mode='w', table=True)

    # Return store
    return store.select('ta_data')
    return 'Finished reading to HDF5 Store, continuing processing data.'

to_hdf()
</code>```

Edit

If I go into the CSV file that raises the CParserError EOF... and manually delete all rows after the line that is causing the problem, the csv file is read properly. However all I'm deleting are blank rows anyway.
The weird thing is that when I manually correct the erroneous csv files, they are loaded fine into the store individually. But when I again use a list of multiple files the 'false' files still return me errors.

答:
The solution is to use the parameter engine=’python’ in the read_csv function. The Pandas CSV parser can use two different “engines” to parse a CSV file – Python or C (which is also the default).

```<code>pandas.read_csv(filepath, sep=',', delimiter=None,
            header='infer', names=None,
            index_col=None, usecols=None, squeeze=False,
            ..., engine=None, ...)
</code>```

The Python engine is described to be “slower, but is more feature complete” in the Pandas documentation.

```<code>engine : {‘c’, ‘python’}
</code>```

Body:
Using Python3, Pandas 0.12

I'm trying to write multiple csv files (total size is 7.9 GB) to a HDF5 store to process later onwards. The csv files contain around a million of rows each, 15 columns and data types are mostly strings, but some floats. However when I'm trying to read the csv files I get the following error:

Traceback (most recent call last):
  File "filter-1.py", line 38, in <module>
    to_hdf()
  File "filter-1.py", line 31, in to_hdf
    for chunk in reader:
  File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 578, in __iter__
    yield self.read(self.chunksize)
  File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 608, in read
    ret = self._engine.read(nrows)
  File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 1028, in read
    data = self._reader.read(nrows)
  File "parser.pyx", line 706, in pandas.parser.TextReader.read (pandas\parser.c:6745)
  File "parser.pyx", line 740, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:7146)
  File "parser.pyx", line 781, in pandas.parser.TextReader._read_rows (pandas\parser.c:7568)
  File "parser.pyx", line 768, in pandas.parser.TextReader._tokenize_rows (pandas\parser.c:7451)
  File "parser.pyx", line 1661, in pandas.parser.raise_parser_error (pandas\parser.c:18744)
pandas.parser.CParserError: Error tokenizing data. C error: EOF inside string starting at line 754991
Closing remaining open files: ta_store.h5... done

Edit:

I managed to find a file that produced this problem. I think it's reading an EOF character. However I have no clue to overcome this problem. Given the large size of the combined files I think it's too cumbersome to check each single character in each string. (Even then I would still not be sure what to do.) As far as I checked, there are no strange characters in the csv files that could raise the error.
I also tried passing error_bad_lines=False to pd.read_csv(), but the error persists.

My code is the following:

# -*- coding: utf-8 -*-

import pandas as pd
import os
from glob import glob

def list_files(path=os.getcwd()):
    ''' List all files in specified path '''
    list_of_files = [f for f in glob('2013-06*.csv')]
    return list_of_files

def to_hdf():
    """ Function that reads multiple csv files to HDF5 Store """
    # Defining path name
    path = 'ta_store.h5'
    # If path exists delete it such that a new instance can be created
    if os.path.exists(path):
        os.remove(path)
    # Creating HDF5 Store
    store = pd.HDFStore(path)

    # Reading csv files from list_files function
    for f in list_files():
        # Creating reader in chunks -- reduces memory load
        reader = pd.read_csv(f, chunksize=50000)
        # Looping over chunks and storing them in store file, node name 'ta_data'
        for chunk in reader:
            chunk.to_hdf(store, 'ta_data', mode='w', table=True)

    # Return store
    return store.select('ta_data')
    return 'Finished reading to HDF5 Store, continuing processing data.'

to_hdf()

Edit

If I go into the CSV file that raises the CParserError EOF... and manually delete all rows after the line that is causing the problem, the csv file is read properly. However all I'm deleting are blank rows anyway.
The weird thing is that when I manually correct the erroneous csv files, they are loaded fine into the store individually. But when I again use a list of multiple files the 'false' files still return me errors.

Body:
The solution is to use the parameter engine=’python’ in the read_csv function. The Pandas CSV parser can use two different “engines” to parse a CSV file – Python or C (which is also the default).

pandas.read_csv(filepath, sep=',', delimiter=None,
            header='infer', names=None,
            index_col=None, usecols=None, squeeze=False,
            ..., engine=None, ...)

The Python engine is described to be “slower, but is more feature complete” in the Pandas documentation.

engine : {‘c’, ‘python’}


答:
When the backslash \ does not escape the terminating quote of the string or otherwise create a valid escape sequence (in double quoted strings), then either of these work to produce one backslash:

```<code>$string = 'abc\def';
$string = "abc\def";
//
$string = 'abc\\def';
$string = "abc\\def";
</code>```

When escaping the next character would cause a parse error (terminating quote of the string) or a valid escape sequence (in double quoted strings) then the backslash needs to be escaped:

```<code>$string = 'abcdef\\';
$string = "abcdef\\";

$string = 'abc\012';
$string = "abc\\012";
</code>```

Body:
When the backslash \ does not escape the terminating quote of the string or otherwise create a valid escape sequence (in double quoted strings), then either of these work to produce one backslash:

$string = 'abc\def';
$string = "abc\def";
//
$string = 'abc\\def';
$string = "abc\\def";

When escaping the next character would cause a parse error (terminating quote of the string) or a valid escape sequence (in double quoted strings) then the backslash needs to be escaped:

$string = 'abcdef\\';
$string = "abcdef\\";

$string = 'abc\012';
$string = "abc\\012";

ContentLicense: CC BY-SA 4.0


问:
Grouping numeric distribution in R
I have moved to R very recently and enjoying it ,so is there any way to group X values in R? I want to group by 10 and frequency would occur accordingly?

count(delivery_days)# delivery_days is the table X is delivery time taken for one product and freq I've gathered by the count code in R.

```<code>    x freq
1   3    1
2   4    1
3   5    1
4  10    1
5  12    2
6  25    3
7  32    1
8  45    1
9  65    1
10 78    1
</code>```

Is there any packages need installing to get it or else please let me know .

答:
Your question in not much clear,but as far as i have understood,you want to extract all X = 10 to be grouped ad one dataframe with all columns available.

Since delivery_days is your table name.

```<code>new_table <- delivery_days[delivery_days$X == 10,]
</code>```

Title: Grouping numeric distribution in R

Body:
I have moved to R very recently and enjoying it ,so is there any way to group X values in R? I want to group by 10 and frequency would occur accordingly?

count(delivery_days)# delivery_days is the table X is delivery time taken for one product and freq I've gathered by the count code in R.

    x freq
1   3    1
2   4    1
3   5    1
4  10    1
5  12    2
6  25    3
7  32    1
8  45    1
9  65    1
10 78    1

Is there any packages need installing to get it or else please let me know .

Body:
Your question in not much clear,but as far as i have understood,you want to extract all X = 10 to be grouped ad one dataframe with all columns available.

Since delivery_days is your table name.

new_table <- delivery_days[delivery_days$X == 10,]


问:
Accessing Model Through Custom Class
I'm trying to access a model through a class.
I'm trying to get this done on a Laravel 5.5 installation.
The folder structure is the default except for I have a folder in App/Libraries that holds my custom classes.

My issue is I get the below error when I'm trying to access a model through my class. Probably a namespace issue, but I just can't seem to find it. It's looking at the wrong place.

The error is

Class 'App\Libraries\App\AccountsModel' not found

Below is my code.

app/Libraries/Account.php

```<code><?php
namespace App\Libraries;
use App\AccountsModel;
class Account {

public $accountNum;
    public $accountDescription;
    public $isMainAccount;
    public $parentAccount;
    public $createTime;
    public $updatedTime;

    public function getInfo($accountNum)
    {
        $account = App\AccountsModel::where('accountNumber', $accountNum)->take(1)->get(); //Error coming up due to this line
        //return $account;
        //return $this;
    }
}
?>
</code>```

app\AccountsModel.php

```<code><?php
namespace App\AccountsModel;
use Illuminate\Database\Eloquent\Model;

class AccountsModel extends Model
{
    protected $table = 'accounts';

}
</code>```

app/Http/Controllers/AccountsController.php

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Libraries\Account;

class AccountsController extends Controller
{
    public function create()
    {
        $account = new Account;
        var_dump($account->getInfo("1-1000"));
    }
}
</code>```

I'm autoloading the model on composer.json as below.
Any input on the below is also appreciated.
I tried echoing the class name on a construct in the model, with no echo so I'm guessing I'm autoloading this incorrectly too.

```<code>"autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/",
            "AccountsModel\\" : "app/AccountsModel.php"
        }
    },
</code>```

Ultimately I'm trying to access the model through my custom Account class when I get the error.
Any help is greatly appreciated.

答:
In your app/AccountsModel.php file the namespace should be App

```<code>namespace App;
</code>```

and there's no need of the following entry in composer.json file

```<code>"AccountsModel\\" : "app/AccountsModel.php"
</code>```

Title: Accessing Model Through Custom Class

Body:
I'm trying to access a model through a class.
I'm trying to get this done on a Laravel 5.5 installation.
The folder structure is the default except for I have a folder in App/Libraries that holds my custom classes.

My issue is I get the below error when I'm trying to access a model through my class. Probably a namespace issue, but I just can't seem to find it. It's looking at the wrong place.

The error is

Class 'App\Libraries\App\AccountsModel' not found

Below is my code.

app/Libraries/Account.php

<?php
namespace App\Libraries;
use App\AccountsModel;
class Account {

public $accountNum;
    public $accountDescription;
    public $isMainAccount;
    public $parentAccount;
    public $createTime;
    public $updatedTime;

    public function getInfo($accountNum)
    {
        $account = App\AccountsModel::where('accountNumber', $accountNum)->take(1)->get(); //Error coming up due to this line
        //return $account;
        //return $this;
    }
}
?>

app\AccountsModel.php

<?php
namespace App\AccountsModel;
use Illuminate\Database\Eloquent\Model;

class AccountsModel extends Model
{
    protected $table = 'accounts';

}

app/Http/Controllers/AccountsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Libraries\Account;

class AccountsController extends Controller
{
    public function create()
    {
        $account = new Account;
        var_dump($account->getInfo("1-1000"));
    }
}

I'm autoloading the model on composer.json as below.
Any input on the below is also appreciated.
I tried echoing the class name on a construct in the model, with no echo so I'm guessing I'm autoloading this incorrectly too.

"autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/",
            "AccountsModel\\" : "app/AccountsModel.php"
        }
    },

Ultimately I'm trying to access the model through my custom Account class when I get the error.
Any help is greatly appreciated.

Body:
In your app/AccountsModel.php file the namespace should be App

namespace App;

and there's no need of the following entry in composer.json file

"AccountsModel\\" : "app/AccountsModel.php"


问:
How to restore data for individual app from iCloud?
I accidentally deleted an app on the iPhone. The data was lost as well. The data was backed up on iCloud only. How can I restore that app with data from iCloud without restore entire system?

Thanks

答:
The answer @LordNeckbeard gave is the “ALL or Nothing” iCloud restore. You get everything in the iCloud backup, or you get nothing from it. Apple doesn’t allow users to selectively restore apps from iCloud.

But you can try some iPhone data restore tool for example iMyFone D-Port Pro. It supports to restore only one apps from backups.


问:
jquery passing string reference to object as parameter to function
I'm not sure wether to pass an $(object) or a string referencing the name of an object to a function:

```<code>function makeObject(div){
    var newDiv = $(div);
    $(div).html("newDiv: " + newDiv);
    }
</code>```

and caller:

```<code><div id="myDiv">
<a href="#" onclick="makeObject($(this).parent().attr('id'));">makeObject(this</a>
</div>
</code>```

I hope this is clear. It's a test function to get the principle in my head. Thanks in advance.

答:
You need to pass a valid selector, in case of id selector add # prefix in the string.

```<code>onclick="makeObject('#' + $(this).parent().attr('id'));"
</code>```

Or simply pass the parent element jQuery object. In this case, you don't need to wrap it using jQuery again inside the function.

```<code>onclick="makeObject($(this).parent());"
</code>```

Body:
I'm not sure wether to pass an $(object) or a string referencing the name of an object to a function:

function makeObject(div){
    var newDiv = $(div);
    $(div).html("newDiv: " + newDiv);
    }

and caller:

makeObject(this

I hope this is clear. It's a test function to get the principle in my head. Thanks in advance.

Body:
You need to pass a valid selector, in case of id selector add # prefix in the string.

onclick="makeObject('#' + $(this).parent().attr('id'));"

Or simply pass the parent element jQuery object. In this case, you don't need to wrap it using jQuery again inside the function.

onclick="makeObject($(this).parent());"


问:
Find ulimit -a for other users
Is anyone aware of a way to find the "ulimit -a" values for another user in Linux? I want user A to be able to check User B's ulimit values. Assumptions are the User A and User B are non-root users.

Thanks in advance

答:
Pancho's answer is correct, but sometimes you may get an error like this:

```<code>su - www-data -c "ulimit -n"
</code>```

No directory, logging in with HOME=/

This account is currently not available.

You may specify a shell to overcome this:

```<code>su www-data --shell /bin/bash --command "ulimit -aH"
</code>```

( -aH give you hard limit, -aS give you soft limit )

Title: Find ulimit -a for other users

Body:
Pancho's answer is correct, but sometimes you may get an error like this:

su - www-data -c "ulimit -n"

No directory, logging in with HOME=/

This account is currently not available.

You may specify a shell to overcome this:

su www-data --shell /bin/bash --command "ulimit -aH"

( -aH give you hard limit, -aS give you soft limit )


问:
ASP.Net JSON configuration file transforms with arrays
I have a base configuration file eg.

appsettings.json

```<code>{
    "Values": {
        "Test": ["one", "two"]
    }
}
</code>```

and

appsettings.dev.json

```<code>{
    "Values": {
        "Test": ["three"]
    }
}
</code>```

and after transforming, the array would be

```<code>["three", "two"]
</code>```

How do I make sure the transformed array is shrunk to a smaller number of elements rather than each element changing individually?

答:
To understand the cause of such 'strange' behavior for overridden array settings you need to understand how those settings are stored inside configuration providers.

The reality is that all loaded settings are stored in dictionaries, own for each configuration provider. Keys are built from setting paths where nested sections are delimited with a colon.
Array settings are stored in the same dictionary with an index in setting path (:0, :1, ...).

For configuration you described you will have 2 configuration providers with following sets of settings:

```<code>provider1[Values:Test:0] = "one"
provider1[Values:Test:1] = "two"
</code>```

and

```<code>provider2[Values:Test:0] = "three"
</code>```

Now it's clear why the final value of array setting is ["three", "two"]. Values:Test:0 from the second provider overrides the same setting from the first provider, and Values:Test:1 is left untouched.

Unfortunately, there is now a built-in possibility to overcome this problem. Fortunately, .net core configuration model is flexible enough for adjusting this behavior for your needs.

Idea is the following:

Enumerate configuration providers in reverse order.

For each provider get all its setting keys. You could call IConfigurationProvider.GetChildKeys() method recursively for this purpose. See GetProviderKeys() in below snippet.

With a regular expression check whether current key is an array entry.

If it is and some of previous providers overrides this array, then just suppress current array entry by setting it to null value.

If it's unseen array then current provider is marked as the only provider of values for this array. Arrays from all other providers will be suppressed (step #4).

For convenience you could wrap all this logic into extension method on IConfigurationRoot.

Here is a working sample:

```<code>public static class ConfigurationRootExtensions
{
    private static readonly Regex ArrayKeyRegex = new Regex("^(.+):\\d+$", RegexOptions.Compiled);

    public static IConfigurationRoot FixOverridenArrays(this IConfigurationRoot configurationRoot)
    {
        HashSet<string> knownArrayKeys = new HashSet<string>();

        foreach (IConfigurationProvider provider in configurationRoot.Providers.Reverse())
        {
            HashSet<string> currProviderArrayKeys = new HashSet<string>();

            foreach (var key in GetProviderKeys(provider, null).Reverse())
            {
                //  Is this an array value?
                var match = ArrayKeyRegex.Match(key);
                if (match.Success)
                {
                    var arrayKey = match.Groups[1].Value;
                    //  Some provider overrides this array.
                    //  Suppressing the value.
                    if (knownArrayKeys.Contains(arrayKey))
                    {
                        provider.Set(key, null);
                    }
                    else
                    {
                        currProviderArrayKeys.Add(arrayKey);
                    }
                }
            }

            foreach (var key in currProviderArrayKeys)
            {
                knownArrayKeys.Add(key);
            }
        }

        return configurationRoot;
    }

    private static IEnumerable<string> GetProviderKeys(IConfigurationProvider provider,
        string parentPath)
    {
        var prefix = parentPath == null
                ? string.Empty
                : parentPath + ConfigurationPath.KeyDelimiter;

        List<string> keys = new List<string>();
        var childKeys = provider.GetChildKeys(Enumerable.Empty<string>(), parentPath)
            .Distinct()
            .Select(k => prefix + k).ToList();
        keys.AddRange(childKeys);
        foreach (var key in childKeys)
        {
            keys.AddRange(GetProviderKeys(provider, key));
        }

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

The last thing is to call it when building the configuration:

```<code>IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("AppSettings.json")
    .AddJsonFile("appsettings.dev.json");
var configuration = configurationBuilder.Build();
configuration.FixOverridenArrays();
</code>```

Body:
I have a base configuration file eg.

appsettings.json

{
    "Values": {
        "Test": ["one", "two"]
    }
}

and

appsettings.dev.json

{
    "Values": {
        "Test": ["three"]
    }
}

and after transforming, the array would be

["three", "two"]

How do I make sure the transformed array is shrunk to a smaller number of elements rather than each element changing individually?

Body:
To understand the cause of such 'strange' behavior for overridden array settings you need to understand how those settings are stored inside configuration providers.

The reality is that all loaded settings are stored in dictionaries, own for each configuration provider. Keys are built from setting paths where nested sections are delimited with a colon.
Array settings are stored in the same dictionary with an index in setting path (:0, :1, ...).

For configuration you described you will have 2 configuration providers with following sets of settings:

provider1[Values:Test:0] = "one"
provider1[Values:Test:1] = "two"

and

provider2[Values:Test:0] = "three"

Now it's clear why the final value of array setting is ["three", "two"]. Values:Test:0 from the second provider overrides the same setting from the first provider, and Values:Test:1 is left untouched.

Unfortunately, there is now a built-in possibility to overcome this problem. Fortunately, .net core configuration model is flexible enough for adjusting this behavior for your needs.

Idea is the following:

Enumerate configuration providers in reverse order.

For each provider get all its setting keys. You could call IConfigurationProvider.GetChildKeys() method recursively for this purpose. See GetProviderKeys() in below snippet.

With a regular expression check whether current key is an array entry.

If it is and some of previous providers overrides this array, then just suppress current array entry by setting it to null value.

If it's unseen array then current provider is marked as the only provider of values for this array. Arrays from all other providers will be suppressed (step #4).

For convenience you could wrap all this logic into extension method on IConfigurationRoot.

Here is a working sample:

public static class ConfigurationRootExtensions
{
    private static readonly Regex ArrayKeyRegex = new Regex("^(.+):\\d+$", RegexOptions.Compiled);

    public static IConfigurationRoot FixOverridenArrays(this IConfigurationRoot configurationRoot)
    {
        HashSet<string> knownArrayKeys = new HashSet<string>();

        foreach (IConfigurationProvider provider in configurationRoot.Providers.Reverse())
        {
            HashSet<string> currProviderArrayKeys = new HashSet<string>();

            foreach (var key in GetProviderKeys(provider, null).Reverse())
            {
                //  Is this an array value?
                var match = ArrayKeyRegex.Match(key);
                if (match.Success)
                {
                    var arrayKey = match.Groups[1].Value;
                    //  Some provider overrides this array.
                    //  Suppressing the value.
                    if (knownArrayKeys.Contains(arrayKey))
                    {
                        provider.Set(key, null);
                    }
                    else
                    {
                        currProviderArrayKeys.Add(arrayKey);
                    }
                }
            }

            foreach (var key in currProviderArrayKeys)
            {
                knownArrayKeys.Add(key);
            }
        }

        return configurationRoot;
    }

    private static IEnumerable<string> GetProviderKeys(IConfigurationProvider provider,
        string parentPath)
    {
        var prefix = parentPath == null
                ? string.Empty
                : parentPath + ConfigurationPath.KeyDelimiter;

        List<string> keys = new List<string>();
        var childKeys = provider.GetChildKeys(Enumerable.Empty<string>(), parentPath)
            .Distinct()
            .Select(k => prefix + k).ToList();
        keys.AddRange(childKeys);
        foreach (var key in childKeys)
        {
            keys.AddRange(GetProviderKeys(provider, key));
        }

        return keys;
    }
}

The last thing is to call it when building the configuration:

IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("AppSettings.json")
    .AddJsonFile("appsettings.dev.json");
var configuration = configurationBuilder.Build();
configuration.FixOverridenArrays();


问:
Find a number in a string after specific set of strings and characters
I am a python noob and am having trouble trying to extract a number. Its a SQL query, but i turned it into a string type. If there's a better way to do this, please let me know as well. My string contains many words that are similar, so I want to extract the number after a distinct set of words.

Example

```<code>{'first_name': 'Abigail', 'last_name': 'Smith', 'updated': '2017-12-04 22:12:24.699-08', 'account_id': '338502', 'created': '2017-12-04 22:12:24.699-08', 'student_id': '1730', 'notes': '', 'school_id': '16', 'major_id': '20', 'status': 'OPEN', 'id': '37'}
</code>```

Out of this, I want to extract the "37" from they key "id". Store it in a variable

I tried it with .split(), but I am not sure that works because there are characters that don't work with the index because of the apostrophes and the colon. I know that there is a way to use SQL to get result (query.get('id')), but I want to know a way to extract this in a string.

Please help! Thank you!

Body:
I am a python noob and am having trouble trying to extract a number. Its a SQL query, but i turned it into a string type. If there's a better way to do this, please let me know as well. My string contains many words that are similar, so I want to extract the number after a distinct set of words.

Example

{'first_name': 'Abigail', 'last_name': 'Smith', 'updated': '2017-12-04 22:12:24.699-08', 'account_id': '338502', 'created': '2017-12-04 22:12:24.699-08', 'student_id': '1730', 'notes': '', 'school_id': '16', 'major_id': '20', 'status': 'OPEN', 'id': '37'}

Out of this, I want to extract the "37" from they key "id". Store it in a variable

I tried it with .split(), but I am not sure that works because there are characters that don't work with the index because of the apostrophes and the colon. I know that there is a way to use SQL to get result (query.get('id')), but I want to know a way to extract this in a string.

Please help! Thank you!

Body:
this looks like a dictionary - so you can simply access it by set["id"]

di = {'first_name': 'Abigail', 'last_name': 'Smith', 'updated': '2017-12-04 22:12:24.699-08', 'account_id': '338502', 'created': '2017-12-04 22:12:24.699-08', 'student_id': '1730', 'notes': '', 'school_id': '16', 'major_id': '20', 'status': 'OPEN', 'id': '37'}

print(di["id"])

Output:

37

Done.

If it is a string, you can split it into a dict like this:

di = "{'first_name': 'Abigail', 'last_name': 'Smith', 'updated': '2017-12-04 22:12:24.699-08', 'account_id': '338502', 'created': '2017-12-04 22:12:24.699-08', 'student_id': '1730', 'notes': '', 'school_id': '16', 'major_id': '20', 'status': 'OPEN', 'id': '37'}"

pairs = [x.replace("'","").strip("{}") for x in di.split(",")]
dic = dict( [ x.replace("'","").strip().split(":",1) for x in pairs] )
print(dic)
print(dic ["id"])

Output:

{'first_name': ' Abigail', 'last_name': ' Smith', 'updated': ' 2017-12-04 22:12:24.699-08', 'account_id': ' 338502', 'created': ' 2017-12-04 22:12:24.699-08', 'student_id': ' 1730', 'notes': '', 'school_id': ' 16', 'major_id': ' 20', 'status': ' OPEN', 'id': ' 37'}
 37


问:
What's the meaning of attribute 'msgid' in strings.xml?
What's the meaning of attribute 'msgid' in strings.xml ?

How to get its value?

答:
Attribute "msgid" is present in strings.xml if you are using string localization. For example, if you have alternate application strings for Spanish in the folder values-es, values.xml will contain "msgid".

When I look at the strings.xml for Spanish I see some long values like

8340973892742019101

What is interesting is that strings.xml for Italian and other languages contains the same msgid for the same string.

The only thing that comes to my mind is that it are some unique resource IDs, produced internally by the application. So, I do not think it makes sense to search for additional meaning in them. They are unique within the application, and that is only important.


问:
Laravel: How to use the ignore rule in Form Request Validation
Laravel has a 'unique' rule with an 'except' clause.  From the validation documentation, it takes this form:

```<code>unique:table,column,except,idColumn
</code>```

My application has a 'shop' entity.  When the user updates the shop's profile, I have a Form Request, with a validation rule configured as follows:

```<code>public function rules()
{
    return [
        'shop.name' => 'required|string|max:100|unique:shops,name,except,id',
    ];
}
</code>```

(The primary key on my shops table is id).

The problem is that Laravel does not take any notice of the 'except' clause.  This makes sense (sort of) since the shop ID is not being injected into the Form Request. I can inject id as just another form value, but that doesn't seem to work.

How can I get this rule working in a Form Request?

答:
To use the except clause of the unique rule, we need to provide the value of the field on the record that we want the rule to ignore directly in the rule itself.

So, if we want a unique name field for every record except for on the record that the request updates, we need to add the value of the ID field to ignore:

class UpdateShopRequest extends FormRequest
{
    ...
    public function rules()
    {
        return [
            'shop.name' => 'unique:shops,name,' . $this->shop['id'],
        ];
    }
}
```
<p>As shown, this rule will cause validation to fail if any row contains the same shop name <em>unless</em> the row's <code>id</code> matches <code>$this->shop['id']</code>. This example assumes that our form contains a <em>nested input field</em> for the record's ID attribute because this particular question is performing validation on an array input:</p>
<pre class="lang-html prettyprint-override"><code><input type="hidden" name="shop[id]" value="{{ $shop->id }}">
</code>```

...which lets us fetch the value within the request like we can with any other request.

However, most forms do not contain arrays, so—in other cases—the validation rule will likely refer to the input field directly (without nested identifiers):

'name' => 'unique:shops,name,' . $this->id,
```
<p>More typically, we pass the record ID as a route parameter, which we can retrieve using the request's <code>route()</code> method:</p>
<pre class="lang-php prettyprint-override"><code>'name' => 'unique:shops,name,' . $this->route('id'),
</code>```

...which works if we have a route defined similarly to:

Route::post('shops/{id}', ...);
```
<p>The fourth parameter to the <code>unique</code> validation rule lets us specify which column the <code>except</code> clause applies to, and defaults to <code>id</code>, so we can leave it off if we're just comparing the record's ID.</p>
<p>The rule looks a bit clumsy when we just concatenate the column value, especially for a field with a lot of other rules. Since version 5.3, Laravel provides a more elegant syntax to create a <code>unique</code> rule with an <code>except</code> clause:</p>
<pre class="lang-php prettyprint-override"><code>use Illuminate\Validation\Rule;
...
return [
    'name' => [
        'required',
        'string',
        'max:100',
        Rule::unique('shops', 'name')->ignore($this->id, 'optional_column'),
    ],
];

</code>```

Body:
Laravel has a 'unique' rule with an 'except' clause.  From the validation documentation, it takes this form:

unique:table,column,except,idColumn

My application has a 'shop' entity.  When the user updates the shop's profile, I have a Form Request, with a validation rule configured as follows:

public function rules()
{
    return [
        'shop.name' => 'required|string|max:100|unique:shops,name,except,id',
    ];
}

(The primary key on my shops table is id).

The problem is that Laravel does not take any notice of the 'except' clause.  This makes sense (sort of) since the shop ID is not being injected into the Form Request. I can inject id as just another form value, but that doesn't seem to work.

How can I get this rule working in a Form Request?

Body:
To use the except clause of the unique rule, we need to provide the value of the field on the record that we want the rule to ignore directly in the rule itself.

So, if we want a unique name field for every record except for on the record that the request updates, we need to add the value of the ID field to ignore:

class UpdateShopRequest extends FormRequest
{
    ...
    public function rules()
    {
        return [
            'shop.name' => 'unique:shops,name,' . $this->shop['id'],
        ];
    }
}

As shown, this rule will cause validation to fail if any row contains the same shop name unless the row's id matches $this->shop['id']. This example assumes that our form contains a nested input field for the record's ID attribute because this particular question is performing validation on an array input:

<input type="hidden" name="shop[id]" value="{{ $shop->id }}">

...which lets us fetch the value within the request like we can with any other request.

However, most forms do not contain arrays, so—in other cases—the validation rule will likely refer to the input field directly (without nested identifiers):

'name' => 'unique:shops,name,' . $this->id,

More typically, we pass the record ID as a route parameter, which we can retrieve using the request's route() method:

'name' => 'unique:shops,name,' . $this->route('id'),

...which works if we have a route defined similarly to:

Route::post('shops/{id}', ...);

The fourth parameter to the unique validation rule lets us specify which column the except clause applies to, and defaults to id, so we can leave it off if we're just comparing the record's ID.

The rule looks a bit clumsy when we just concatenate the column value, especially for a field with a lot of other rules. Since version 5.3, Laravel provides a more elegant syntax to create a unique rule with an except clause:

use Illuminate\Validation\Rule;
...
return [
    'name' => [
        'required',
        'string',
        'max:100',
        Rule::unique('shops', 'name')->ignore($this->id, 'optional_column'),
    ],
];


答:
The class AccountsModel already include in use section. So, you can just use AccountsModel instead of App\AccountsModel. See the updated code below

```<code><?php
namespace App\Libraries;
use App\AccountsModel;
class Account {

public $accountNum;
    public $accountDescription;
    public $isMainAccount;
    public $parentAccount;
    public $createTime;
    public $updatedTime;

    public function getInfo($accountNum)
    {
        $account = AccountsModel::where('accountNumber', $accountNum)->take(1)->get(); // this line updated
    }
}
?>
</code>```

Update your model to this. Just namespace App;

```<code><?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class AccountsModel extends Model
{
    protected $table = 'accounts';

}
</code>```

Also, this is not needed in composer.json since the AccountModel is part of App.

```<code>"AccountsModel\\" : "app/AccountsModel.php"
</code>```

Title: Accessing Model Through Custom Class

Body:
The class AccountsModel already include in use section. So, you can just use AccountsModel instead of App\AccountsModel. See the updated code below

<?php
namespace App\Libraries;
use App\AccountsModel;
class Account {

public $accountNum;
    public $accountDescription;
    public $isMainAccount;
    public $parentAccount;
    public $createTime;
    public $updatedTime;

    public function getInfo($accountNum)
    {
        $account = AccountsModel::where('accountNumber', $accountNum)->take(1)->get(); // this line updated
    }
}
?>

Update your model to this. Just namespace App;

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class AccountsModel extends Model
{
    protected $table = 'accounts';

}

Also, this is not needed in composer.json since the AccountModel is part of App.

"AccountsModel\\" : "app/AccountsModel.php"


问:
Xcode 9.2 Upload to App Store fails with description length and invalid toolchain errors
I've read through a bunch of forums including here:

https://forums.developer.apple.com/thread/87862

and some Stack Overflow posts.

I have tried modifying my plist using the proposed solution of

```<code>find Products/ -name Info.plist -print0 | xargs -0n1 plutil -replace BuildMachineOSBuild -string 16A323
</code>```

in the archive directory that I'm trying to load, and I'm still receiving the error below. I believe I have valid Xcode and Mac OS versions. I'm running Xcode 9.2 which was released today and High Sierra 10.13.1. Why does my upload fail with these errors and how can I fix it?

The errors in text (to make this post more searchable):

The following issues occurred while distributing your application.

⚠ iTunes Store Operation Failed

   description length:2651858

⚠ iTunes Store Operation Failed

   ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."

答:
There is a discussion on this subject : https://forums.developer.apple.com/thread/93253
They advise to wait for the deployment of the new Xcode version number on the backend or come back to Xcode 9.1, it seems it works.

UPDATE : Change the DTXcodeBuild doesn't work

Body:
I've read through a bunch of forums including here:

https://forums.developer.apple.com/thread/87862

and some Stack Overflow posts.

I have tried modifying my plist using the proposed solution of

find Products/ -name Info.plist -print0 | xargs -0n1 plutil -replace BuildMachineOSBuild -string 16A323

in the archive directory that I'm trying to load, and I'm still receiving the error below. I believe I have valid Xcode and Mac OS versions. I'm running Xcode 9.2 which was released today and High Sierra 10.13.1. Why does my upload fail with these errors and how can I fix it?

The errors in text (to make this post more searchable):

The following issues occurred while distributing your application.

⚠ iTunes Store Operation Failed

   description length:2651858

⚠ iTunes Store Operation Failed

   ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."


答:
You can use the ast module to convert string to dictionary

```<code>import ast
d="{'first_name': 'Abigail', 'last_name': 'Smith', 'updated': '2017-12-04 22:12:24.699-08', 'account_id': '338502', 'created': '2017-12-04 22:12:24.699-08', 'student_id': '1730', 'notes': '', 'school_id': '16', 'major_id': '20', 'status': 'OPEN', 'id': '37'}"
dic=ast.literal_eval(d)
print dic['id']
</code>```

 Output

```<code>37
</code>```

Title: Find a number in a string after specific set of strings and characters

Body:
You can use the ast module to convert string to dictionary

import ast
d="{'first_name': 'Abigail', 'last_name': 'Smith', 'updated': '2017-12-04 22:12:24.699-08', 'account_id': '338502', 'created': '2017-12-04 22:12:24.699-08', 'student_id': '1730', 'notes': '', 'school_id': '16', 'major_id': '20', 'status': 'OPEN', 'id': '37'}"
dic=ast.literal_eval(d)
print dic['id']

 Output

37


问:
While updating database with php i'm experiencing some issue
I'm working on library management system. and in update field. if user didn't pass data the i want to keep my data as it is, instead of changing it into blank

```<code><?php
if( isset($_POST['update']) )
{
    $conn = mysql_connect('localhost', 'root', '');
    if( !$conn )
    {
        die('Could not connect: ' . mysql_error());
    }
    $db_selected = mysql_select_db('library', $conn);
    $Book_ID     = $_POST['Book_ID'];
    $Book_Name   = $_POST['Book_Name'];
    $Author      = $_POST['Author'];
    $Quantity    = $_POST['Quantity'];

    $sql    = "update books set Book_Name='$Book_Name', Author='$Author',
            Quantity='$Quantity' where Book_ID='$Book_ID'";
    mysql_select_db('test_db');
    $retval = mysql_query($sql, $conn);

    if( !$retval )
    {
        die('Could not update data: ' . mysql_error());
    }
    echo "Updated data successfully\n";
    header("refresh:2; url=updatebook.php");
    mysql_close($conn);
}
else
{
    ?>
    <form method = "post" action = "<?php $_PHP_SELF ?>">
        <table width = "400" border =" 0" cellspacing = "1" cellpadding = "2">
            <tr>
                <td width = "100">Book ID</td>
                <td><input name = "Book_ID" type = "number" id = "Book_ID"></td>
            </tr>
            <tr>
                <td width = "100">Book Name</td>
                <td><input name = "Book_Name" type = "text" id = "Book_Name"></td>
            </tr>
            <tr>
                <td width = "100">Author</td>
                <td><input name = "Author" type = "text" id = "Author"></td>
            </tr>
            <tr>
                <td width = "100">Quantity</td>
                <td><input name = "Quantity" type = "text" id = "Quantity"></td>
            </tr>

            <tr>
                <td width = "100"> </td>
                <td> </td>
            </tr>

            <tr>
                <td width = "100"> </td>
                <td>
            <tr>
                <td width = "100"> </td>
                <td> </td>
            </tr>

            <tr>
                <td width = "100"> </td>
                <td>
                    <input name = "update" type = "submit" id = "update" value = "Update">
                </td>
            </tr>
        </table>
    </form>
    <?php
}
?>
</code>```

If user didn't want to change value of some field and keep it blank. i don't want to update that field with blank. I want to keep the data of that field, as it is.

from this code if i enter Book ID and kept Book Name, blank then this code passes the value

答:
You can do this with the help of simple if...else condition in mysql.

```<code>$sql = "UPDATE books SET
        Book_Name=IF(LENGTH('$Book_Name')=0, Book_Name, '$Book_Name'),
        Author=IF(LENGTH('$Author')=0, Author, '$Author'),
        Quantity=IF(LENGTH('$Quantity')=0, Quantity, '$Quantity')
        WHERE Book_ID='$Book_ID'";
</code>```

Don't use direct query to database. Its like an open invitation to Sql Injection.

Body:
I'm working on library management system. and in update field. if user didn't pass data the i want to keep my data as it is, instead of changing it into blank

<?php
if( isset($_POST['update']) )
{
    $conn = mysql_connect('localhost', 'root', '');
    if( !$conn )
    {
        die('Could not connect: ' . mysql_error());
    }
    $db_selected = mysql_select_db('library', $conn);
    $Book_ID     = $_POST['Book_ID'];
    $Book_Name   = $_POST['Book_Name'];
    $Author      = $_POST['Author'];
    $Quantity    = $_POST['Quantity'];

    $sql    = "update books set Book_Name='$Book_Name', Author='$Author',
            Quantity='$Quantity' where Book_ID='$Book_ID'";
    mysql_select_db('test_db');
    $retval = mysql_query($sql, $conn);

    if( !$retval )
    {
        die('Could not update data: ' . mysql_error());
    }
    echo "Updated data successfully\n";
    header("refresh:2; url=updatebook.php");
    mysql_close($conn);
}
else
{
    ?>
    <form method = "post" action = "<?php $_PHP_SELF ?>">

                Book ID
                <input name = "Book_ID" type = "number" id = "Book_ID">

                Book Name
                <input name = "Book_Name" type = "text" id = "Book_Name">

                Author
                <input name = "Author" type = "text" id = "Author">

                Quantity
                <input name = "Quantity" type = "text" id = "Quantity">

                    <input name = "update" type = "submit" id = "update" value = "Update">

    </form>
    <?php
}
?>

If user didn't want to change value of some field and keep it blank. i don't want to update that field with blank. I want to keep the data of that field, as it is.

from this code if i enter Book ID and kept Book Name, blank then this code passes the value

Body:
You can do this with the help of simple if...else condition in mysql.

$sql = "UPDATE books SET
        Book_Name=IF(LENGTH('$Book_Name')=0, Book_Name, '$Book_Name'),
        Author=IF(LENGTH('$Author')=0, Author, '$Author'),
        Quantity=IF(LENGTH('$Quantity')=0, Quantity, '$Quantity')
        WHERE Book_ID='$Book_ID'";

Don't use direct query to database. Its like an open invitation to Sql Injection.


问:
Custom font for error message of TextInputLayout in android
I'm trying to utilize TextInput Layout for Floating Labels available in android material design, where i'm showing error using app:errorTextAppearance flag. For this errorTextAppearance I'm unable to apply custom font.

I can change color and other things but not able to apply custom font.

I'm trying match font style of "Please select question" with "Please enter answer"
P.S "Please select question" was a plain text view and i was able to change font easily.

I can't post image but below link has it.

Input Text Layout

Could you please help me with this issue.

答:
As mentioned here:

You can use a SpannableString to set the font:

```<code>SpannableString s = new SpannableString(errorString);
s.setSpan(new TypefaceSpan(font), 0, s.length(),  Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mPasswordView.setError(s);
</code>```

A custom Span class that has a specific Typeface set:

```<code>public class TypefaceSpan extends MetricAffectingSpan {
    private Typeface mTypeface;
    public TypefaceSpan(Typeface typeface) {
        mTypeface = typeface;
    }

    @Override
    public void updateMeasureState(TextPaint p) {
        p.setTypeface(mTypeface);
        p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }

    @Override
    public void updateDrawState(TextPaint tp) {
        tp.setTypeface(mTypeface);
        tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
        }
    }
</code>```

Body:
As mentioned here:

You can use a SpannableString to set the font:

SpannableString s = new SpannableString(errorString);
s.setSpan(new TypefaceSpan(font), 0, s.length(),  Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mPasswordView.setError(s);

A custom Span class that has a specific Typeface set:

public class TypefaceSpan extends MetricAffectingSpan {
    private Typeface mTypeface;
    public TypefaceSpan(Typeface typeface) {
        mTypeface = typeface;
    }

    @Override
    public void updateMeasureState(TextPaint p) {
        p.setTypeface(mTypeface);
        p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }

    @Override
    public void updateDrawState(TextPaint tp) {
        tp.setTypeface(mTypeface);
        tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
        }
    }


问:
User entered data is not storing in component's variable Angular Reactive form
Hello I am using Angular reactive forms, I have used FormArray to add form controls dynamically. I am using ngModel directive to store user entered data in components variable. but it not storing it in components variable. my code is:

```<code><form [formGroup]="reviewForm" (ngSubmit)="onSubmit()">
  <div class="example-label">
    <span class='block'>
          <span *ngIf="selectedForm">
                  <h2 class="example-heading">{{displayForm}} </h2>
          </span>
    <div formArrayName="controlArray">
      <div *ngFor="let control of reviewForm.get('controlArray').controls; let i = index">
        <table>
          <tr>
            <td> <span *ngIf="control.value.controlType == 'text'">
          <md-form-field class="example-full-width">
            <input mdInput type="text" placeholder="{{control.value.placeholder}}"
            ([ngModel])="control.value.value" > <!--user entered data is not storing in control.value.value -->
          </md-form-field>
      </span></td>

          </tr>
        </table>
      </div>
      <button md-raised-button color="primary" type="submit" [disabled]="!reviewForm.valid">Submit</button>
    </div>
    </span>
  </div>
</form>
</code>```

Here is the component class code:

```<code>export class FormListComponent {

  formsDb: FormData[];
  selectedForm: FormData;
  displayForm: String;
  test: String;
  reviewForm = new FormGroup({
    'controlArray': new FormArray([])
  });
  constructor(public formService: FormService, public authGuardService: AuthGuardService) {
    console.log('form-list is logged in 0528', this.authGuardService.authService.isLoggedIn);
  }

  ngOnInit() {
    this.reviewForm = new FormGroup({
      'controlArray': new FormArray([
      ])
    });
    this.showDefaultForm();
  }

  addForm() {
    this.displayForm = this.selectedForm.formName;
    this.reviewForm.setControl('controlArray', new FormArray([]));  //to reset FormArray
    console.log('selected form 0528', this.selectedForm);
    for (let control of this.selectedForm.controlsArr) {
      const myControl: Control = new Control(control.controlType, control.label, control.required,
        control.placeholder, control.options);

      var controlArg: FormControl;
      if (control.required)
        controlArg = new FormControl(myControl, Validators.required);
      else
        controlArg = new FormControl(myControl);

      (<FormArray>this.reviewForm.get('controlArray')).push(controlArg);
    }
  }

  onSubmit() {
    console.log('submitted form 0528', this.reviewForm);
  }
}
</code>```

Here is my Control class, I pass its object to FormControl constructor:

```<code>export class Control{
    constructor(public controlType?:string, public label?:string, public required?:boolean ,public placeholder?:string,
      public options?:string[], public value?:string){  }
  }
</code>```

to check whether user entered data is stored in component's variable I logged my FormGroup variable i.e. reviewForm in this case. No data is saved in it. Please help, Thanks

答:
I would suggest not using ngModel in reactive forms. Utilize the form controls instead for your reactive form, so remove value and [(ngModel)]. Here's a simplified version of your code for you to get the idea. Build the form, and if you are getting some default values, iterate that array and push formgroups to your formArray:

constructor(private fb: FormBuilder) {
  this.reviewForm = fb.group({
    controlArray: fb.array([])
  })
  let controlArr = this.reviewForm.controls.controlArray as FormArray
  // arr contains your default values
  this.arr.forEach(x => {
    controlArr.push(fb.group({
      controlType: [x.controlType],
      value: [x.value]
    }))
  })
}
```

<p>Then in your template, switch to using <code>formControlName</code> for your controls, and also add <code>formGroupName</code> for each formgroup in your FormArray:</p>

<pre class="lang-html prettyprint-override"><code><div formArrayName="controlArray">
  <!-- add formGroupName -->
  <div *ngFor="let control of reviewForm.get('controlArray').controls;
               let i = index"
               [formGroupName]="i">
    <table>
      <tr>
        <td>
          <span *ngIf="control.value.controlType == 'text'">
            <div class="example-full-width">
              <input type="text" formControlName="value">
             </div>
          </span>
        </td>
      </tr>
    </table>
  </div>
</div>
</code>```

StackBlitz

Body:
Hello I am using Angular reactive forms, I have used FormArray to add form controls dynamically. I am using ngModel directive to store user entered data in components variable. but it not storing it in components variable. my code is:

<form [formGroup]="reviewForm" (ngSubmit)="onSubmit()">

{{displayForm}}

          <md-form-field class="example-full-width">
            <input mdInput type="text" placeholder="{{control.value.placeholder}}"
            ([ngModel])="control.value.value" >
          </md-form-field>

      <button md-raised-button color="primary" type="submit" [disabled]="!reviewForm.valid">Submit</button>

</form>

Here is the component class code:

export class FormListComponent {

  formsDb: FormData[];
  selectedForm: FormData;
  displayForm: String;
  test: String;
  reviewForm = new FormGroup({
    'controlArray': new FormArray([])
  });
  constructor(public formService: FormService, public authGuardService: AuthGuardService) {
    console.log('form-list is logged in 0528', this.authGuardService.authService.isLoggedIn);
  }

  ngOnInit() {
    this.reviewForm = new FormGroup({
      'controlArray': new FormArray([
      ])
    });
    this.showDefaultForm();
  }

  addForm() {
    this.displayForm = this.selectedForm.formName;
    this.reviewForm.setControl('controlArray', new FormArray([]));  //to reset FormArray
    console.log('selected form 0528', this.selectedForm);
    for (let control of this.selectedForm.controlsArr) {
      const myControl: Control = new Control(control.controlType, control.label, control.required,
        control.placeholder, control.options);

      var controlArg: FormControl;
      if (control.required)
        controlArg = new FormControl(myControl, Validators.required);
      else
        controlArg = new FormControl(myControl);

      (<FormArray>this.reviewForm.get('controlArray')).push(controlArg);
    }
  }

  onSubmit() {
    console.log('submitted form 0528', this.reviewForm);
  }
}

Here is my Control class, I pass its object to FormControl constructor:

export class Control{
    constructor(public controlType?:string, public label?:string, public required?:boolean ,public placeholder?:string,
      public options?:string[], public value?:string){  }
  }

to check whether user entered data is stored in component's variable I logged my FormGroup variable i.e. reviewForm in this case. No data is saved in it. Please help, Thanks

Body:
I would suggest not using ngModel in reactive forms. Utilize the form controls instead for your reactive form, so remove value and [(ngModel)]. Here's a simplified version of your code for you to get the idea. Build the form, and if you are getting some default values, iterate that array and push formgroups to your formArray:

constructor(private fb: FormBuilder) {
  this.reviewForm = fb.group({
    controlArray: fb.array([])
  })
  let controlArr = this.reviewForm.controls.controlArray as FormArray
  // arr contains your default values
  this.arr.forEach(x => {
    controlArr.push(fb.group({
      controlType: [x.controlType],
      value: [x.value]
    }))
  })
}

Then in your template, switch to using formControlName for your controls, and also add formGroupName for each formgroup in your FormArray:

<div formArrayName="controlArray">
  <!-- add formGroupName -->
  <div *ngFor="let control of reviewForm.get('controlArray').controls;
               let i = index"
               [formGroupName]="i">
    <table>
      <tr>
        <td>
          <span *ngIf="control.value.controlType == 'text'">
            <div class="example-full-width">
              <input type="text" formControlName="value">
             </div>
          </span>
        </td>
      </tr>
    </table>
  </div>
</div>

StackBlitz


问:
VSTS Release : bubbling up release quality metrics
We have a continuous deployment pipeline that is setup to deploy to a chain of environments.

In the portal, all I can see is the following :

How do I configure the portal such that it also shows :

How long each release took, split by environment

Historic graph which show release time taken over time, split by environment

Failures split by environment over time

答:
You can’t configure VSTS to show these, there isn’t such feature available in VSTS. Also, there isn’t the official extension can show them.

Some widgets can add release information to dashboard, but don’t meet your requirement. (Add release information to the dashboard)

You can get such information through Release REST API: Get a release (timeToDeploy value of each environment), so you can build an application (e.g. VSTS extension) to statistics data and show them.