问:
How to add EditText input to custom model using data binding adapter?
This is my data binding adapter:

```<code>@BindingAdapter("taskMinutes")
public static void taskMinutes(@NonNull TextView view, @NonNull Task task) {
    if (task.getDueDate() == null) {
        view.setText("");
        return;
    }
    view.setText(String.valueOf(DateUtils.getDateMinutes(task.getDueDate())));
}
</code>```

And in xml:

```<code>app:taskMinutes="@{task}"
</code>```

And minutes show in EditText normally but didn't add to task.dueDate.

But how can I add adapter for add new input from EditText filed to task.dueDate?

答:
I my case I add an attribute "input" and implement inverseBinding on it

```<code>@BindingAdapter(value = {"input", "inputAttrChanged"}, requireAll = false)
    public static void bindIntegerInText(AppCompatEditText tv, int value, final InverseBindingListener inverseBindingListener)
    {
        tv.setText(String.valueOf(value));
        // Set the cursor to the end of the text
        tv.setSelection(tv.getText().length());

        tv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //inverseBindingListener.onChange();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                inverseBindingListener.onChange();
            }

            @Override
            public void afterTextChanged(Editable s) {
                //inverseBindingListener.onChange();
            }
        });
    }

    @InverseBindingAdapter(attribute = "app:input", event = "app:inputAttrChanged")
    public static int bindCountryInverseAdapter(AppCompatEditText view) {
        String string = view.getText().toString();
        return string.isEmpty() ? 0 : Integer.parseInt(string);
    }
</code>```

Xml:

```<code><android.support.v7.widget.AppCompatEditText
            android:id="@+id/et_age"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:hint="Enter Age"
            android:inputType="number"
            app:input="@={userInfo.age}"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/et_password"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp" />
</code>```

I add a check in my model object to avoid infinite loop between model and view

```<code>@Bindable
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        Log.d("Age","Age "+age);
        if (this.age != age){
            this.age = age;
            if (this.age != 0)
            notifyPropertyChanged(BR.age);
        }
    }
</code>```

There is another simple way of doing this::

# Write a class for conversion and add this two methods

```<code>    public class Conversion {

    @InverseMethod("toInt")
    public static String toString(int age) {
        return age == 0 ? null : String.valueOf(age);
    }

    public static int toInt(String string) {
        return string.isEmpty() ? 0 : Integer.parseInt(string);
    }
}
</code>```

@InverseMethod("toInt") means, toInt() method will be called for data inversion.

# In XML

```<code><android.support.v7.widget.AppCompatEditText
            android:id="@+id/et_age"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:hint="Enter Age"
            android:inputType="number"
            android:text="@={Conversion.toString(userInfo.age)}"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/et_password"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp" />
</code>```

# Import the Conversion class in the layout file

```<code><import type="bytes.wit.databinding.Conversion"/>
</code>```

Body:
This is my data binding adapter:

@BindingAdapter("taskMinutes")
public static void taskMinutes(@NonNull TextView view, @NonNull Task task) {
    if (task.getDueDate() == null) {
        view.setText("");
        return;
    }
    view.setText(String.valueOf(DateUtils.getDateMinutes(task.getDueDate())));
}

And in xml:

app:taskMinutes="@{task}"

And minutes show in EditText normally but didn't add to task.dueDate.

But how can I add adapter for add new input from EditText filed to task.dueDate?

Body:
I my case I add an attribute "input" and implement inverseBinding on it

@BindingAdapter(value = {"input", "inputAttrChanged"}, requireAll = false)
    public static void bindIntegerInText(AppCompatEditText tv, int value, final InverseBindingListener inverseBindingListener)
    {
        tv.setText(String.valueOf(value));
        // Set the cursor to the end of the text
        tv.setSelection(tv.getText().length());

        tv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //inverseBindingListener.onChange();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                inverseBindingListener.onChange();
            }

            @Override
            public void afterTextChanged(Editable s) {
                //inverseBindingListener.onChange();
            }
        });
    }

    @InverseBindingAdapter(attribute = "app:input", event = "app:inputAttrChanged")
    public static int bindCountryInverseAdapter(AppCompatEditText view) {
        String string = view.getText().toString();
        return string.isEmpty() ? 0 : Integer.parseInt(string);
    }

Xml:

<android.support.v7.widget.AppCompatEditText
            android:id="@+id/et_age"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:hint="Enter Age"
            android:inputType="number"
            app:input="@={userInfo.age}"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/et_password"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp" />

I add a check in my model object to avoid infinite loop between model and view

@Bindable
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        Log.d("Age","Age "+age);
        if (this.age != age){
            this.age = age;
            if (this.age != 0)
            notifyPropertyChanged(BR.age);
        }
    }

There is another simple way of doing this::

# Write a class for conversion and add this two methods

    public class Conversion {

    @InverseMethod("toInt")
    public static String toString(int age) {
        return age == 0 ? null : String.valueOf(age);
    }

    public static int toInt(String string) {
        return string.isEmpty() ? 0 : Integer.parseInt(string);
    }
}

@InverseMethod("toInt") means, toInt() method will be called for data inversion.

# In XML

<android.support.v7.widget.AppCompatEditText
            android:id="@+id/et_age"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:hint="Enter Age"
            android:inputType="number"
            android:text="@={Conversion.toString(userInfo.age)}"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/et_password"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp" />

# Import the Conversion class in the layout file

<import type="bytes.wit.databinding.Conversion"/>


来源: stackexchange

问:
mysql slow log query
Question - When i am looking into mysql-slowquery.log then there i found queries having high query_time, even when one query has row examine = 1. This log is of a heavily populated database. From php website. Can you explain the reason and why are they used(if any idea about queries) ?</p>

```<code>Query type 1 :

# Query_time: 0.198267  Lock_time: 0.000121 Rows_sent: 1  Rows_examined: 10636
use mysql;
SET timestamp=1490832000;
SELECT count(name) FROM information_schema.innodb_sys_tables
    WHERE name like '%/#sql-%';

Query type 2:

# Query_time: 0.007362  Lock_time: 0.000127 Rows_sent: 0  Rows_examined: 1
use mysql;
SET timestamp=1490835900;
SELECT count(*) from mysql.rds_history
    WHERE action = 'disable set master'
    GROUP BY action_timestamp, called_by_user, action, mysql_version ,master_host,
             master_port, master_user, master_log_file , master_log_pos,
             master_ssl
    ORDER BY action_timestamp LIMIT 1;
</code>```

答:
Query type 1:

information_schema is not a real table.  Instead, it is a view into various in-memory structures.  Some of these structures are views into stuff that needs to be calculated or even fetched from disk.  So...  Some IS queries are fast, some are unexpectedly slow.

In your case, it had to touch 10K things, and that is what took time, apparently 198ms.  That is reasonable.

The query looks like it is counting the number of tmp tables used by things like ALTER TABLE.  (I can't think why it is useful.)

(Note: My Answer disagrees with Rahul's.)

Query type 2:

This took 7ms, and apparently made one probe into a table with at most one row.  It seems to have done a table scan, but found nothing with that action.  This is a 'reasonable' amount of time.  After all, it had to locate and open the table, perhaps for the first time in this session, and read whatever it found.

The query is, however rather strange.  It does a COUNT(*) and a GROUP BY, but it does not list what it is grouping by in the SELECT.  If there were useful data, it would return a set of numbers (counts), but no clue of what each count refers to.

Addenda - From Amazon:

Type 1 is meant to identify leftover temporary tables in InnoDB dictionary, which is used as diagnostic aid in case of crashed ALTERs.

Type 2 is an internal check for features enabled on the instance.

To address the impact, we need to know the frequency of these queries, whether it is RDS or Aurora, the setting of log_queries_not_using_indexes, and how far apart the client and server are (milliseconds latency).

ContentLicense: CC BY-SA 3.0

Title: mysql slow log query

Body:
Question - When i am looking into mysql-slowquery.log then there i found queries having high query_time, even when one query has row examine = 1. This log is of a heavily populated database. From php website. Can you explain the reason and why are they used(if any idea about queries) ?

Query type 1 :

# Query_time: 0.198267  Lock_time: 0.000121 Rows_sent: 1  Rows_examined: 10636
use mysql;
SET timestamp=1490832000;
SELECT count(name) FROM information_schema.innodb_sys_tables
    WHERE name like '%/#sql-%';

Query type 2:

# Query_time: 0.007362  Lock_time: 0.000127 Rows_sent: 0  Rows_examined: 1
use mysql;
SET timestamp=1490835900;
SELECT count(*) from mysql.rds_history
    WHERE action = 'disable set master'
    GROUP BY action_timestamp, called_by_user, action, mysql_version ,master_host,
             master_port, master_user, master_log_file , master_log_pos,
             master_ssl
    ORDER BY action_timestamp LIMIT 1;


问:
ng-cloak not working in Angular
I am trying to remove {{ }} from my website. Basically it came if angular didn't load. So, I checked SO and found some answer to use ng-cloak. I tried that but I can still see {{ }}. I added the CSS code below in a CSS file as well as locally on the page.

CSS

```<code>.ng-cloak {
      display: none !important;
}
</code>```

Here is the form.

```<code><form name="register" method="post" id="register" role="form" ng-submit="registerForm()">
<div class="form-group" ng-class="{ 'has-error' : erroractype }">
        <select id="actype" name="actype" class=" selector form-control" ng-model="formData.actype" required="required">
           <option value="" selected="selected" >I am</option>
          <option value="1"> Student</option>
          <option value="2"> Teacher</option>
          <option value="3"> School</option>
          </select>
<span class="help-block" ng-show="errorName" class="ng-cloak">{{ erroractype }}</span>
</div>

<div class="form-group" ng-class="{ 'has-error' : errorFname }">

<input type="text" id="fname" name="fname" placeholder="First Name" title="Please Enter Your First Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Fname">
<div class = "alert alert-danger" ng-show="errorFname" class="ng-cloak">{{errorFname}}</div>

</div>

<div class="form-group" ng-class="{ 'has-error' : errorLname }">
<input type="text" id="lname" name="lname" placeholder="Last Name" title="Please Enter Your Last Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Lname">
<div class = "alert alert-danger" ng-show="errorLname" class="ng-cloak">{{ errorLname }}</div>
</div>

<div class="form-group" ng-class="{ 'has-error' : errorEmail1 }">
<input type="email" id="email1" name="email1" placeholder="Email" class="form-control input-sm textbox1" title="Please Enter Your Valid Email" required="required" ng-model="formData.Email1">
<div class = "alert alert-danger" ng-show="errorEmail1" class="ng-cloak">{{ errorEmail1 }}</div>
</div>

<div class="form-group" ng-class="{ 'has-error' : errorPassword1 }">
<input type="password" name="password1" id="password1" placeholder="Password" title="Please enter AlphaNumeric value" class="form-control input-sm textbox1" required="required" ng-model="formData.Password1">
<div class = "alert alert-danger" ng-show="errorPassword1" class="ng-cloak">{{ errorPassword1 }}</div>
{{ errorPassword1 }}
</div>

<div class="form-group" ng-class="{ 'has-error' : errormobile }">
    <input type="text" id="mobile" name="mobile" placeholder="Mobile Number (+1)" title="Please Enter Your Contact Number without Coutry Code." class="form-control input-sm textbox1" required="required" ng-model="formData.mobile">
    <div class = "alert alert-danger" ng-show="errormobile" class="ng-cloak">{{ errormobile }}</div>
 </div>

<div class="form-group">
<button type="submit" class="btn btn-home" name="btn-register" id="btn-register" required="required">Register</button>
</div>
</form>
</code>```

Any advice as to what am I doing wrong?

答:
Sorry guys, that was a silly mistake.

```<code><div class = "alert alert-danger" ng-show="errorEmail1" class="ng-cloak">{{ errorEmail1 }}</div>
</code>```

Needs to change like this.

```<code><div class = "alert alert-danger ng-cloak" ng-show="errorEmail1" >{{ errorEmail1 }}</div>
</code>```

It was really silly. A very basic one. I hope someone will come across these kinds of funny situation.

Title: ng-cloak not working in Angular

Body:
I am trying to remove {{ }} from my website. Basically it came if angular didn't load. So, I checked SO and found some answer to use ng-cloak. I tried that but I can still see {{ }}. I added the CSS code below in a CSS file as well as locally on the page.

CSS

.ng-cloak {
      display: none !important;
}

Here is the form.

<form name="register" method="post" id="register" role="form" ng-submit="registerForm()">

        <select id="actype" name="actype" class=" selector form-control" ng-model="formData.actype" required="required">
           <option value="" selected="selected" >I am</option>
          <option value="1"> Student</option>
          <option value="2"> Teacher</option>
          <option value="3"> School</option>
          </select>
{{ erroractype }}

<input type="text" id="fname" name="fname" placeholder="First Name" title="Please Enter Your First Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Fname">

{{errorFname}}

<input type="text" id="lname" name="lname" placeholder="Last Name" title="Please Enter Your Last Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Lname">

{{ errorLname }}

<input type="email" id="email1" name="email1" placeholder="Email" class="form-control input-sm textbox1" title="Please Enter Your Valid Email" required="required" ng-model="formData.Email1">

{{ errorEmail1 }}

<input type="password" name="password1" id="password1" placeholder="Password" title="Please enter AlphaNumeric value" class="form-control input-sm textbox1" required="required" ng-model="formData.Password1">

{{ errorPassword1 }}

{{ errorPassword1 }}

    <input type="text" id="mobile" name="mobile" placeholder="Mobile Number (+1)" title="Please Enter Your Contact Number without Coutry Code." class="form-control input-sm textbox1" required="required" ng-model="formData.mobile">

{{ errormobile }}

<button type="submit" class="btn btn-home" name="btn-register" id="btn-register" required="required">Register</button>

</form>

Any advice as to what am I doing wrong?

Body:
Sorry guys, that was a silly mistake.

<div class = "alert alert-danger" ng-show="errorEmail1" class="ng-cloak">{{ errorEmail1 }}</div>

Needs to change like this.

<div class = "alert alert-danger ng-cloak" ng-show="errorEmail1" >{{ errorEmail1 }}</div>

It was really silly. A very basic one. I hope someone will come across these kinds of funny situation.


问:
SSIS Case Statement not working
This SSIS case expression looks perfectly valid to me, but it's coming up red. Can anybody explain why?</p>

```<code>[Copy of "final_benefit_type_grouper"] == "MEDICAL" ? "2"
</code>```

答:
Referring to the Microsoft Documentation, ? conditional syntax is like the following:

```<code>boolean_expression?expression1:expression2
</code>```

"If the Boolean expression evaluates to TRUE, then the first expression is evaluated and the result is the expression result. If the Boolean expression evaluates to FALSE then the second expression is evaluated and its result is the expression result." Read more

so i think you are missing the second part of the expression, i might be something like this:

```<code>[Copy of "final_benefit_type_grouper"] == "MEDICAL" ? "2" : ""
</code>```

Also it is better to add a NULL checking to your expression using ISNULL() function (to avoid a null value exception):

```<code>ISNULL([Copy of "final_benefit_type_grouper"])? "" : ( [Copy of "final_benefit_type_grouper"] == "MEDICAL" ? "2" : "")
</code>```

It is also to follow this Link to Read more about write a case statment using a SSIS expression

Title: SSIS Case Statement not working

Body:
This SSIS case expression looks perfectly valid to me, but it's coming up red. Can anybody explain why?

[Copy of "final_benefit_type_grouper"] == "MEDICAL" ? "2"

Body:
Referring to the Microsoft Documentation, ? conditional syntax is like the following:

boolean_expression?expression1:expression2

"If the Boolean expression evaluates to TRUE, then the first expression is evaluated and the result is the expression result. If the Boolean expression evaluates to FALSE then the second expression is evaluated and its result is the expression result." Read more

so i think you are missing the second part of the expression, i might be something like this:

[Copy of "final_benefit_type_grouper"] == "MEDICAL" ? "2" : ""

Also it is better to add a NULL checking to your expression using ISNULL() function (to avoid a null value exception):

ISNULL([Copy of "final_benefit_type_grouper"])? "" : ( [Copy of "final_benefit_type_grouper"] == "MEDICAL" ? "2" : "")

It is also to follow this Link to Read more about write a case statment using a SSIS expression


问:
How to fetch a native ES6 module using Fetch API?
I am using the FF Dev build that supports ES6 modules. When I use

```<code><script type="module" src="./script.js">
</code>```

script.js triggers the download of other scripts in its import section at the start of the file, but that does not happen when I use:

```<code>fetch("./script.js")
</code>```

I did not find how to specify the script type in the Fetch API.

答: Are you doing something with the script after you fetch it? Since fetch returns a promise, as per docs, you have to do something with the resource after you get it. Fetch won't execute the code in that file, it just retrieves it.  </p>


问:
Complex string split method in java
basically, I am trying to be able to read every line separated by some conditions (\n \s , )and store the String into Node A and Node B for the purpose of node addition, but not sure where to start or figured out what to do. please Help!

```<code>public static void main(String[] args) {

    try{
        String oneLine;
        FileReader theFile = new FileReader("src/Test.txt");
        BufferedReader inFile = new BufferedReader(theFile);
        Node A = new Node(0,null);

        while((oneLine = inFile.readLine()) != null) {

            String numbers[]= oneLine.split("\n");

            for (int i=0;i<numbers.length;i++){
                 int a = Integer.parseInt(numbers[i]);
                 A.addNumtoNode(a); } } }

public void addNumtoNode(int e){
        head = new Node(e,head);
        if (size == 0)
        tail = head;
        size++;
        }
</code>```

Sample of Test.txt

```<code>9
4

31,415,926,535
2

0
1,234,567,890

1,734,792
131

1,506,033,005,018,000,029
1,992
</code>```

答: I think that show should split the line using ','. readLine() splits the text in lines and then you want the numbers of that line that are separated by ','.</p>

Title: Complex string split method in java

Body:
basically, I am trying to be able to read every line separated by some conditions (\n \s , )and store the String into Node A and Node B for the purpose of node addition, but not sure where to start or figured out what to do. please Help!

public static void main(String[] args) {

    try{
        String oneLine;
        FileReader theFile = new FileReader("src/Test.txt");
        BufferedReader inFile = new BufferedReader(theFile);
        Node A = new Node(0,null);

        while((oneLine = inFile.readLine()) != null) {

            String numbers[]= oneLine.split("\n");

            for (int i=0;i<numbers.length;i++){
                 int a = Integer.parseInt(numbers[i]);
                 A.addNumtoNode(a); } } }

public void addNumtoNode(int e){
        head = new Node(e,head);
        if (size == 0)
        tail = head;
        size++;
        }

Sample of Test.txt

9
4

31,415,926,535
2

0
1,234,567,890

1,734,792
131

1,506,033,005,018,000,029
1,992


问:
Using Recursion to determine if input is prime
Ive tried to search for similar questions to see if the answer might be on this site to no avail.
Im currently trying to write a program that determines if the user input is a prime number using a recursive method. The problem is it will not compile do to the variable "n" already being defined in the scope. I dont quite see what the compiler means.
Heres is my code</p>

```<code>/**
 * Created on 3/26/2017.
 **/
import java.util.Scanner;
public class PrimeNumberRecursion {
    public static void main(String[] n) {
        //Variables declared
        Scanner userInput = new Scanner(System.in);
        int n;
        int div = 2;
        //Program is introduced
        System.out.println(" Prime Number Recursion Program");
        System.out.println("*********************************");
        //User is prompted for a number
        System.out.print("Please enter a number: ");
        n = userInput.nextInt();
        //Conditional statement prints result
        if(isPrime(n,div) == 1){System.out.println(n +" is a prime number");}
        else{System.out.println(n +" is not a prime number");}
    }
    //User input is passed to isPrime recursive method
    public static int isPrime(int n, int div) {
        if(n == 1) {return 1;}
        else if(n % div == 0) {return -1;}
        else if(n == div) {return -1;}
        else{return isPrime(n, ++div);}
    }
}
</code>```

答: 'n' is a duplicate variable. You are using it both at int n; and String[] n Rename String [] n to n1 or something

Body:
Ive tried to search for similar questions to see if the answer might be on this site to no avail.
Im currently trying to write a program that determines if the user input is a prime number using a recursive method. The problem is it will not compile do to the variable "n" already being defined in the scope. I dont quite see what the compiler means.
Heres is my code

/**
 * Created on 3/26/2017.
 **/
import java.util.Scanner;
public class PrimeNumberRecursion {
    public static void main(String[] n) {
        //Variables declared
        Scanner userInput = new Scanner(System.in);
        int n;
        int div = 2;
        //Program is introduced
        System.out.println(" Prime Number Recursion Program");
        System.out.println("*********************************");
        //User is prompted for a number
        System.out.print("Please enter a number: ");
        n = userInput.nextInt();
        //Conditional statement prints result
        if(isPrime(n,div) == 1){System.out.println(n +" is a prime number");}
        else{System.out.println(n +" is not a prime number");}
    }
    //User input is passed to isPrime recursive method
    public static int isPrime(int n, int div) {
        if(n == 1) {return 1;}
        else if(n % div == 0) {return -1;}
        else if(n == div) {return -1;}
        else{return isPrime(n, ++div);}
    }
}


问:
Creating a link to logout for JSP
when a user logins to my application, he submits a form to be processed through the Servlet. The servlet creates a session for the user. How would I create a link so the user can logout? I cannot seem to directly link to a Servlet. How would I delete the session and link back to the homepage?

Here is a way that I could do it, but it doesn't seem "right".
I could link back to the index.jsp?logout=true. My index.jsp will see if logout is true and delete the sessions.

Is there another way to do it?

答:
Simplest way to do that is make a link of logout like this..

```<code><a href="logout.jsp">LogOut</a>
</code>```

And in the "logout.jsp" write below code

```<code><%
session.invalidate();
response.sendRedirect("index.jsp");
%>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Creating a link to logout for JSP

Body:
Simplest way to do that is make a link of logout like this..

<a href="logout.jsp">LogOut</a>

And in the "logout.jsp" write below code

<%
session.invalidate();
response.sendRedirect("index.jsp");
%>


问:
Doing an AJAX POST followed by GET with Flask
My goal here is to have the user fill out a form, send that information in a POST request to the flask server, then render a template using that form information (after it undergoes some logic on the server).

So far, I have completed the POST part of all of this. I am trying to render a template right now inside the if request.method == POST', and I guess that's not working right now.

Here's the code I have so far:

```<code>@app.route('/filteredsearch/', methods = ["GET", "POST"])
def filteredsearch():
    if request.method == 'POST':
        data = json.loads(request.data)
        tables = data['checkboxes']
        filter_results = getFilteredEntities(tables = tables)
        print filter_results                          #This works
        return render_template("filteredsearch.html", entities = filter_results)
</code>```

Do I have to do a separate GET request on the success of my POST function? If so, how would I do that?

Here is the AJAX request (if it matters, this code can be called on every single page of the app):

```<code>$.ajax({
              url:"/filteredsearch/",
              type: 'POST',
              data: json,
              contentType: 'application/json;charset=UTF-8',
              success: function() {
                           alert("Done");
                       }
          });
</code>```

So, ideally I can render a template while I'm posting. If that's not the case, how do I go about doing a GET request from the same ajax function?

I know that typically you use url_for() for a GET request, is that an option given that I'm in JS at this point?

答:
I know it's a little late, but i just had the same problem than you.

I needed to make a POST with Ajax and then if it succeeded I needed to make a GET request to flask to return a rendered template. Something like:

FLASK PART:

```<code>@app.route('/something', methods=['POST'])
def something_post():
    # Get JSON object passed with Ajax request
    elems = request.json
    # Do stuff
    # If everithing is OK, return success message
    return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}

@app.route('/something', methods=['GET'])
def something_get():
    # Return template
    return render_template('something.html')
</code>```

AJAX PART:

```<code>$.ajax({
        type: 'POST',
        data: myJsonString, // JASON object passed to flask
        url: '/something',
        contentType: "application/json",
        method: 'POST',
        success: function(response) {
            # If we succed we make a request to get the template
            window.location.href = "/something";
            # With this line we are making a simple GET request to Flask and the template returned is opened in the current window
        }
});
</code>```

Please, note than I'm far, far away to be an Ajax expert. I don't know if this is the correct way to do it but it was the simplest way I found.

Body:
My goal here is to have the user fill out a form, send that information in a POST request to the flask server, then render a template using that form information (after it undergoes some logic on the server).

So far, I have completed the POST part of all of this. I am trying to render a template right now inside the if request.method == POST', and I guess that's not working right now.

Here's the code I have so far:

@app.route('/filteredsearch/', methods = ["GET", "POST"])
def filteredsearch():
    if request.method == 'POST':
        data = json.loads(request.data)
        tables = data['checkboxes']
        filter_results = getFilteredEntities(tables = tables)
        print filter_results                          #This works
        return render_template("filteredsearch.html", entities = filter_results)

Do I have to do a separate GET request on the success of my POST function? If so, how would I do that?

Here is the AJAX request (if it matters, this code can be called on every single page of the app):

$.ajax({
              url:"/filteredsearch/",
              type: 'POST',
              data: json,
              contentType: 'application/json;charset=UTF-8',
              success: function() {
                           alert("Done");
                       }
          });

So, ideally I can render a template while I'm posting. If that's not the case, how do I go about doing a GET request from the same ajax function?

I know that typically you use url_for() for a GET request, is that an option given that I'm in JS at this point?

Body:
I know it's a little late, but i just had the same problem than you.

I needed to make a POST with Ajax and then if it succeeded I needed to make a GET request to flask to return a rendered template. Something like:

FLASK PART:

@app.route('/something', methods=['POST'])
def something_post():
    # Get JSON object passed with Ajax request
    elems = request.json
    # Do stuff
    # If everithing is OK, return success message
    return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}

@app.route('/something', methods=['GET'])
def something_get():
    # Return template
    return render_template('something.html')

AJAX PART:

$.ajax({
        type: 'POST',
        data: myJsonString, // JASON object passed to flask
        url: '/something',
        contentType: "application/json",
        method: 'POST',
        success: function(response) {
            # If we succed we make a request to get the template
            window.location.href = "/something";
            # With this line we are making a simple GET request to Flask and the template returned is opened in the current window
        }
});

Please, note than I'm far, far away to be an Ajax expert. I don't know if this is the correct way to do it but it was the simplest way I found.


问:
What is Object Mocking and when do I need it?
Many people use Mock Objects when they are writing unit tests. What is a Mock Object? Why would I ever need one? Do I need a Mock Object Framework?

答:
It allows you to test how one part of your project interacts with the rest, without building the entire thing and potentially missing a vital part.

EDIT: Great example from wikipedia: It allows you to test out code beforehand, like a car designer uses a crash test dummy to test the behavior of a car during an accident.


问:
IList.Cast<typeof(T)>() returns error, syntax looks ok
```<code>public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}
</code>```

<p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>

答:
@Jonathan Holland

T is already a type parameter, you don't need to call typeof on it. TypeOf takes a type and returns its type parameter.

typeof "takes" a type and returns its System.Type

OwnerDisplayName: Sara Chipps

Body:
public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}

So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?

OwnerDisplayName: Matt Hinze

LastEditorDisplayName: Jeff Atwood


问:
How stable/usable is SqlRoleProvider & aspnet_regsql?
this isn't asp.net specific, some of these apps are WinForms, also will be adding some Wpf and possibly some silverlight apps in the future.

I’ve a requirement to put role & permissions based access security into a new app we’re developing here.

The .net RoleProviders in general, and SqlRoleProvider in particular seem to have everything we need, however I’ve a few concerns around the Db Schema changes aspnet_regsql needs.

I’ve tried googling for these but I’m not sure what to ask for.

i.e.

How straightforward (or not) is it going to be to upgrade this between .net versions?

Will .Net 2.0 and .net 3.5 apps happily use the same schemas? i.e. Can we have .net 2.0 and 3.5 apps use the same permissions in the same Db?

How stable are the Sql Security providers, is anyone out there using them in anger? Are they worth using?

Am I better off biting the bullet and implementing my own - limited - Role functionality (that will do everything I need) and my own custom RoleProvider?

As you can see I'm caught between "not wanting to re-invent the wheel" and "not getting stuck with problems with some unknown 3rd party code" (unknown to me anyway, that's why I'm asking you)

Thanks in advance for your advice & testimonials,

BW

答:
I believe the SqlRoleProvider is the way to go.  It's highly scalable and easy to set up.  Unless you've already rolled your own proven solution (then why are you posting this question) then this is a no brainer.

I agree with webchanix, the system does allow for multiple applications and does lots of table scans but in the end, I think we're talking about an pretty small perf hit based on it's benefits.

OwnerDisplayName: Binary Worrier


问:
convert total minutes into days, hours, minutes in vb
i want to convert total minutes into days hours and minutes. i am new to vb and still trying to learn...
this is my code...

```<code>    Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged
    TextBox1.Text = TextBox3.Text / 1440
    End Sub

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    TextBox3.Text = TextBox1.Text * 1440
    TextBox7.Text = TextBox1.Text / 24
    End Sub

    Private Sub TextBox7_TextChanged(sender As Object, e As EventArgs) Handles TextBox7.TextChanged
    TextBox1.Text = TextBox7.Text * 24
    End Sub
</code>```

When i run it i am having answers in decimal.. can anyone suggest me a proper way to do this? i do not want decimals.

答:
It doesn't look like you understand the concept of variables, you don't need to have three different handlers to make this work, you can do it all in one handler.

You could do what you want arithmetically but in my opinion, an easier way is to use TimeSpan. It would look something like this:

```<code>'TextBox1 is where the user inputs the number of minutes
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    Dim d = TimeSpan.FromMinutes(TextBox1.Text) 'creates a TimeSpan based on user input, this is also a variable creation

    TextBox5.Text = d.ToString("dd\:hh\:mm") 'you can format it with a custom format

    'Or you can access the elements of the TimeSpan like so

    TextBox2.Text = d.Days
    TextBox3.Text = d.Hours
    TextBox4.Text = d.Minutes
End Sub
</code>```

Body:
i want to convert total minutes into days hours and minutes. i am new to vb and still trying to learn...
this is my code...

    Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged
    TextBox1.Text = TextBox3.Text / 1440
    End Sub

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    TextBox3.Text = TextBox1.Text * 1440
    TextBox7.Text = TextBox1.Text / 24
    End Sub

    Private Sub TextBox7_TextChanged(sender As Object, e As EventArgs) Handles TextBox7.TextChanged
    TextBox1.Text = TextBox7.Text * 24
    End Sub

When i run it i am having answers in decimal.. can anyone suggest me a proper way to do this? i do not want decimals.

Body:
It doesn't look like you understand the concept of variables, you don't need to have three different handlers to make this work, you can do it all in one handler.

You could do what you want arithmetically but in my opinion, an easier way is to use TimeSpan. It would look something like this:

'TextBox1 is where the user inputs the number of minutes
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    Dim d = TimeSpan.FromMinutes(TextBox1.Text) 'creates a TimeSpan based on user input, this is also a variable creation

    TextBox5.Text = d.ToString("dd\:hh\:mm") 'you can format it with a custom format

    'Or you can access the elements of the TimeSpan like so

    TextBox2.Text = d.Days
    TextBox3.Text = d.Hours
    TextBox4.Text = d.Minutes
End Sub


问:
Telnetlib read server response without telnet commands
I'm using telnetlib to connect to a remote telnet server and parse it's response, however, all telnetlib's read_* methods return its raw response - including raw telnet command bytes (starting with 0xFF) - which is undesirable for my purpose.

For example, when calling read_all:

desired output - b'Hello'

output returned by telnetlib - b'\xff\xfd\x18\xff\xfdHello'

Is there a way to make telnetlib exclude those special telnet control bytes from its output?

答:
As far as I can tell from your question you need to convert the string into UTF-8. This may be your solution.
https://www.tutorialspoint.com/python/string_decode.htm</p>


问:
Querying Google Maps Using PHP
I am trying to pass the Latitude and Longitude as a variable in PHP to fetch static Google Maps , But this just picks up one Image despite of changing the co ordinates .Please help

*

```<code><?php
session_start();
$latitude=doubleval($_POST['latitude']);
$longitude=doubleval($_POST['longitude']);
$cordinate=$latitude.",".$longitude;
$cordinate1=doubleval($cordinate);
echo $latitude;
echo $longitude;
$src='https://maps.googleapis.com/maps/api/staticmap?center=($latitude,$longitude)&zoom=20&size=640x640&maptype=satellite&key=MyKey';
$time=strval(mktime());
$destfolder='images/';
$mapImgName=$time."google-map.PNG";
$imagePath=$destfolder.$mapImgName
file_put_contents($imagePath,file_get_contents($src));
?>
<img src="<?php echo $imagePath; ?>"/>
</code>```

答:
change it double quotes so that the $latitude and $longitude variables are read

with single quotes your string is reading as

https://maps.googleapis.com/maps/api/staticmap?center=($latitude,$longitude)&zoom=20&size=640x640&maptype=satellite&key=MyKey

where as you want it to read as

https://maps.googleapis.com/maps/api/staticmap?center=(5,10)&zoom=20&size=640x640&maptype=satellite&key=MyKey

so change your string to

```<code>"https://maps.googleapis.com/maps/api/staticmap?center=($latitude,$longitude)&zoom=20&size=640x640&maptype=satellite&key=MyKey";
</code>```

source What is the difference between single-quoted and double-quoted strings in PHP?

Title: Querying Google Maps Using PHP

Body:
I am trying to pass the Latitude and Longitude as a variable in PHP to fetch static Google Maps , But this just picks up one Image despite of changing the co ordinates .Please help

*

<?php
session_start();
$latitude=doubleval($_POST['latitude']);
$longitude=doubleval($_POST['longitude']);
$cordinate=$latitude.",".$longitude;
$cordinate1=doubleval($cordinate);
echo $latitude;
echo $longitude;
$src='https://maps.googleapis.com/maps/api/staticmap?center=($latitude,$longitude)&zoom=20&size=640x640&maptype=satellite&key=MyKey';
$time=strval(mktime());
$destfolder='images/';
$mapImgName=$time."google-map.PNG";
$imagePath=$destfolder.$mapImgName
file_put_contents($imagePath,file_get_contents($src));
?>
<img src="<?php echo $imagePath; ?>"/>

Body:
change it double quotes so that the $latitude and $longitude variables are read

with single quotes your string is reading as

https://maps.googleapis.com/maps/api/staticmap?center=($latitude,$longitude)&zoom=20&size=640x640&maptype=satellite&key=MyKey

where as you want it to read as

https://maps.googleapis.com/maps/api/staticmap?center=(5,10)&zoom=20&size=640x640&maptype=satellite&key=MyKey

so change your string to

"https://maps.googleapis.com/maps/api/staticmap?center=($latitude,$longitude)&zoom=20&size=640x640&maptype=satellite&key=MyKey";

source What is the difference between single-quoted and double-quoted strings in PHP?


问:
Difference between view_type and view_mode when defining action window?
What exacty does each of these attribute values mean when used while defining act_window, for eg;

 <record id="open_estimate_quantity_extra_request" model="ir.actions.act_window">
   <field name="name">Extra Requests</field>
   <field name="res_model">estimate.quantity.extra.request</field>
   <field name="view_type">form</field>
   <field name="view_mode">tree,form</field>
 </record>
```

In the above code what does it mean to have a value of form for view_type and a value of tree,form for view_mode.  From what i understand, view_mode tells odoo to display both tree and form views for the  estimate.quantity.extra.request model.  But what purpose does view_type have?

答:
view_mode if defining the list of view mode and the sequence :

<field name="view_mode">tree,form,graph,...</field>
```

<p>but view type_type there is two (tree or form) when you choose tree you can make a special hierarchic tree best example</p>

<p><img src="https://i.stack.imgur.com/EL7Hv.png" alt="enter image description here"> </p>

<p>but when you change the type_view from tree to form all  the children records cannot be seen :</p>

<p><img src="https://i.stack.imgur.com/EmztM.png" alt="enter image description here"></p>

<p>view_type it's used for Hierarchy tree view, see account module to see how is the don you need to compute level field and you need a one2many field children recordSet</p>

<p>see Model <code>_name = "account.financial.report"</code></p>

<p>[EDITS] :
The key to this is in the tree and the action </p>

<pre class="lang-xml prettyprint-override"><code><record id="view_account_report_tree_hierarchy" model="ir.ui.view">
    <field name="name">account.report.hierarchy</field>
    <field name="model">account.financial.report</field>
    <!-- this field one2many field and the compute field level -->
    <field name="field_parent">children_ids</field>
    <field name="arch" type="xml">
        <tree string="Account Reports Hierarchy">
            <field name="name"/>
            <field name="type"/>
            <field name="parent_id" invisible="1"/>
            <field name="account_report_id"/>
        </tree>
    </field>
</record>
</code>```

Body:
What exacty does each of these attribute values mean when used while defining act_window, for eg;

 <record id="open_estimate_quantity_extra_request" model="ir.actions.act_window">
   <field name="name">Extra Requests</field>
   <field name="res_model">estimate.quantity.extra.request</field>
   <field name="view_type">form</field>
   <field name="view_mode">tree,form</field>
 </record>

In the above code what does it mean to have a value of form for view_type and a value of tree,form for view_mode.  From what i understand, view_mode tells odoo to display both tree and form views for the  estimate.quantity.extra.request model.  But what purpose does view_type have?

Body:
view_mode if defining the list of view mode and the sequence :

<field name="view_mode">tree,form,graph,...</field>

but view type_type there is two (tree or form) when you choose tree you can make a special hierarchic tree best example

but when you change the type_view from tree to form all  the children records cannot be seen :

view_type it's used for Hierarchy tree view, see account module to see how is the don you need to compute level field and you need a one2many field children recordSet

see Model _name = "account.financial.report"

[EDITS] :
The key to this is in the tree and the action

<record id="view_account_report_tree_hierarchy" model="ir.ui.view">
    <field name="name">account.report.hierarchy</field>
    <field name="model">account.financial.report</field>
    <!-- this field one2many field and the compute field level -->
    <field name="field_parent">children_ids</field>
    <field name="arch" type="xml">
        <tree string="Account Reports Hierarchy">
            <field name="name"/>
            <field name="type"/>
            <field name="parent_id" invisible="1"/>
            <field name="account_report_id"/>
        </tree>
    </field>
</record>


问:
Unable to execute Perl script unless Perl is inserted before script name
Running Lubuntu -
Beginner Perl programmer

Script is XXX.pl located at ~/projects/XXX/XXX.pl

First line is the shebang

```<code>#!/usr/bin/perl
</code>```

Permission to run is set to Anyone.

In directory ~/projects/XXX, the command

```<code>~/projects/XXX$ perl XXX.pl
</code>```

works as desired, but the command

```<code>~/projects/XXX$ XXX.pl
</code>```

Fails with XXX.pl: command not found

What am I missing ?

答:
Can the script be found?

Is . in your path? If it's not, add it to your path, or use ./XXX.pl instead of XXX.pl.

Can the script be executed?

Do you have execute permission to the file? Fix using chmod u+x XXX.pl.

Is the interpreter correct?

which perl will tell you which interpreter is used when you use perl XXX.pl. That's the path that should be on your shebang (#!) line.

Body:
Running Lubuntu -
Beginner Perl programmer

Script is XXX.pl located at ~/projects/XXX/XXX.pl

First line is the shebang

#!/usr/bin/perl

Permission to run is set to Anyone.

In directory ~/projects/XXX, the command

~/projects/XXX$ perl XXX.pl

works as desired, but the command

~/projects/XXX$ XXX.pl

Fails with XXX.pl: command not found

What am I missing ?


问:
Cannot perform ember data queries/rest call inside Ember.service
I'm using ember 2.12

Here's my route

```<code>import Ember from 'ember';

export default Ember.Route.extend({
    rentalService: Ember.inject.service('rentals-service'),

    model(){
        this.get('rentalService').findRentals();
        console.log('Inside route');
        console.log(this.get('store'));
        return this.get('store').findAll('rental');
  }
});
</code>```

Here's my ember rental-service

```<code>import Ember from 'ember';

export default Ember.Service.extend({
  findRentals() {
    console.log("Inside servce");
    console.log(this.get('store'));
    return "hello from servce";
  }
});
</code>```

Why is it I cannot access the ember-data on the rental-service? whenever I console .log this.get('store') inside the rental-service it returns an undefined. However on the routes, whenever I console.log the same code it returns this value.

Does this mean I cannot perform a rest call using ember data inside a service?

I'm using Mirage to mock a web-server/http requests

答:
You cannot access the store inside an ember component/service. A workaround for this is to retrieve the store via dependency injection.

```<code>export default Ember.Service.extend({
  store: Ember.inject.service('store'),

  findRentals() {
    console.log("Inside service");
    console.log(this.get('store'));
    return "hello from service";
  }
});
</code>```

Be wary if you have another service with a name of store, it might fetch that one.

Body:
I'm using ember 2.12

Here's my route

import Ember from 'ember';

export default Ember.Route.extend({
    rentalService: Ember.inject.service('rentals-service'),

    model(){
        this.get('rentalService').findRentals();
        console.log('Inside route');
        console.log(this.get('store'));
        return this.get('store').findAll('rental');
  }
});

Here's my ember rental-service

import Ember from 'ember';

export default Ember.Service.extend({
  findRentals() {
    console.log("Inside servce");
    console.log(this.get('store'));
    return "hello from servce";
  }
});

Why is it I cannot access the ember-data on the rental-service? whenever I console .log this.get('store') inside the rental-service it returns an undefined. However on the routes, whenever I console.log the same code it returns this value.

Does this mean I cannot perform a rest call using ember data inside a service?

I'm using Mirage to mock a web-server/http requests

Body:
You cannot access the store inside an ember component/service. A workaround for this is to retrieve the store via dependency injection.

export default Ember.Service.extend({
  store: Ember.inject.service('store'),

  findRentals() {
    console.log("Inside service");
    console.log(this.get('store'));
    return "hello from service";
  }
});

Be wary if you have another service with a name of store, it might fetch that one.


问:
speed up sql INSERTs
I have the following method to insert millions of rows of data into a table (I use SQL 2008) and it seems slow, is there any way to speed up INSERTs?

Here is the code snippet - I use MS enterprise library

```<code>        public void InsertHistoricData(List<DataRow> dataRowList)
        {
            string sql = string.Format( @"INSERT INTO [MyTable] ([Date],[Open],[High],[Low],[Close],[Volumn])
                VALUES( @DateVal, @OpenVal, @High, @Low, @CloseVal, @Volumn )");

            DbCommand dbCommand = VictoriaDB.GetSqlStringCommand( sql );
            DB.AddInParameter(dbCommand, "DateVal", DbType.Date);
            DB.AddInParameter(dbCommand, "OpenVal", DbType.Currency);
            DB.AddInParameter(dbCommand, "High", DbType.Currency );
            DB.AddInParameter(dbCommand, "Low", DbType.Currency);
            DB.AddInParameter(dbCommand, "CloseVal", DbType.Currency);
            DB.AddInParameter(dbCommand, "Volumn", DbType.Int32);

            foreach (NasdaqHistoricDataRow dataRow in dataRowList)
            {
                DB.SetParameterValue( dbCommand, "DateVal", dataRow.Date );
                DB.SetParameterValue( dbCommand, "OpenVal", dataRow.Open );
                DB.SetParameterValue( dbCommand, "High", dataRow.High );
                DB.SetParameterValue( dbCommand, "Low", dataRow.Low );
                DB.SetParameterValue( dbCommand, "CloseVal", dataRow.Close );
                DB.SetParameterValue( dbCommand, "Volumn", dataRow.Volumn );

                DB.ExecuteNonQuery( dbCommand );
            }
        }
</code>```

答:
FYI - looping through a record set and doing a million+ inserts on a relational DB, is the worst case scenario when loading a table. Some languages now offer record-set objects. For fastest performance SMINK is right, use BULK INSERT. Millions of rows loaded in minutes, rather than hours. Orders of magnitude faster than any other method.

As an example, I worked on a eCommerce project, that required a product list refresh each night. 100,000 rows inserted into a high-end Oracle DB, took 10 hours. If I remember correctly the top speed to when doing row-by-row inserts is aprox 10 recs/sec. Painful slow and completely unnecessary. With bulk insert - 100K rows should take less than a minute.

Hope this helps.

Title: speed up sql INSERTs

Body:
I have the following method to insert millions of rows of data into a table (I use SQL 2008) and it seems slow, is there any way to speed up INSERTs?

Here is the code snippet - I use MS enterprise library

        public void InsertHistoricData(List<DataRow> dataRowList)
        {
            string sql = string.Format( @"INSERT INTO [MyTable] ([Date],[Open],[High],[Low],[Close],[Volumn])
                VALUES( @DateVal, @OpenVal, @High, @Low, @CloseVal, @Volumn )");

            DbCommand dbCommand = VictoriaDB.GetSqlStringCommand( sql );
            DB.AddInParameter(dbCommand, "DateVal", DbType.Date);
            DB.AddInParameter(dbCommand, "OpenVal", DbType.Currency);
            DB.AddInParameter(dbCommand, "High", DbType.Currency );
            DB.AddInParameter(dbCommand, "Low", DbType.Currency);
            DB.AddInParameter(dbCommand, "CloseVal", DbType.Currency);
            DB.AddInParameter(dbCommand, "Volumn", DbType.Int32);

            foreach (NasdaqHistoricDataRow dataRow in dataRowList)
            {
                DB.SetParameterValue( dbCommand, "DateVal", dataRow.Date );
                DB.SetParameterValue( dbCommand, "OpenVal", dataRow.Open );
                DB.SetParameterValue( dbCommand, "High", dataRow.High );
                DB.SetParameterValue( dbCommand, "Low", dataRow.Low );
                DB.SetParameterValue( dbCommand, "CloseVal", dataRow.Close );
                DB.SetParameterValue( dbCommand, "Volumn", dataRow.Volumn );

                DB.ExecuteNonQuery( dbCommand );
            }
        }


问:
Android saving coordinates canvas Drawcircle and display on Different Devices
```<code>class Draw extends View {
    private Paint mPaint;
    public Button mCircles;

    DrawFragment mDrawFragment;
    private Circle mCurrentCircle;
    private List<Circle> mCircle= new ArrayList<>();

    public Draw(Context context){
        this(context,null);
    }

    public Draw(Context context, AttributeSet attrs) {
        super(context, attrs);

        mPaint=new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setAlpha(80);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        for (Circle circle : mCircle) {
            float x1 = circle.getCenter().x;
            float x2 = circle.getFinal().x;
            float y1 = circle.getCenter().y;
            float y2 = circle.getFinal().y;

            double radius = Math.sqrt(Math.pow(dpx1 - dpx2, 2) + Math.pow(dpy1 - dpy2, 2));

            float rad = (float) radius;

            canvas.drawCircle(dpx1, dpy1, rad, mPaint);
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mCurrentCircle = new Circle(current);
                mCircle.add(mCurrentCircle);
                break;

            case MotionEvent.ACTION_MOVE:
                if (mCurrentCircle != null) {
                    mCurrentCircle.setFinal(current);
                    invalidate();
                }
                break;

            case MotionEvent.ACTION_UP:
                mCurrentCircle = null;
                invalidate();  break;
        }

    }

    Log.i(TAG, "onTouchEvent: at x="+current.x + ", y =" + current.y);

    return true;
}
</code>```

1.I'm saving these coordinates of circles drawn on canvas and this is to mark damages on a car.
            but when i use these values to display on a bigger device , Circle positions are not intact .. what can be done?

答:
All the coordinates are referenced to a device with a screen determined by pixels and pixels per inches.

If you wish to use the same information on a different device, you must set a sort of anchor point which works for you as a reference.

For example, if those circles will be drawn over a background image of a car, you should be able to reference theme to the position of that picture.

With that information, on any other device, you should be able to redraw those circles on any device based on the fact the coordinates are not referenced to the device but are reference to the car image.

I hope this help you to re think the problem.

Body:
class Draw extends View {
    private Paint mPaint;
    public Button mCircles;

    DrawFragment mDrawFragment;
    private Circle mCurrentCircle;
    private List<Circle> mCircle= new ArrayList<>();

    public Draw(Context context){
        this(context,null);
    }

    public Draw(Context context, AttributeSet attrs) {
        super(context, attrs);

        mPaint=new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setAlpha(80);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        for (Circle circle : mCircle) {
            float x1 = circle.getCenter().x;
            float x2 = circle.getFinal().x;
            float y1 = circle.getCenter().y;
            float y2 = circle.getFinal().y;

            double radius = Math.sqrt(Math.pow(dpx1 - dpx2, 2) + Math.pow(dpy1 - dpy2, 2));

            float rad = (float) radius;

            canvas.drawCircle(dpx1, dpy1, rad, mPaint);
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mCurrentCircle = new Circle(current);
                mCircle.add(mCurrentCircle);
                break;

            case MotionEvent.ACTION_MOVE:
                if (mCurrentCircle != null) {
                    mCurrentCircle.setFinal(current);
                    invalidate();
                }
                break;

            case MotionEvent.ACTION_UP:
                mCurrentCircle = null;
                invalidate();  break;
        }

    }

    Log.i(TAG, "onTouchEvent: at x="+current.x + ", y =" + current.y);

    return true;
}

1.I'm saving these coordinates of circles drawn on canvas and this is to mark damages on a car.
            but when i use these values to display on a bigger device , Circle positions are not intact .. what can be done?


问:
This is a bug in Date class or i mistake (Java/android)
i write this code

```<code>Date xx2 = new Date(2017,3,31);
Date xx3 = new Date(2017,4,1);

Assistance.print("--> y:"+xx2.getYear()+"  m:"+xx2.getMonth()+" d:"+xx2.getDate());
Assistance.print("--> y:"+xx3.getYear()+"  m:"+xx3.getMonth()+" d:"+xx3.getDate());
</code>```

but i get same result !!!

Result:

--> y: 2017  m:4   d:1

--> y: 2017  m:4   d:1

What?

答:
You need to read the javadoc of constructor
Date(int year, int month, int day)
carefully, especially

month - the month between 0-11

Hence, new Date(2017,3,31) is April 31,
and new Date(2017,4,1) is May 01, which is actually the same day (because April has 30 days only).

Body:
i write this code

Date xx2 = new Date(2017,3,31);
Date xx3 = new Date(2017,4,1);

Assistance.print("--> y:"+xx2.getYear()+"  m:"+xx2.getMonth()+" d:"+xx2.getDate());
Assistance.print("--> y:"+xx3.getYear()+"  m:"+xx3.getMonth()+" d:"+xx3.getDate());

but i get same result !!!

Result:

--> y: 2017  m:4   d:1

--> y: 2017  m:4   d:1

What?


问:
find a path that contains specific text
How do I find all paths that contain the string "tomcat" from a specific directory?
i.e. I want to find anything that contains tomcat1, tomcat2, tomcat3 etc?

Thanks.

答:
With Linux find (GNU findutils) 4.7 try -wholename test:

find . -wholename */tomcat*

or

find . -type d -wholename */tomcat*

Title: find a path that contains specific text


问:
Why am I getting so many br tags
I started writing html code and when I view it on chrome, the table is displayed after a long white space. When I inspect the element, on chrome, I get a lot of br tags but I have not given any br tags in the code

How come?

<!DOCTYPE html>

  <title> Practice </title>

 <big><big> Registration Form <big><big>

<form name="My Form" action="" method="">

 Username
 <input type="text" name="t1" size="6"/>

 Password
 <input type="password" name="t2" size="6"/>

 Name
 <input type="text" name="t3" size="30"/>

 Address
 <input type="text" name="t4" size="30"/>

 Country
<select name="s1">
<option> Select Your Country </option>
<option> Afghanistan </option>
<option> Bangladesh </option>
<option> China </option>
<option> India </option>
<option> Russia </option>
</select>

 Zip Code
 <input type="text" name="t5" size="6"/>

 Email
 <input type="text" name="t6" size="30"/>

Sex
<input type="radio" name="r1" value="100" checked/>Male
<input type="radio" name="r1" value="102"/>Female

Language
<input type="checkbox" name="r1" value="100" checked/>English
<input type="checkbox" name="r2" value="102"/>Non English

 About
<textarea name="a1" rows="5" cols="32"> </textarea>

<input type="submit" name="b2" value="submit here"/>

</form>

```

答:
Use this code, This might solve your issues

```<code>  <table border="0.00001" align="center" bgcolor="silver" cellpadding="10">
    <caption align="center"><b> Registration Form </b> </caption><br><br>
<form name="My Form" action="" method="">
<tr>
<td> Username </td>
<td> <input type="text" name="t1" size="6"/> </td>
</tr>

<tr>
<td> Password </td>
<td> <input type="password" name="t2" size="6"/> </td>
</tr>

<tr>
<td> Name </td>
<td> <input type="text" name="t3" size="30"/> </td>
</tr>

<tr>
<td> Address </td>
<td> <input type="text" name="t4" size="30"/> </td>
</tr>

<tr>
<td> Country </td>
<td><select name="s1">
<option> Select Your Country </option>
<option> Afghanistan </option>
<option> Bangladesh </option>
<option> China </option>
<option> India </option>
<option> Russia </option>
</select></td>
</tr>

<tr>
<td> Zip Code </td>
<td> <input type="text" name="t5" size="6"/> </td>
</tr>

<tr>
<td> Email </td>
<td> <input type="text" name="t6" size="30"/> </td>
</tr>
<tr>
<td>Sex</td>
<td><input type="radio" name="r1" value="100" checked/>Male
<input type="radio" name="r1" value="102"/>Female</td>
</tr>
<tr>
<td>Language</td>
<td><input type="checkbox" name="r1" value="100" checked/>English
<input type="checkbox" name="r2" value="102"/>Non English</td>
</tr>

<tr>
<td> About </td>
<td><textarea name="a1" rows="5" cols="32"> </textarea></td>
</tr>

<tr align="centre">
<td><input type="submit" name="b2" value="submit here"/></td>
</tr>

</form>
</table>
</code>```

Just removed some un-necessary tags, that might be causing issues. Please try

Title: Why am I getting so many br tags

Body:
Use this code, This might solve your issues

  <table border="0.00001" align="center" bgcolor="silver" cellpadding="10">
    <caption align="center"><b> Registration Form </b> </caption><br><br>
<form name="My Form" action="" method="">
<tr>
<td> Username </td>
<td> <input type="text" name="t1" size="6"/> </td>
</tr>

<tr>
<td> Password </td>
<td> <input type="password" name="t2" size="6"/> </td>
</tr>

<tr>
<td> Name </td>
<td> <input type="text" name="t3" size="30"/> </td>
</tr>

<tr>
<td> Address </td>
<td> <input type="text" name="t4" size="30"/> </td>
</tr>

<tr>
<td> Country </td>
<td><select name="s1">
<option> Select Your Country </option>
<option> Afghanistan </option>
<option> Bangladesh </option>
<option> China </option>
<option> India </option>
<option> Russia </option>
</select></td>
</tr>

<tr>
<td> Zip Code </td>
<td> <input type="text" name="t5" size="6"/> </td>
</tr>

<tr>
<td> Email </td>
<td> <input type="text" name="t6" size="30"/> </td>
</tr>
<tr>
<td>Sex</td>
<td><input type="radio" name="r1" value="100" checked/>Male
<input type="radio" name="r1" value="102"/>Female</td>
</tr>
<tr>
<td>Language</td>
<td><input type="checkbox" name="r1" value="100" checked/>English
<input type="checkbox" name="r2" value="102"/>Non English</td>
</tr>

<tr>
<td> About </td>
<td><textarea name="a1" rows="5" cols="32"> </textarea></td>
</tr>

<tr align="centre">
<td><input type="submit" name="b2" value="submit here"/></td>
</tr>

</form>
</table>

Just removed some un-necessary tags, that might be causing issues. Please try


问:
Complex string split method in java
basically, I am trying to be able to read every line separated by some conditions (\n \s , )and store the String into Node A and Node B for the purpose of node addition, but not sure where to start or figured out what to do. please Help!

```<code>public static void main(String[] args) {

    try{
        String oneLine;
        FileReader theFile = new FileReader("src/Test.txt");
        BufferedReader inFile = new BufferedReader(theFile);
        Node A = new Node(0,null);

        while((oneLine = inFile.readLine()) != null) {

            String numbers[]= oneLine.split("\n");

            for (int i=0;i<numbers.length;i++){
                 int a = Integer.parseInt(numbers[i]);
                 A.addNumtoNode(a); } } }

public void addNumtoNode(int e){
        head = new Node(e,head);
        if (size == 0)
        tail = head;
        size++;
        }
</code>```

Sample of Test.txt

```<code>9
4

31,415,926,535
2

0
1,234,567,890

1,734,792
131

1,506,033,005,018,000,029
1,992
</code>```

答:
String#split() takes regular expression as delimiter.

Use regex \D+ it means One or more Non digit.

So just change String numbers[]= oneLine.split("\n")
 to  :

```<code> if (oneLine.isEmpty()) {
      continue;
 }
 String numbers[]= oneLine.split("\\D+");
</code>```

Title: Complex string split method in java

Body:
basically, I am trying to be able to read every line separated by some conditions (\n \s , )and store the String into Node A and Node B for the purpose of node addition, but not sure where to start or figured out what to do. please Help!

public static void main(String[] args) {

    try{
        String oneLine;
        FileReader theFile = new FileReader("src/Test.txt");
        BufferedReader inFile = new BufferedReader(theFile);
        Node A = new Node(0,null);

        while((oneLine = inFile.readLine()) != null) {

            String numbers[]= oneLine.split("\n");

            for (int i=0;i<numbers.length;i++){
                 int a = Integer.parseInt(numbers[i]);
                 A.addNumtoNode(a); } } }

public void addNumtoNode(int e){
        head = new Node(e,head);
        if (size == 0)
        tail = head;
        size++;
        }

Sample of Test.txt

9
4

31,415,926,535
2

0
1,234,567,890

1,734,792
131

1,506,033,005,018,000,029
1,992

Body:
String#split() takes regular expression as delimiter.

Use regex \D+ it means One or more Non digit.

So just change String numbers[]= oneLine.split("\n")
 to  :

 if (oneLine.isEmpty()) {
      continue;
 }
 String numbers[]= oneLine.split("\\D+");


问:
Meebo triggers a mixed content warning in IE
Hey all.  I've installed the meebo toolbar on our test website and it's working fine generally except that in some versions of IE, on an https page, it generates a mixed content warning.  When i render out the page i look at request.protocol and decide whether to add the "https:true" option to the meebo javascript so i'd have thought it would be fine.

I'm looking at what gets loaded by JS in the IE8 developers toolbar and can see the following problem resource loads:

```<code>https://s-ssl.meebocdn.net/cim/skin_v89_cim_10_3_4/bar.ie8.http.s-ssl.meebocdn.net.css
https://s-ssl.meebocdn.net/cim/skin_v89_cim_10_3_4/bar.ie8.http.s-ssl.meebocdn.net.css
</code>```

Now i'm not sure what meebo does with these but even though there a reference to an http (rather than https in there) url it also references ssl and is in fact an https request.  So, why does this trigger a warning, does anyone know?

Here's what the developer toolbar info window says:

```<code>GET /cim/skin_v89_cim_10_3_4/bar.ie8.http.s-ssl.meebocdn.net.css HTTP/1.1
Accept: */*
Referer: https://cim.meebo.com/cim/sandbox.php?lang=en-GB&version=v89_cim_10_3_4&protocol=https%3A&network=millionaireforschools_ri84xu
Accept-Language: en-gb
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Accept-Encoding: gzip, deflate
Host: s-ssl.meebocdn.net
Connection: Keep-Alive

HTTP/1.1 404 Not Found
Server: EdgePrismSSL
Date: Mon, 08 Nov 2010 17:39:38 GMT
Content-Type: text/html
Connection: keep-alive
Content-Length: 345
</code>```

As you can see it's a 404 but i don't know if that is due to meebo going wrong or IE going wrong somehow.  Any ideas anyone?

cheers, max

答: I suspect what's going on is that meebo's javascript creates iframes without src attributes. See http://ajaxian.com/archives/ie-frame-bug and similar posts.</p>

Body:
Hey all.  I've installed the meebo toolbar on our test website and it's working fine generally except that in some versions of IE, on an https page, it generates a mixed content warning.  When i render out the page i look at request.protocol and decide whether to add the "https:true" option to the meebo javascript so i'd have thought it would be fine.

I'm looking at what gets loaded by JS in the IE8 developers toolbar and can see the following problem resource loads:

https://s-ssl.meebocdn.net/cim/skin_v89_cim_10_3_4/bar.ie8.http.s-ssl.meebocdn.net.css
https://s-ssl.meebocdn.net/cim/skin_v89_cim_10_3_4/bar.ie8.http.s-ssl.meebocdn.net.css

Now i'm not sure what meebo does with these but even though there a reference to an http (rather than https in there) url it also references ssl and is in fact an https request.  So, why does this trigger a warning, does anyone know?

Here's what the developer toolbar info window says:

GET /cim/skin_v89_cim_10_3_4/bar.ie8.http.s-ssl.meebocdn.net.css HTTP/1.1
Accept: */*
Referer: https://cim.meebo.com/cim/sandbox.php?lang=en-GB&version=v89_cim_10_3_4&protocol=https%3A&network=millionaireforschools_ri84xu
Accept-Language: en-gb
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Accept-Encoding: gzip, deflate
Host: s-ssl.meebocdn.net
Connection: Keep-Alive

HTTP/1.1 404 Not Found
Server: EdgePrismSSL
Date: Mon, 08 Nov 2010 17:39:38 GMT
Content-Type: text/html
Connection: keep-alive
Content-Length: 345

As you can see it's a 404 but i don't know if that is due to meebo going wrong or IE going wrong somehow.  Any ideas anyone?

cheers, max


问:
Get all possible english words from a string
Generate all possible combination of english words from a given string in python.

Input: godaddy
Output: go, god, dad, add, daddy

Any good libraries?

答:
First, get a set of all English words. I expect there are many libraries that can do this, but recommendations for software libraries are off-topic for Stack Overflow, so just use whatever you can find.

Then, iterate through all substrings of the string, and see if any of them are in the collection.

```<code>words = #???
s = "godaddy"
for i in range(len(s)):
    for j in range(i+1, len(s)):
        substring = s[i:j+1]
        if substring in words:
            print(substring)
</code>```

Result:

```<code>go
god
od
oda
da
dad
daddy
ad
add
</code>```

Body:
First, get a set of all English words. I expect there are many libraries that can do this, but recommendations for software libraries are off-topic for Stack Overflow, so just use whatever you can find.

Then, iterate through all substrings of the string, and see if any of them are in the collection.

words = #???
s = "godaddy"
for i in range(len(s)):
    for j in range(i+1, len(s)):
        substring = s[i:j+1]
        if substring in words:
            print(substring)

Result:

go
god
od
oda
da
dad
daddy
ad
add


问:
Python 3 troubles with dictionary and list
I need to get index (number) of item in list, which contains a string c = "Return To Sender (Matrey Remix)". Then get information from this index. But I got numbers of all items in list. No errors

```<code>demo = json.loads(raw)
c = "Return To Sender (Matrey Remix)"
for i in (i for i, tr in enumerate(demo['tracks']) if str(tr['title']).find(c)):
    print(i)
dict = demo['tracks'][i]
</code>```

For example I have 7 track titles in result of code:

```<code>for tr in demo['tracks']:
    print(tr['title'])
</code>```

Track titles:

```<code>Return To Sender (Original Mix)
Return To Sender (Matrey Remix)
Return To Sender (Matrey Remix)
Return To Sender (Matrey Remix)
Return To Sender (Original Mix)
Return To Sender (Original Mix)
Return To Sender (Original Mix)
</code>```

But output is empty

The demo object:

```<code>{
    'mixes': [],
    'packs': [],
    'stems': [],
    'tracks': [{
        'id': 7407969,
        'mix': 'Original Mix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Original Mix)',
    }, {
        'id': 7407971,
        'mix': 'Matrey Remix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Matrey Remix)',
    }, {
        'id': 9011142,
        'mix': 'Matrey Remix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Matrey Remix)',
    }, {
        'id': 7846774,
        'mix': 'Matrey Remix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Matrey Remix)',
    }, {
        'id': 7407969,
        'mix': 'Original Mix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Original Mix)',
    }, {
        'id': 9011141,
        'mix': 'Original Mix',
        'name': 'Return To Sender',
        'type': 'track',
    }, {
        'id': 7789328,
        'mix': 'Original Mix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Original Mix)',
    }]
}
</code>```

答:
str.find() returns 0 when the text is found at the start:

```<code>>>> 'foo bar'.find('foo')
0
</code>```

That is considered a false value in a boolean context:

```<code>>>> if 0:
...     print('Found at position 0!')
...
>>>
</code>```

If the text is not there, str.find() returns -1 instead. From the str.find() documentation:

Return the lowest index in the string where substring sub is found [...]. Return -1 if sub is not found.

This means that only if the text is at the start will your code not print anything. In all other cases (including not finding the title), the tracks will be printed.

Don't use str.find(). Use in to get True if the text is there, False if it is not:

```<code>for i in (i for i, tr in enumerate(demo['tracks']) if c in tr['title']):
</code>```

Demo using your json data:

```<code>>>> c = "Return To Sender (Matrey Remix)"
>>> for i in (i for i, tr in enumerate(demo['tracks']) if c in tr['title']):
...     print(i)
...
1
2
3
</code>```

Body:
I need to get index (number) of item in list, which contains a string c = "Return To Sender (Matrey Remix)". Then get information from this index. But I got numbers of all items in list. No errors

demo = json.loads(raw)
c = "Return To Sender (Matrey Remix)"
for i in (i for i, tr in enumerate(demo['tracks']) if str(tr['title']).find(c)):
    print(i)
dict = demo['tracks'][i]

For example I have 7 track titles in result of code:

for tr in demo['tracks']:
    print(tr['title'])

Track titles:

Return To Sender (Original Mix)
Return To Sender (Matrey Remix)
Return To Sender (Matrey Remix)
Return To Sender (Matrey Remix)
Return To Sender (Original Mix)
Return To Sender (Original Mix)
Return To Sender (Original Mix)

But output is empty

The demo object:

{
    'mixes': [],
    'packs': [],
    'stems': [],
    'tracks': [{
        'id': 7407969,
        'mix': 'Original Mix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Original Mix)',
    }, {
        'id': 7407971,
        'mix': 'Matrey Remix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Matrey Remix)',
    }, {
        'id': 9011142,
        'mix': 'Matrey Remix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Matrey Remix)',
    }, {
        'id': 7846774,
        'mix': 'Matrey Remix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Matrey Remix)',
    }, {
        'id': 7407969,
        'mix': 'Original Mix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Original Mix)',
    }, {
        'id': 9011141,
        'mix': 'Original Mix',
        'name': 'Return To Sender',
        'type': 'track',
    }, {
        'id': 7789328,
        'mix': 'Original Mix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Original Mix)',
    }]
}

Body:
str.find() returns 0 when the text is found at the start:

>>> 'foo bar'.find('foo')
0

That is considered a false value in a boolean context:

>>> if 0:
...     print('Found at position 0!')
...
>>>

If the text is not there, str.find() returns -1 instead. From the str.find() documentation:

Return the lowest index in the string where substring sub is found [...]. Return -1 if sub is not found.

This means that only if the text is at the start will your code not print anything. In all other cases (including not finding the title), the tracks will be printed.

Don't use str.find(). Use in to get True if the text is there, False if it is not:

for i in (i for i, tr in enumerate(demo['tracks']) if c in tr['title']):

Demo using your json data:

>>> c = "Return To Sender (Matrey Remix)"
>>> for i in (i for i, tr in enumerate(demo['tracks']) if c in tr['title']):
...     print(i)
...
1
2
3


问:
how to reorder columns with only text in r
I have a dataframe in R which looks like this

```<code>ClientID    Reason_1    Reason_2   Reason_3  Reason_4   Reason_5   Reason_6    Reason_7    Reason_8
 ABC         Trend                  Low                   High       Med
 XYZ                     High       Low                                          Low
 PQW                                          High        Low                                Med
</code>```

There is no text in every reason column, I want to reorder this to following

```<code> ClientID    Reason_1    Reason_2   Reason_3  Reason_4   Reason_5   Reason_6    Reason_7    Reason_8
 ABC         Trend         Low       High       Med
 XYZ          High         Low       Low
 PQW          High         Low       Med
</code>```

Is there any easy way to this in R other than ifelse to check every column to see whether it contains text or not and if not then copy the other columns text into that column.

答:
This can be done by looping over the rows using apply with MARGIN = 1 to select only the non-empty elements, then the empty elements, concatenate it together, transpose and assign it back to the original dataset

```<code>df1[] <- t(apply(df1, 1, FUN = function(x) c(x[x!=""], x[x==""])))
df1
#    ClientID Reason_1 Reason_2 Reason_3 Reason_4 Reason_5 Reason_6 Reason_7
#1      ABC    Trend      Low     High      Med
#2      XYZ     High      Low      Low
#3      PQW     High      Low      Med
#     Reason_8
#1
#2
#3
</code>```

If the blanks are NA then use is.na instead of == and !=

```<code>df1[] <- t(apply(df1, 1, FUN = function(x) c(x[!is.na(x)], x[is.na(x)])))
</code>```

Or another option is to paste the elements by row and then read it with read.table and fill = TRUE

```<code>df2 <- read.table(text=do.call(paste, df1), header=FALSE,
                  na.strings = "", col.names = names(df1), fill = TRUE)
</code>```

data

```<code>df1 <- structure(list(ClientID = c("ABC", "XYZ", "PQW"), Reason_1 = c("Trend",
 "", ""), Reason_2 = c("", "High", ""), Reason_3 = c("Low", "Low",
 ""), Reason_4 = c("", "", "High"), Reason_5 = c("High", "", "Low"
 ), Reason_6 = c("Med", "", ""), Reason_7 = c("", "Low", ""),
Reason_8 = c("", "", "Med")), .Names = c("ClientID", "Reason_1",
"Reason_2", "Reason_3", "Reason_4", "Reason_5", "Reason_6", "Reason_7",
"Reason_8"), class = "data.frame", row.names = c(NA, -3L))
</code>```

Body:
I have a dataframe in R which looks like this

ClientID    Reason_1    Reason_2   Reason_3  Reason_4   Reason_5   Reason_6    Reason_7    Reason_8
 ABC         Trend                  Low                   High       Med
 XYZ                     High       Low                                          Low
 PQW                                          High        Low                                Med

There is no text in every reason column, I want to reorder this to following

 ClientID    Reason_1    Reason_2   Reason_3  Reason_4   Reason_5   Reason_6    Reason_7    Reason_8
 ABC         Trend         Low       High       Med
 XYZ          High         Low       Low
 PQW          High         Low       Med

Is there any easy way to this in R other than ifelse to check every column to see whether it contains text or not and if not then copy the other columns text into that column.

Body:
This can be done by looping over the rows using apply with MARGIN = 1 to select only the non-empty elements, then the empty elements, concatenate it together, transpose and assign it back to the original dataset

df1[] <- t(apply(df1, 1, FUN = function(x) c(x[x!=""], x[x==""])))
df1
#    ClientID Reason_1 Reason_2 Reason_3 Reason_4 Reason_5 Reason_6 Reason_7
#1      ABC    Trend      Low     High      Med
#2      XYZ     High      Low      Low
#3      PQW     High      Low      Med
#     Reason_8
#1
#2
#3

If the blanks are NA then use is.na instead of == and !=

df1[] <- t(apply(df1, 1, FUN = function(x) c(x[!is.na(x)], x[is.na(x)])))

Or another option is to paste the elements by row and then read it with read.table and fill = TRUE

df2 <- read.table(text=do.call(paste, df1), header=FALSE,
                  na.strings = "", col.names = names(df1), fill = TRUE)

data

df1 <- structure(list(ClientID = c("ABC", "XYZ", "PQW"), Reason_1 = c("Trend",
 "", ""), Reason_2 = c("", "High", ""), Reason_3 = c("Low", "Low",
 ""), Reason_4 = c("", "", "High"), Reason_5 = c("High", "", "Low"
 ), Reason_6 = c("Med", "", ""), Reason_7 = c("", "Low", ""),
Reason_8 = c("", "", "Med")), .Names = c("ClientID", "Reason_1",
"Reason_2", "Reason_3", "Reason_4", "Reason_5", "Reason_6", "Reason_7",
"Reason_8"), class = "data.frame", row.names = c(NA, -3L))


问:
How to use asp:Table in asp:ListView LayoutTemplate ItemTemplate
I get the following exception message when I call the DataBind() method of the ListView

'Table' cannot have children of type 'ListViewDataItem'.

Here's my markup

```<code><asp:ListView ID="lv" runat="server">
    <LayoutTemplate>
        <asp:Table ID="t" runat="server" CssClass="contentframework">
            <asp:TableHeaderRow>
                <asp:TableHeaderCell>1</asp:TableHeaderCell>
                <asp:TableHeaderCell>2</asp:TableHeaderCell>
            </asp:TableHeaderRow>

            <asp:TableRow ID="itemPlaceHolder" runat="server" />

        </asp:Table>

    </LayoutTemplate>

    <ItemTemplate>
        <asp:TableRow>
            <asp:TableCell><%# Eval("1") %></asp:TableCell>
            <asp:TableCell><%# Eval("2") %></asp:TableCell>
        </asp:TableRow>
    </ItemTemplate>

    <EmptyDataTemplate>
        <h2>No Records!</h2>
    </EmptyDataTemplate>
</asp:ListView>
</code>```

答:
You have to nest an asp:tableCell in the asp:TableRow and then the placeholder should work in the tablecell</p>

```<code><asp:TableRow runat="server">
    <asp:TableCell ID="TableCell2" runat="server">
        <asp:PlaceHolder runat="server" ID="itemplaceholder" />
    </asp:TableCell>
</asp:TableRow>`
</code>```

Body:
I get the following exception message when I call the DataBind() method of the ListView

'Table' cannot have children of type 'ListViewDataItem'.

Here's my markup

<asp:ListView ID="lv" runat="server">
    <LayoutTemplate>
        <asp:Table ID="t" runat="server" CssClass="contentframework">
            <asp:TableHeaderRow>
                <asp:TableHeaderCell>1</asp:TableHeaderCell>
                <asp:TableHeaderCell>2</asp:TableHeaderCell>
            </asp:TableHeaderRow>

            <asp:TableRow ID="itemPlaceHolder" runat="server" />

        </asp:Table>

    </LayoutTemplate>

    <ItemTemplate>
        <asp:TableRow>
            <asp:TableCell><%# Eval("1") %></asp:TableCell>
            <asp:TableCell><%# Eval("2") %></asp:TableCell>
        </asp:TableRow>
    </ItemTemplate>

    <EmptyDataTemplate>

No Records!

    </EmptyDataTemplate>
</asp:ListView>

Body:
You have to nest an asp:tableCell in the asp:TableRow and then the placeholder should work in the tablecell

<asp:TableRow runat="server">
    <asp:TableCell ID="TableCell2" runat="server">
        <asp:PlaceHolder runat="server" ID="itemplaceholder" />
    </asp:TableCell>
</asp:TableRow>`


问:
Exception of a method not handled and code compiles successfully
```<code>public class ExceptionDemo {

    public static void main(String...args) {
        try {
            bar();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        foo();
    }

    public static void bar() {

    }

    public static void foo() throws NullPointerException {

    }
}
</code>```

Please explain me why this code compiles successfully even though we didn't handle foo() method exception.

答:
In java we have two exception,

```<code>1) Checked Exception (Compile Time Exception)
2) Unchecked Exception (Runtime Exception)
</code>```

NullPointerException is a Runtime Exception, means it will get checked at Runtime.

Here in your example Foo() method propagating NullPointeException by throws keyword to the calling method so at the time of compilation it is okay but if somehow NullPointerException will be thrown at runtime your code will break.

Recommendation: You should handle it by checking null rather than propagating it by throws.

for more details you can check http://technostepup.com/CoreJava/ExceptionHandling/exception-types.php

Body:
public class ExceptionDemo {

    public static void main(String...args) {
        try {
            bar();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        foo();
    }

    public static void bar() {

    }

    public static void foo() throws NullPointerException {

    }
}

Please explain me why this code compiles successfully even though we didn't handle foo() method exception.

Body:
In java we have two exception,

1) Checked Exception (Compile Time Exception)
2) Unchecked Exception (Runtime Exception)

NullPointerException is a Runtime Exception, means it will get checked at Runtime.

Here in your example Foo() method propagating NullPointeException by throws keyword to the calling method so at the time of compilation it is okay but if somehow NullPointerException will be thrown at runtime your code will break.

Recommendation: You should handle it by checking null rather than propagating it by throws.

for more details you can check http://technostepup.com/CoreJava/ExceptionHandling/exception-types.php


问:
curl gives 403 error?
I'm trying to set a cookie for my phpBB forums from a MediaWiki login page. Using the hook after a login to the wiki is successful, I want to run a php script that sets the cookie.

The script works when I run it independently or when I use GET , but for security reasons I want to POST to the script. For this I figured curl would be the best option.

Unfortunately, even the basic script like this:

```<code>curl_setopt($ch, CURLOPT_URL, "http://www.example.com/ForumLogin.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
</code>```

Gives me a 403 Forbidden error. There's no rules in robots.txt that should interfere. What else could I try to get the script to work, or are there any other ways I could run the script from within MediaWiki?

答:
to act/request like real try "curl/7.39.0" user agent

```<code>$useragent= "curl/7.39.0";
curl_setopt($ch,CURLOPT_USERAGENT, $useragent);
</code>```

or try randam user agents from browsers array list like

```<code>//browser pack start
         $useragents=array(
      "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4",
      "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4",
      "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53",
      "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
      "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
      "Mozilla/5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53",
      "Mozilla/5.0 (iPad; CPU OS 4_3_5 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8L1 Safari/6533.18.5",
      "Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",
      "Mozilla/5.0 (Linux; U; en-us; KFTHWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",
      "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.0.141.16-Gen4_11004310) AppleWebkit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true",
      "Mozilla/5.0 (Linux; U; Android 2.3.4; en-us; Nexus S Build/GRJ22) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
      "Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.72 Safari/537.36",
      "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
      "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+",
      "Mozilla/5.0 (Linux; Android 4.3; Nexus 10 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.72 Safari/537.36",
      "Mozilla/5.0 (Linux; U; Android 2.3; en-us; SAMSUNG-SGH-I717 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
      "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
      "Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
      "Mozilla/5.0 (Linux; Android 4.2.2; GT-I9505 Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36",
      "Mozilla/5.0 (Linux; U; Android 2.2; en-us; SCH-I800 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",

         "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36");
            //browser pack end
  $useragent=$useragents[rand()%sizeof($useragents)];
     curl_setopt($ch,CURLOPT_USERAGENT, $useragent);
</code>```

Title: curl gives 403 error?

Body:
I'm trying to set a cookie for my phpBB forums from a MediaWiki login page. Using the hook after a login to the wiki is successful, I want to run a php script that sets the cookie.

The script works when I run it independently or when I use GET , but for security reasons I want to POST to the script. For this I figured curl would be the best option.

Unfortunately, even the basic script like this:

curl_setopt($ch, CURLOPT_URL, "http://www.example.com/ForumLogin.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);

Gives me a 403 Forbidden error. There's no rules in robots.txt that should interfere. What else could I try to get the script to work, or are there any other ways I could run the script from within MediaWiki?

Body:
to act/request like real try "curl/7.39.0" user agent

$useragent= "curl/7.39.0";
curl_setopt($ch,CURLOPT_USERAGENT, $useragent);

or try randam user agents from browsers array list like

//browser pack start
         $useragents=array(
      "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4",
      "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4",
      "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53",
      "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
      "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
      "Mozilla/5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53",
      "Mozilla/5.0 (iPad; CPU OS 4_3_5 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8L1 Safari/6533.18.5",
      "Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",
      "Mozilla/5.0 (Linux; U; en-us; KFTHWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",
      "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.0.141.16-Gen4_11004310) AppleWebkit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true",
      "Mozilla/5.0 (Linux; U; Android 2.3.4; en-us; Nexus S Build/GRJ22) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
      "Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.72 Safari/537.36",
      "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
      "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+",
      "Mozilla/5.0 (Linux; Android 4.3; Nexus 10 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.72 Safari/537.36",
      "Mozilla/5.0 (Linux; U; Android 2.3; en-us; SAMSUNG-SGH-I717 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
      "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
      "Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
      "Mozilla/5.0 (Linux; Android 4.2.2; GT-I9505 Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36",
      "Mozilla/5.0 (Linux; U; Android 2.2; en-us; SCH-I800 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",

         "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36");
            //browser pack end
  $useragent=$useragents[rand()%sizeof($useragents)];
     curl_setopt($ch,CURLOPT_USERAGENT, $useragent);