问:
Operation with checkbox in a nested gridview
This is the design for the GridView.

```<code><asp:GridView ID="gmainrole" runat="server" OnRowDataBound="gmainrole_RowDataBound">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <input type="checkbox" id="chkavail" runat="server" checked='<%#Eval("checkstatus") %>' />

                <asp:Literal ID="litstate" runat="server" Text='<%#Eval("areaname") %>'></asp:Literal>
                <asp:Literal ID="lituserrole" runat="server" Text='<%#Eval("nid") %>' Visible="false"></asp:Literal>
                <asp:GridView ID="subrole" runat="server" AutoGenerateColumns="false" OnRowDataBound="subrole_RowDataBound">
                    <Columns>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:CheckBox ID="chk1vail" runat="server" Checked='<%#Eval("checkstatus") %>' />
                                <asp:Literal ID="litstate" runat="server" Text='<%#Eval("areaname") %>'></asp:Literal>
                                <asp:Literal ID="lituserrole" runat="server" Text='<%#Eval("nid") %>' Visible="false"></asp:Literal>
                                <asp:DataList ID="glastrole" runat="server" GridLines="None" AutoGenerateColumns="false" OnItemDataBound="glastrole_ItemDataBound">
                                    <ItemTemplate>
                                        <div>
                                            <asp:CheckBoxList runat="server" ID="chklastrole">
                                            </asp:CheckBoxList>

                                                                                <asp:Literal ID="Literal1" runat="server" Text='<%#Eval("areaname") %>'></asp:Literal>
                                            <asp:Literal ID="litlast" runat="server" Text='<%#Eval("nid") %>' Visible="false"></asp:Literal>
                                            <asp:DataList ID="ecounter" runat="server" GridLines="None" AutoGenerateColumns="false">
                                                <ItemTemplate>
                                                    <asp:CheckBoxList runat="server" ID="chklastrole">
                                                    </asp:CheckBoxList>

                                                                                <asp:Literal ID="Literal11" runat="server" Text='<%#Eval("areaname") %>'></asp:Literal>
                                                    <asp:Literal ID="litlast1" runat="server" Text='<%#Eval("nid") %>' Visible="false"></asp:Literal>
                                                </ItemTemplate>
                                            </asp:DataList>
                                        </div>
                                    </ItemTemplate>
                                </asp:DataList>
                                </table>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
                </td>
                    </tr>
                </table>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
</code>```

This GridView is a four level nested GridView where the lower two levels are DataLists and upper two levels are GridViews. I want that when a user checks a CheckBox inside the second GridView named subrole(level 2), all the subsequent CheckBoxes in the DataList glastrole(level 3) and DataList ecounter(level 4) get their CheckBoxes checked for that particular level 2 checkbox. I would give you the code that I have tried till now but the fact is I don't even know how to approach this problem. Please help!

答:
Try this can solve your problem:

Add OnCheckedChanged property <asp:CheckBox ID="chk1vail" OnCheckedChanged="Checked_Changed" runat="server" Checked='<%#Eval("checkstatus") %>' />

code behind to find the controls:

```<code>    protected void Checked_Changed(object sender, EventArgs e)
    {
        // gets a row from GridView
        GridViewRow subrole_row = ((CheckBox)sender).Parent as GridViewRow;

        // get GridView
        GridView subrole = subrole_row.Parent as GridView;

        // find the datalist in GridView
        DataList glastrole = subrole.Rows[subrole_row.RowIndex].FindControl("glastrole") as DataList;

        glastrole.DataSource = glastrole_dt; // set your data to datalist
        glastrole.DataBind(); // bind datalist

        subrole.DataSource = subrole_dt; // set your data to gridview
        subrole.DataBind(); // bind gridview
    }

    protected void glastrole_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            GridViewRow subrole_row = ((DataList)sender).Parent as GridViewRow;

            CheckBox chk1vail = subrole_row.FindControl("chk1vail") as CheckBox;

            // find CheckBoxList in glastrole
            CheckBoxList chklastrole = e.Item.FindControl("chklastrole") as CheckBoxList;

            // find if checkbox is checked
            if (chk1vail.Checked)
            {
                // here you can check all the CheckBoxList items
                foreach (ListItem item in chklastrole.Items)
                {
                    item.Selected = true;
                }
            }

            // find DataList in glastrole
            DataList ecounter = e.Item.FindControl("ecounter") as DataList;

            ecounter.DataSource = ecounter_dt; // set your data to datalist
            ecounter.DataBind(); // bind datalist
        }
    }

    protected void ecounter_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            DataList glastrole = ((DataList)sender).Parent as DataList;
            DataList ecounter = glastrole.Parent as DataList;

            GridViewRow subrole_row = ecounter.Parent as GridViewRow;

            CheckBox chk1vail = subrole_row.FindControl("chk1vail") as CheckBox;

            // find CheckBoxList in glastrole
            CheckBoxList chklastrole = e.Item.FindControl("chklastrole") as CheckBoxList;

            // find if checkbox is checked
            if (chk1vail.Checked)
            {
                // here you can check all the CheckBoxList items
                foreach (ListItem item in chklastrole.Items)
                {
                    item.Selected = true;
                }
            }
        }
    }
</code>```

Body:
This is the design for the GridView.

<asp:GridView ID="gmainrole" runat="server" OnRowDataBound="gmainrole_RowDataBound">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <input type="checkbox" id="chkavail" runat="server" checked='<%#Eval("checkstatus") %>' />

                <asp:Literal ID="litstate" runat="server" Text='<%#Eval("areaname") %>'></asp:Literal>
                <asp:Literal ID="lituserrole" runat="server" Text='<%#Eval("nid") %>' Visible="false"></asp:Literal>
                <asp:GridView ID="subrole" runat="server" AutoGenerateColumns="false" OnRowDataBound="subrole_RowDataBound">
                    <Columns>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:CheckBox ID="chk1vail" runat="server" Checked='<%#Eval("checkstatus") %>' />
                                <asp:Literal ID="litstate" runat="server" Text='<%#Eval("areaname") %>'></asp:Literal>
                                <asp:Literal ID="lituserrole" runat="server" Text='<%#Eval("nid") %>' Visible="false"></asp:Literal>
                                <asp:DataList ID="glastrole" runat="server" GridLines="None" AutoGenerateColumns="false" OnItemDataBound="glastrole_ItemDataBound">
                                    <ItemTemplate>

                                            <asp:CheckBoxList runat="server" ID="chklastrole">
                                            </asp:CheckBoxList>

                                                                                <asp:Literal ID="Literal1" runat="server" Text='<%#Eval("areaname") %>'></asp:Literal>
                                            <asp:Literal ID="litlast" runat="server" Text='<%#Eval("nid") %>' Visible="false"></asp:Literal>
                                            <asp:DataList ID="ecounter" runat="server" GridLines="None" AutoGenerateColumns="false">
                                                <ItemTemplate>
                                                    <asp:CheckBoxList runat="server" ID="chklastrole">
                                                    </asp:CheckBoxList>

                                                                                <asp:Literal ID="Literal11" runat="server" Text='<%#Eval("areaname") %>'></asp:Literal>
                                                    <asp:Literal ID="litlast1" runat="server" Text='<%#Eval("nid") %>' Visible="false"></asp:Literal>
                                                </ItemTemplate>
                                            </asp:DataList>

                                    </ItemTemplate>
                                </asp:DataList>

                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

This GridView is a four level nested GridView where the lower two levels are DataLists and upper two levels are GridViews. I want that when a user checks a CheckBox inside the second GridView named subrole(level 2), all the subsequent CheckBoxes in the DataList glastrole(level 3) and DataList ecounter(level 4) get their CheckBoxes checked for that particular level 2 checkbox. I would give you the code that I have tried till now but the fact is I don't even know how to approach this problem. Please help!

Body:
Try this can solve your problem:

Add OnCheckedChanged property <asp:CheckBox ID="chk1vail" OnCheckedChanged="Checked_Changed" runat="server" Checked='<%#Eval("checkstatus") %>' />

code behind to find the controls:

    protected void Checked_Changed(object sender, EventArgs e)
    {
        // gets a row from GridView
        GridViewRow subrole_row = ((CheckBox)sender).Parent as GridViewRow;

        // get GridView
        GridView subrole = subrole_row.Parent as GridView;

        // find the datalist in GridView
        DataList glastrole = subrole.Rows[subrole_row.RowIndex].FindControl("glastrole") as DataList;

        glastrole.DataSource = glastrole_dt; // set your data to datalist
        glastrole.DataBind(); // bind datalist

        subrole.DataSource = subrole_dt; // set your data to gridview
        subrole.DataBind(); // bind gridview
    }

    protected void glastrole_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            GridViewRow subrole_row = ((DataList)sender).Parent as GridViewRow;

            CheckBox chk1vail = subrole_row.FindControl("chk1vail") as CheckBox;

            // find CheckBoxList in glastrole
            CheckBoxList chklastrole = e.Item.FindControl("chklastrole") as CheckBoxList;

            // find if checkbox is checked
            if (chk1vail.Checked)
            {
                // here you can check all the CheckBoxList items
                foreach (ListItem item in chklastrole.Items)
                {
                    item.Selected = true;
                }
            }

            // find DataList in glastrole
            DataList ecounter = e.Item.FindControl("ecounter") as DataList;

            ecounter.DataSource = ecounter_dt; // set your data to datalist
            ecounter.DataBind(); // bind datalist
        }
    }

    protected void ecounter_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            DataList glastrole = ((DataList)sender).Parent as DataList;
            DataList ecounter = glastrole.Parent as DataList;

            GridViewRow subrole_row = ecounter.Parent as GridViewRow;

            CheckBox chk1vail = subrole_row.FindControl("chk1vail") as CheckBox;

            // find CheckBoxList in glastrole
            CheckBoxList chklastrole = e.Item.FindControl("chklastrole") as CheckBoxList;

            // find if checkbox is checked
            if (chk1vail.Checked)
            {
                // here you can check all the CheckBoxList items
                foreach (ListItem item in chklastrole.Items)
                {
                    item.Selected = true;
                }
            }
        }
    }


来源: stackexchange

问:
Double Clicking a shell script on Mac
i have a small script that runs a jar file :

```<code>#!/bin/bash

prefix="foo";
name=`ls ${prefix}*.jar`;
echo $name;
java -jar $name prop1.properties prop2.properties
</code>```

when i run it in the terminal using ./myscript.sh, it works fine and the jar file executes, but when i rename it in myscript.command and double click it, i have this error :

```<code>ls: foo*.jar : No such file or directory
</code>```

I saw that apparently a .command file opens a terminal at the root directory, so I tried finding the directory containing myscript.command using that :

```<code>dir = 'find <dir> -maxdepth 1 -type d -name '*myDirContainingJar*' -print -quit'
cd $dir
</code>```

but dir is just blank, any ideas ???

答:
Opening a shell script from Finder on macOS (whether it has extension .command or is an extension-less executable shell script) makes the current user's home directory the current directory (as of macOS 10.12).

To explicitly change to the directory in which the script itself is located in a bash script, use:

```<code>cd -- "$(dirname -- "$BASH_SOURCE")"
</code>```

In this invocation scenario, the following POSIX-compliant variation, which uses $0 in lieu of $BASH_SOURCE, would work too:  cd -- "$(dirname -- "$0")"

Note:

Generally, if your script is invoked via a symlink and you want to change to the target's directory (the actual script file's directory as opposed to the directory in which the symlink is located), more work is needed - see this answer of mine.

When opening a script from Finder, however, this issue does not apply, because Finder itself resolves a symlink to its (ultimate) target and then invokes the target directly.

ContentLicense: CC BY-SA 3.0

Title: Double Clicking a shell script on Mac

Body:
i have a small script that runs a jar file :

#!/bin/bash

prefix="foo";
name=`ls ${prefix}*.jar`;
echo $name;
java -jar $name prop1.properties prop2.properties

when i run it in the terminal using ./myscript.sh, it works fine and the jar file executes, but when i rename it in myscript.command and double click it, i have this error :

ls: foo*.jar : No such file or directory

I saw that apparently a .command file opens a terminal at the root directory, so I tried finding the directory containing myscript.command using that :

dir = 'find <dir> -maxdepth 1 -type d -name '*myDirContainingJar*' -print -quit'
cd $dir

but dir is just blank, any ideas ???

Body:
Opening a shell script from Finder on macOS (whether it has extension .command or is an extension-less executable shell script) makes the current user's home directory the current directory (as of macOS 10.12).

To explicitly change to the directory in which the script itself is located in a bash script, use:

cd -- "$(dirname -- "$BASH_SOURCE")"

In this invocation scenario, the following POSIX-compliant variation, which uses $0 in lieu of $BASH_SOURCE, would work too:  cd -- "$(dirname -- "$0")"

Note:

Generally, if your script is invoked via a symlink and you want to change to the target's directory (the actual script file's directory as opposed to the directory in which the symlink is located), more work is needed - see this answer of mine.

When opening a script from Finder, however, this issue does not apply, because Finder itself resolves a symlink to its (ultimate) target and then invokes the target directly.


问:
How to make a foreach of an object in javascript?
I am currently building a mashup in Qlik Sense in JavaScript and jQuery. I have made some data selection and I have put them in a variable object :

```<code>var CurrentSelec = app1.selectionState().selections;
console.log(CurrentSelec);`
console.log(typeof CurrentSelec);
</code>```

This is what I get on my browser console :

I'm trying to show the qSelected value in a Foreach :

I have tried with Javascript :

```<code>for(var index in CurrentSelec) {
    console.log(index.qSelected);
}
</code>```

I have tried with jQuery:

```<code>$.each(CurrentSelec, function(i, index) {
  console.log(index.qSelected)
});
</code>```

But my browser console do not show the log of my foreach.

Do you know how to properly make a foreach of an object and show its content on a browser console, please ?

Regards.

答:
You can use jQuery as like this,

```<code>$.each(CurrentSelec, function( key, value ) {
   alert( key + ": " + value );
});
</code>```

I am sure it helps,

Body:
I am currently building a mashup in Qlik Sense in JavaScript and jQuery. I have made some data selection and I have put them in a variable object :

var CurrentSelec = app1.selectionState().selections;
console.log(CurrentSelec);`
console.log(typeof CurrentSelec);

This is what I get on my browser console :

I'm trying to show the qSelected value in a Foreach :

I have tried with Javascript :

for(var index in CurrentSelec) {
    console.log(index.qSelected);
}

I have tried with jQuery:

$.each(CurrentSelec, function(i, index) {
  console.log(index.qSelected)
});

But my browser console do not show the log of my foreach.

Do you know how to properly make a foreach of an object and show its content on a browser console, please ?

Regards.

Body:
You can use jQuery as like this,

$.each(CurrentSelec, function( key, value ) {
   alert( key + ": " + value );
});

I am sure it helps,


问:
Why are 2 of the 6 built-in constants assignable?
In the documentation on built-in constants (excluding site constants) it's stated that:

Note: The names None, False, True and __debug__ cannot be reassigned (assignments to them, even as an attribute name, raise SyntaxError), so they can be considered “true” constants.

If I'm not mistaken, True and False became "true" contants in Python 3. (As also described in the duplicate.)

Question is, why aren't the other two (Ellipsis, NotImplemented) "true" contants? Is there a use case for re-assigning these (numpy with Ellipsis perhaps?) that has exempted them from this limitation?

Exacerbating my confusion, in the documentation for standard library types, both the Ellipsis and NotImplemented types are, behaviorally, identical to the None type. Namely:

They are singletons

They don't support special operations.

This question is not related to the proposed duplicate: Why were True and False changed to keywords in Python 3. It asks something completely different, namely, why Ellipsis and NotImplemented are not "true" constants and not why True and False where changed into ones.

答:
You can assign to any valid identifier that is not a keyword. What is special about True, False, None is that they are both keywords and identifiers. You can read about the reasoning for that in this question:

Why were True and False changed to keywords in Python 3

Builtins such as NotImplemented or Ellipsis are not special cases, and neither are int, list, type and so on. Assigning to NotImplemented doesn't change the builtin constant. Instead you bind the name Ellipsis to a different value in the current scope. The original Ellipsis is not changed.

Assigning to a keyword is a SyntaxError.

You can see the list of keywords by importing the keywords module.

```<code>>>> import keyword
>>> keyword.kwlist

['False',
 'None',
 'True',
 'and',
 'as',
 'assert',
 'break',
 'class',
 'continue',
 'def',
 'del',
 'elif',
 'else',
 'except',
 'finally',
 'for',
 'from',
 'global',
 'if',
 'import',
 'in',
 'is',
 'lambda',
 'nonlocal',
 'not',
 'or',
 'pass',
 'raise',
 'return',
 'try',
 'while',
 'with',
 'yield']
</code>```

There are lots of builtin identifiers that are not in this list, and you can assign new values to int, Ellipsis etc.

... is a special case, since it's not a valid identifier name in the first place, so it would be impossible to assign to.

Python keeps the list of reserved keywords quite short, compared to many other languages. One reason is probably to keep backwards compatibility with code that for some reason used identifiers such as Ellipsis before it became part of the language.

Body:
You can assign to any valid identifier that is not a keyword. What is special about True, False, None is that they are both keywords and identifiers. You can read about the reasoning for that in this question:

Why were True and False changed to keywords in Python 3

Builtins such as NotImplemented or Ellipsis are not special cases, and neither are int, list, type and so on. Assigning to NotImplemented doesn't change the builtin constant. Instead you bind the name Ellipsis to a different value in the current scope. The original Ellipsis is not changed.

Assigning to a keyword is a SyntaxError.

You can see the list of keywords by importing the keywords module.

>>> import keyword
>>> keyword.kwlist

['False',
 'None',
 'True',
 'and',
 'as',
 'assert',
 'break',
 'class',
 'continue',
 'def',
 'del',
 'elif',
 'else',
 'except',
 'finally',
 'for',
 'from',
 'global',
 'if',
 'import',
 'in',
 'is',
 'lambda',
 'nonlocal',
 'not',
 'or',
 'pass',
 'raise',
 'return',
 'try',
 'while',
 'with',
 'yield']

There are lots of builtin identifiers that are not in this list, and you can assign new values to int, Ellipsis etc.

... is a special case, since it's not a valid identifier name in the first place, so it would be impossible to assign to.

Python keeps the list of reserved keywords quite short, compared to many other languages. One reason is probably to keep backwards compatibility with code that for some reason used identifiers such as Ellipsis before it became part of the language.


问:
Get date from Edittext to DayDecorator
first of all thanks for reading this :)

Here is my problem.

I got an EditText (User date input) and i want to get a colored background on my CustomCalander for that day using DayDecorator.

```<code>//EditText I want to get the date
huablauf = (EditText)getActivity().findViewById(R.id.huablauf);

//adding calendar day decorators

List<DayDecorator> decorators = new ArrayList<>();

decorators.add(new Markierung());

calendarView.setDecorators(decorators);

calendarView.refreshCalendar(currentCalendar);

//class Markierung

private class Markierung implements DayDecorator {

EditText huablauf=(EditText)getActivity().findViewById(R.id.huablauf);

        @Override
        public void decorate(DayView dayView) {

        // I know I have to get my String to a date and then get it to
        // dayView.getDate()! But my code didn´t work

        dayView.getDate();
        int color = Color.parseColor("#f9acb8");
        dayView.setBackgroundColor(color);

        }
</code>```

Hope you can understand my problem and anybody can help :)

Thx from Bavaria

答:
Try this:</p>

```<code>@Override
public void decorate(DayView dayView) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());

    try{
        if(dayView.getDate().equals(dateFormat.parse(huablauf.getText().toString()))){
            int color = Color.parseColor("#f9acb8");
            dayView.setBackgroundColor(color);
        }
    } catch (Exception e){
        //Handle exception.
    }
</code>```

Title: Get date from Edittext to DayDecorator

Body:
first of all thanks for reading this :)

Here is my problem.

I got an EditText (User date input) and i want to get a colored background on my CustomCalander for that day using DayDecorator.

//EditText I want to get the date
huablauf = (EditText)getActivity().findViewById(R.id.huablauf);

//adding calendar day decorators

List<DayDecorator> decorators = new ArrayList<>();

decorators.add(new Markierung());

calendarView.setDecorators(decorators);

calendarView.refreshCalendar(currentCalendar);

//class Markierung

private class Markierung implements DayDecorator {

EditText huablauf=(EditText)getActivity().findViewById(R.id.huablauf);

        @Override
        public void decorate(DayView dayView) {

        // I know I have to get my String to a date and then get it to
        // dayView.getDate()! But my code didn´t work

        dayView.getDate();
        int color = Color.parseColor("#f9acb8");
        dayView.setBackgroundColor(color);

        }

Hope you can understand my problem and anybody can help :)

Thx from Bavaria

Body:
Try this:

@Override
public void decorate(DayView dayView) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());

    try{
        if(dayView.getDate().equals(dateFormat.parse(huablauf.getText().toString()))){
            int color = Color.parseColor("#f9acb8");
            dayView.setBackgroundColor(color);
        }
    } catch (Exception e){
        //Handle exception.
    }


问:
Error in sort.list(y) : invalid input 'Eldon Imàge® Series Desk Accessories, Clear' in 'utf8towcs'
I'm still a newbie in R and I have ran logistic regression model with the below code and the error in the title appeared.Please help

code

```<code>logit_model <- glm(train_data$Returns ~ .,
                  data=train_data,
                  family =binomial (link="logit"))
</code>```

答: No worries fam,the error was that one of the columns had a long name in it.Logistic regression could not execute,maybe it was length issue</p>

Body:
I'm still a newbie in R and I have ran logistic regression model with the below code and the error in the title appeared.Please help

code

logit_model <- glm(train_data$Returns ~ .,
                  data=train_data,
                  family =binomial (link="logit"))


问:
Finding average of data within a certain range
How do I find the average of data set within a certain range? Specifically I am looking to find the average for a data set for all data points that are within one standard deviations of the original average. Here is an example:

```<code>Student_ID  Test_Scores
1           3
1           20
1           30
1           40
1           50
1           60
1           95
</code>```

Average = 42.571

Standard Deviation = 29.854

I want to find all data points that are within one standard deviation of this original average, so within the range (42.571-29.854)<=Data<=(42.571+29.854). And from here I want to recalculate a new average.

So my desired data set is:

```<code>Student_ID  Test_Scores
1           20
1           30
1           40
1           50
1           60
</code>```

My desired new average is: 40

Here is my following SQL code and it didn't yield my desired result:

```<code>SELECT
    Student_ID,
    AVG(Test_Scores)
FROM
    Student_Data
WHERE
    Test_Scores BETWEEN (AVG(Test_Scores)-STDEV(Test_Scores)) AND (AVG(Test_Scores)+STDEV(Test_Scores))
ORDER BY
    Student_ID
</code>```

Anyone know how I could fix this?

答:
```<code>select avg(
            select test_scores from table where
                test_scores between
                                   (
                                    (select avg(test_scores) from table)-(select stddev(test_scores) from table))
                                    and
                                    (
                                    (select avg(test_scores) from table)+(select stddev(test_scores) from table))
           );
</code>```

Body:
How do I find the average of data set within a certain range? Specifically I am looking to find the average for a data set for all data points that are within one standard deviations of the original average. Here is an example:

Student_ID  Test_Scores
1           3
1           20
1           30
1           40
1           50
1           60
1           95

Average = 42.571

Standard Deviation = 29.854

I want to find all data points that are within one standard deviation of this original average, so within the range (42.571-29.854)<=Data<=(42.571+29.854). And from here I want to recalculate a new average.

So my desired data set is:

Student_ID  Test_Scores
1           20
1           30
1           40
1           50
1           60

My desired new average is: 40

Here is my following SQL code and it didn't yield my desired result:

SELECT
    Student_ID,
    AVG(Test_Scores)
FROM
    Student_Data
WHERE
    Test_Scores BETWEEN (AVG(Test_Scores)-STDEV(Test_Scores)) AND (AVG(Test_Scores)+STDEV(Test_Scores))
ORDER BY
    Student_ID

Anyone know how I could fix this?


问:
How to get a value in ng-repeat without ng-model?
I am using ng-repeat for iterating a list of objects. When the user selects an option, I want that object, not a single value. ng-model only seems to give me the id.

答:
You can change your select to use the object, and thus the model:

```<code><select
  ng-model="vm.subapp"
  ng-options="subapp.name for subapp in vm.subapplicationList">
</select>
</code>```

It'll show the name, but it'll use the object. So for you, vm.subapps (or this.subapps in your controller) is an object.

Edit: since you don't want to show the Id you can simply change your alert line:

```<code>alert(JSON.stringify($scope.subappData.value));
</code>```

Then you won't be showing the ID. Also, don't think you need the JSON.stringify(), but also suggest using console.log() instead of alert()

Body:
You can change your select to use the object, and thus the model:

<select
  ng-model="vm.subapp"
  ng-options="subapp.name for subapp in vm.subapplicationList">
</select>

It'll show the name, but it'll use the object. So for you, vm.subapps (or this.subapps in your controller) is an object.

Edit: since you don't want to show the Id you can simply change your alert line:

alert(JSON.stringify($scope.subappData.value));

Then you won't be showing the ID. Also, don't think you need the JSON.stringify(), but also suggest using console.log() instead of alert()


问:
pass method with template arguments to a macro
I am unable to use Google Test's ASSERT_THROW() macro in combination with multiple template arguments. Consider that I want to make sure that construction of Matrix<5,1> throws:

```<code>ASSERT_THROW(Matrix<5,1>(), std::runtime_error);
</code>```

(this example doesn't make a lot of sense, of course this shoud not throw, but it is what stayed after simplifying what I had.)

I get this output from MS VC++ 2008:

```<code>warning C4002: too many actual parameters for macro 'ASSERT_THROW'
error C2143: syntax error : missing ',' before ';'
</code>```

Whereas there are no problems with:

```<code>ASSERT_THROW(Matrix<1>(), std::runtime_error);
</code>```

How can I overcome this problem?

Thanks!

答:
#define COMMA , may not compile in GCC.
Use #define COMMA() , instead.
Why can't I add comment to other's post?</p>

ContentLicense: CC BY-SA 2.5

Body:
I am unable to use Google Test's ASSERT_THROW() macro in combination with multiple template arguments. Consider that I want to make sure that construction of Matrix<5,1> throws:

ASSERT_THROW(Matrix<5,1>(), std::runtime_error);

(this example doesn't make a lot of sense, of course this shoud not throw, but it is what stayed after simplifying what I had.)

I get this output from MS VC++ 2008:

warning C4002: too many actual parameters for macro 'ASSERT_THROW'
error C2143: syntax error : missing ',' before ';'

Whereas there are no problems with:

ASSERT_THROW(Matrix<1>(), std::runtime_error);

How can I overcome this problem?

Thanks!


问:
Analysis and data processing On las file using point cloud library
I have .las data and i want to do analysis on it  and i want to use Features of   POINT CLOUD Library for this . can any body tell me how to covert .las file to .pcd or any other suitable fie format  so i can use the newly created file/format in POINT CLOUD Library  for analysis
here is details step

1) i have .las file and want to convert this to suitable format (.pcd or any other ) so i can use points cloud features
2) use point cloud library features to show Show    point   cloud   data    in  a   data    viewer  user    can perform following

```<code>2.1operations   in  data    viewer.
2.2) Zoom   In/Out
</code>```

答:
Take a look at liblas https://www.liblas.org/

Here is an usage example: http://www.pcl-users.org/Creating-pcd-from-las-files-with-rgb-values-using-laslib-td4028505.html

Body:
I have .las data and i want to do analysis on it  and i want to use Features of   POINT CLOUD Library for this . can any body tell me how to covert .las file to .pcd or any other suitable fie format  so i can use the newly created file/format in POINT CLOUD Library  for analysis
here is details step

1) i have .las file and want to convert this to suitable format (.pcd or any other ) so i can use points cloud features
2) use point cloud library features to show Show    point   cloud   data    in  a   data    viewer  user    can perform following

2.1operations   in  data    viewer.
2.2) Zoom   In/Out


问:
What am i missing Set-DynamicDistributionGroup
I am trying to apply dynamic distribution group recipient filter to take the country into account

```<code>Set-DynamicDistributionGroup -identity "HR - Everyone" -RecipientFilter {(CountryCore -eq 191) -and (RecipientType -eq 'UserMailbox') -and (Company -eq "Contoso ltd")}
</code>```

And i get the 'cannot be null' error, but the documentation says that only 'identity' is required, so i'm puzzled by this.

Cannot retrieve the dynamic parameters for the cmdlet. You cannot call
  a method on a null-valued expression.
      + CategoryInfo          : InvalidArgument: (:) [Set-DynamicDistributionGroup], ParameterBindingException
      + FullyQualifiedErrorId : GetDynamicParametersException,Set-DynamicDistributionGroup

答:
Its countryCode not CountryCore as written in your statement (looks like a typo).

Try:

```<code>Set-DynamicDistributionGroup -identity "HR - Everyone" -RecipientFilter {(CountryCode -eq 191) -and (RecipientType -eq 'UserMailbox') -and (Company -eq "Contoso ltd")}
</code>```

Body:
I am trying to apply dynamic distribution group recipient filter to take the country into account

Set-DynamicDistributionGroup -identity "HR - Everyone" -RecipientFilter {(CountryCore -eq 191) -and (RecipientType -eq 'UserMailbox') -and (Company -eq "Contoso ltd")}

And i get the 'cannot be null' error, but the documentation says that only 'identity' is required, so i'm puzzled by this.

Cannot retrieve the dynamic parameters for the cmdlet. You cannot call
  a method on a null-valued expression.
      + CategoryInfo          : InvalidArgument: (:) [Set-DynamicDistributionGroup], ParameterBindingException
      + FullyQualifiedErrorId : GetDynamicParametersException,Set-DynamicDistributionGroup

Body:
Its countryCode not CountryCore as written in your statement (looks like a typo).

Try:

Set-DynamicDistributionGroup -identity "HR - Everyone" -RecipientFilter {(CountryCode -eq 191) -and (RecipientType -eq 'UserMailbox') -and (Company -eq "Contoso ltd")}


问:
How to set bootstrap checkbox in razor CheckBoxFor()
I want to use bootstrap styled checkbox in my asp .net mvc form, however I find it very difficult. After hours looking for solution, I couldn't find anything that works for me.

Here is my HTML razor code, however checkbox doesn't show.

```<code>                 <div class="form-group">
                    @Html.LabelFor(c => c.IsSynchronize, new { @class = "col-sm-2 control-label" })
                    <div class="col-sm-10">
                        <div class="checkbox">
                            @Html.CheckBoxFor(model => model.IsSynchronize)
                        </div>
                    </div>
                </div>
</code>```

Here is rendered HTML :

```<code><div class="checkbox">
<input data-val="true" data-val-required="Pole Synchronizacja jest wymagane." id="IsSynchronize" name="IsSynchronize" type="checkbox" value="true">
<input name="IsSynchronize" type="hidden" value="false">
</div>
</code>```

How can I setup this simple thing in my form?

答:
Under mvc a true/false checkbox based on the model value (boolean) also has a hidden field with the same name (supposedly to cater for when you don't check the box you still get a value in the Forms collection)

Its this hidden field that stops the checkbox working in bootstrap format.
A bootstrap styled checkbox from what I can see will never display properly under mvc using @Html.CheckBoxFor

This is what i did to get it working

```<code>        <div class="checkbox">
            <input type="checkbox" value="@Model.propertyname" id="[same as property name]" name="[same as property name]" />
            <label for="propertyname">any label you like</label>
        </div>
</code>```

Unfortunately the model isn't updated when you post the form and you have to handle that in the HttpPost'ed action

Body:
I want to use bootstrap styled checkbox in my asp .net mvc form, however I find it very difficult. After hours looking for solution, I couldn't find anything that works for me.

Here is my HTML razor code, however checkbox doesn't show.

                    @Html.LabelFor(c => c.IsSynchronize, new { @class = "col-sm-2 control-label" })

                            @Html.CheckBoxFor(model => model.IsSynchronize)

Here is rendered HTML :

<input data-val="true" data-val-required="Pole Synchronizacja jest wymagane." id="IsSynchronize" name="IsSynchronize" type="checkbox" value="true">
<input name="IsSynchronize" type="hidden" value="false">

How can I setup this simple thing in my form?

Body:
Under mvc a true/false checkbox based on the model value (boolean) also has a hidden field with the same name (supposedly to cater for when you don't check the box you still get a value in the Forms collection)

Its this hidden field that stops the checkbox working in bootstrap format.
A bootstrap styled checkbox from what I can see will never display properly under mvc using @Html.CheckBoxFor

This is what i did to get it working

        <div class="checkbox">
            <input type="checkbox" value="@Model.propertyname" id="[same as property name]" name="[same as property name]" />
            <label for="propertyname">any label you like</label>
        </div>

Unfortunately the model isn't updated when you post the form and you have to handle that in the HttpPost'ed action


问:
Get BlackBerry device phone number
In my application I want to retrive the device phone number. I used Phone.getDevicePhoneNumber(true)

It is working in the simulator, but when I test on the device it returns an empty string.
Is there any other option for getting the device phone number?

I am using jde 4.5.0.

答:
Phone.getDevicePhoneNumber(true) reads the number from the SIM card. The problem is the number isn't always on the SIM card. I've also seen cases where the wrong number is on the SIM card.

There is no guaranteed way to programmatically get the number. What I've done in the past is present the SIM card number to the user and asked them to correct/confirm it.

Title: Get BlackBerry device phone number


问:
Rails 5.1 - Submit form via ajax, returned javascript not executing
I have a Rails 5.1 form for creating a user object, which looks like this when rendered:

```<code><form class="upload-form" action="/users" accept-charset="UTF-8" data-remote="true" method="post">

<input name="utf8" type="hidden" value="✓">

...all the fields...

  <div class="actions">
    <input type="submit" name="commit" value="Submit" data-disable-with="Submit">
  </div>
</form>
</code>```

It submits fine, and the controller actions fires. Here it is:

```<code>  def create
    @user = User.new(user_params)
    if @user.save
      respond_to do |format|
        format.js
      end
    end
  end
</code>```

But the create.js.erb which is returned does not execute in the browser:

```<code>$('#upload-form').on('ajax:success', function(event, data, status, xhr) {
  console.log(data);
  var field = $('#upload-form').find('input[name=fileinput]');
  var file = field[0].files[0];
  console.log(file);
});
</code>```

I am confused as to why this js does not get executed (I can see it returned in the response).

答:
You have defined upload-form as a class, but you are calling it as a ID in the JS

Change

```<code>$('#upload-form').on('ajax:success', function(event, data, status, xhr) {
  console.log(data);
  var field = $('#upload-form').find('input[name=fileinput]');
  var file = field[0].files[0];
  console.log(file);
});
</code>```

to this

```<code>$('.upload-form').on('ajax:success', function(event, data, status, xhr) {
  console.log(data);
  var field = $('.upload-form').find('input[name=fileinput]');
  var file = field[0].files[0];
  console.log(file);
});
</code>```

Body:
I have a Rails 5.1 form for creating a user object, which looks like this when rendered:

<form class="upload-form" action="/users" accept-charset="UTF-8" data-remote="true" method="post">

<input name="utf8" type="hidden" value="✓">

...all the fields...

    <input type="submit" name="commit" value="Submit" data-disable-with="Submit">

</form>

It submits fine, and the controller actions fires. Here it is:

  def create
    @user = User.new(user_params)
    if @user.save
      respond_to do |format|
        format.js
      end
    end
  end

But the create.js.erb which is returned does not execute in the browser:

$('#upload-form').on('ajax:success', function(event, data, status, xhr) {
  console.log(data);
  var field = $('#upload-form').find('input[name=fileinput]');
  var file = field[0].files[0];
  console.log(file);
});

I am confused as to why this js does not get executed (I can see it returned in the response).

Body:
You have defined upload-form as a class, but you are calling it as a ID in the JS

Change

$('#upload-form').on('ajax:success', function(event, data, status, xhr) {
  console.log(data);
  var field = $('#upload-form').find('input[name=fileinput]');
  var file = field[0].files[0];
  console.log(file);
});

to this

$('.upload-form').on('ajax:success', function(event, data, status, xhr) {
  console.log(data);
  var field = $('.upload-form').find('input[name=fileinput]');
  var file = field[0].files[0];
  console.log(file);
});


问:
Do firebase functions run on phonegap desktop?
I am currently trying to build an app that requires users to login and save certain data to a database. I am developing using phonegap but I am fairly new to development. How would I go about using a firebase database to store and read data that users store [Its all text data for small fields, a business card storage app]? Is there any documentation that can help? Most documentation I find points to ionic and firebase, would that be better to use for development?

Would also like to know if the phonegap desktop app for prototyping can be used when prototyping firebase code.

thank you

答:
Yes, there shouldn't be a problem using Firebase with Phonegap cordova Project, including statistics and database. according to this:
https://phonegap.com/blog/2013/04/16/firebase-phonegap-integration/</p>


问:
VBA - ActiveCell.Interior.ColorIndex -4142 error by conditional formatting
I have a check which ensures that no cells in a row are filled with Red(colorindex 3) before carrying on with the function however the Interior.ColorIndex is weirdly returning '-4142'. Anyone experienced this before/notice an error in my code?

```<code>If UCase(ActiveCell.Offset(0, -1).Value) = "X" Then

  For i = 0 To 7
    If ActiveCell.Offset(0, i).Interior.ColorIndex = 3 Then
        MsgBox "Correct fields highlighted in red."
        Exit Sub

    End If
   Next
    ident = ActiveCell.Value
    verNo = ActiveCell.Offset(0, 1).Value
    title = ActiveCell.Offset(0, 2).Value
    status = ActiveCell.Offset(0, 3).Value
    location = ActiveCell.Offset(0, 4).Value
    appDate = ActiveCell.Offset(0, 6).Value
    ccRef = ActiveCell.Offset(0, 7).Value
</code>```

Where I initially add the highlighting:

```<code>With ThisWorkbook.Worksheets("Document Index").Range("B5:B500")
    .FormatConditions.Delete
    .FormatConditions.Add Type:=xlExpression, Formula1:="=AND(($B5=""""),
$A5=""X"")"
    .FormatConditions(1).Interior.ColorIndex = 3
    .FormatConditions.Add Type:=xlExpression, Formula1:="=AND(($B5<>""""),
$A5=""X"")"
   .FormatConditions(2).Interior.ColorIndex = 37
End With
</code>```

答:
There are plenty of reasons why the code does not work. And all of them are hidden in the part of the code that you do not show...

In general, just guessing, is that you do not have writing access to the sheet with the ActiveCell. Thus, you have to unlock it.

Another option can be, that you have selected a Chart, and not a worksheet.

A third option is that you are making some other tricks. In general, a plain code like this works:

```<code>Sub Test
    ActiveCell.Offset(0,0).interior.ColorIndex =3
End Sub
</code>```

But I really think that the error is the first one I have pointed out, I get it when I lock the sheet with the ActiveCell:

Concerning color index in format condition, you should use the nice Functions, provided by Mr. Pearson:

```<code>Function ColorIndexOfCF(Rng As Range, _
    Optional OfText As Boolean = False) As Integer

Dim AC As Integer
AC = ActiveCondition(Rng)
If AC = 0 Then
    If OfText = True Then
       ColorIndexOfCF = Rng.Font.ColorIndex
    Else
       ColorIndexOfCF = Rng.Interior.ColorIndex
    End If
Else
    If OfText = True Then
       ColorIndexOfCF = Rng.FormatConditions(AC).Font.ColorIndex
    Else
       ColorIndexOfCF = Rng.FormatConditions(AC).Interior.ColorIndex
    End If
End If

End Function
</code>```

http://www.cpearson.com/Excel/CFColors.htm

ContentLicense: CC BY-SA 4.0

Body:
I have a check which ensures that no cells in a row are filled with Red(colorindex 3) before carrying on with the function however the Interior.ColorIndex is weirdly returning '-4142'. Anyone experienced this before/notice an error in my code?

If UCase(ActiveCell.Offset(0, -1).Value) = "X" Then

  For i = 0 To 7
    If ActiveCell.Offset(0, i).Interior.ColorIndex = 3 Then
        MsgBox "Correct fields highlighted in red."
        Exit Sub

    End If
   Next
    ident = ActiveCell.Value
    verNo = ActiveCell.Offset(0, 1).Value
    title = ActiveCell.Offset(0, 2).Value
    status = ActiveCell.Offset(0, 3).Value
    location = ActiveCell.Offset(0, 4).Value
    appDate = ActiveCell.Offset(0, 6).Value
    ccRef = ActiveCell.Offset(0, 7).Value

Where I initially add the highlighting:

With ThisWorkbook.Worksheets("Document Index").Range("B5:B500")
    .FormatConditions.Delete
    .FormatConditions.Add Type:=xlExpression, Formula1:="=AND(($B5=""""),
$A5=""X"")"
    .FormatConditions(1).Interior.ColorIndex = 3
    .FormatConditions.Add Type:=xlExpression, Formula1:="=AND(($B5<>""""),
$A5=""X"")"
   .FormatConditions(2).Interior.ColorIndex = 37
End With

Body:
There are plenty of reasons why the code does not work. And all of them are hidden in the part of the code that you do not show...

In general, just guessing, is that you do not have writing access to the sheet with the ActiveCell. Thus, you have to unlock it.

Another option can be, that you have selected a Chart, and not a worksheet.

A third option is that you are making some other tricks. In general, a plain code like this works:

Sub Test
    ActiveCell.Offset(0,0).interior.ColorIndex =3
End Sub

But I really think that the error is the first one I have pointed out, I get it when I lock the sheet with the ActiveCell:

Concerning color index in format condition, you should use the nice Functions, provided by Mr. Pearson:

Function ColorIndexOfCF(Rng As Range, _
    Optional OfText As Boolean = False) As Integer

Dim AC As Integer
AC = ActiveCondition(Rng)
If AC = 0 Then
    If OfText = True Then
       ColorIndexOfCF = Rng.Font.ColorIndex
    Else
       ColorIndexOfCF = Rng.Interior.ColorIndex
    End If
Else
    If OfText = True Then
       ColorIndexOfCF = Rng.FormatConditions(AC).Font.ColorIndex
    Else
       ColorIndexOfCF = Rng.FormatConditions(AC).Interior.ColorIndex
    End If
End If

End Function

http://www.cpearson.com/Excel/CFColors.htm


问:
[HttpPost]public ActionResult Create(FormCollection collection) VERSUS [HttpPost]public ActionResult Create(Dinner dinner)
In Scott Hanselman's book (chapter 1), he provides us with two options to implement [HttpPost] for Create action method.

The first one relies on the TryUpdateModel to update a model object based on the incoming form fields. When the incoming form fields contains invalid input, the ModelState.IsValid will be set to false.

```<code>        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            Dinner dinner = new Dinner();

            if (TryUpdateModel(dinner))
            {
                dinnerRepository.Add(dinner);

                dinnerRepository.Save();

                return RedirectToAction("Details", new { id = dinner.DinnerId });
            }
            else
                return View(dinner);

        }
</code>```

The second method is to utilize a model passed as Create action method arg as follows:

```<code>        [HttpPost]
        public ActionResult Create(Dinner dinner)
        {
            if (ModelState.IsValid)
            {
                dinnerRepository.Add(dinner);

                dinnerRepository.Save();

                return RedirectToAction("Details", new { id = dinner.DinnerId });
            }
            else
                return View(dinner);
        }
</code>```

Which one is more recommended to use in production ?

答:
If all your required data is either in Request.Form, route data, or the URL query string, then you can use model binding like in your second example.

The model binder creates your dinner object and populates it with data from the request by matching up property names.

You can customize the binding process with “white lists”, “black lists”, prefixes, and marker interfaces.
Just make sure you don't unintentionally bind values – see this link.

Body:
In Scott Hanselman's book (chapter 1), he provides us with two options to implement [HttpPost] for Create action method.

The first one relies on the TryUpdateModel to update a model object based on the incoming form fields. When the incoming form fields contains invalid input, the ModelState.IsValid will be set to false.

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            Dinner dinner = new Dinner();

            if (TryUpdateModel(dinner))
            {
                dinnerRepository.Add(dinner);

                dinnerRepository.Save();

                return RedirectToAction("Details", new { id = dinner.DinnerId });
            }
            else
                return View(dinner);

        }

The second method is to utilize a model passed as Create action method arg as follows:

        [HttpPost]
        public ActionResult Create(Dinner dinner)
        {
            if (ModelState.IsValid)
            {
                dinnerRepository.Add(dinner);

                dinnerRepository.Save();

                return RedirectToAction("Details", new { id = dinner.DinnerId });
            }
            else
                return View(dinner);
        }

Which one is more recommended to use in production ?


问:
Parse all inputs from UI into Single Json Objects
I created a code (took help) which picks value from all the slider and drop downs.
I want to parse this as one single json object, lets say "data", how can i do this?
xyz is actually the container which has all the sliders and dropdown, I want to parse all the inputs from UI as single json object

```<code>  <script>
     $(function() {$('#analysis').bind('click', function() {
       $.post('http://127.0.0.1:5002/',{
         'CK': $('CK').val(),
         'OCE': $('OCE').val(),
         'SR': $('SR').val(),
         'ETP': $('ETP').val(),
         'CC': $('CC').val(),
         'RCD': $('RCD').val(),
         'range_01': $('range_01').val(),
         'range_02': $('range_02').val(),
         'range_03': $('range_03').val(),
         'range_04': $('range_04').val(),
       },
       function(data) {
                     var parsed = JSON.parse(data);
//i dont think this is correct- i want to just get data as json object.//
$("#xyz").text(parsed['abc']);
                 });
                return false;
         });
       });
    </script>
</code>```

Image of inputs

答:
Have a look to the solution https://jsfiddle.net/um9h4L4t/

```<code>submit = function() {
    var child = $('#xyz').children();
    var data = {};

    for(var i=0; i<child.length; i++) {
        data[$(child[i]).attr('id')] = $('#' + $(child[i]).attr('id') + ' :selected').val();
    }

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

If you are looking for the same, not sure.

Body:
I created a code (took help) which picks value from all the slider and drop downs.
I want to parse this as one single json object, lets say "data", how can i do this?
xyz is actually the container which has all the sliders and dropdown, I want to parse all the inputs from UI as single json object

Image of inputs

Body:
Have a look to the solution https://jsfiddle.net/um9h4L4t/

submit = function() {
    var child = $('#xyz').children();
    var data = {};

    for(var i=0; i<child.length; i++) {
        data[$(child[i]).attr('id')] = $('#' + $(child[i]).attr('id') + ' :selected').val();
    }

    console.log(data);
}

If you are looking for the same, not sure.


问:
AutoResetEvent with multiple threads
I have an multiuser application with a SQL back end.  Certain key data needs to be kept current between users, so I have a background refresh on those collection classes.  My current refresh code is as follows.

```<code>public virtual bool Refresh()
{
    if (SetRefreshThread() == RefreshLockStatus.AlreadyRefreshing) {
        DebugLogging("Checking for refresh thread lock", ClassDebugLevel.CollectionRefresh);
        if (RefreshLock.WaitOne(5000) == false) {
            DebugLogging("Refresh in already in progress on another thread.  Aborting refresh");
            return false;
        } else {
            DebugLogging("Finished refreshing on other thread so not refreshing again");
            return true;
        }
    }
    DebugLogging("Refresh Starting");
    //Refresh code here
    DebugLogging("Finished refreshing");
    ClearRefreshThread();
    return true;
}
protected RefreshLockStatus SetRefreshThread()
{
    lock (RefreshSyncLock) {
        if (_RefreshThread != null) {
            return RefreshLockStatus.AlreadyRefreshing;
        }
        _RefreshThread = Threading.Thread.CurrentThread;
        RefreshLock.Reset();
        return RefreshLockStatus.Allowed;
    }
}
protected void ClearRefreshThread()
{
    lock (RefreshSyncLock) {
        _RefreshThread = null;
        RefreshLock.Set();
    }
}
private readonly Threading.AutoResetEvent RefreshLock = new Threading.AutoResetEvent(true);
</code>```

This works fine when called by a single thread, I get the log:

```<code>2017-07-06 07:13:55.272294 Thread #010 Collection1->Refresh Starting
2017-07-06 07:13:55.323755 Thread #010 Collection1->Finished refreshing
</code>```

On two threads, I get also get the expected results:

```<code>2017-07-06 07:13:55.272294 Thread #010 Collection1->Refresh Starting
2017-07-06 07:13:55.272294 Thread #011 Collection1->Checking for refresh thread lock
2017-07-06 07:13:55.323755 Thread #010 Collection1->Finished refreshing
2017-07-06 07:13:55.325258 Thread #011 Collection1->Finished refreshing on other thread so not refreshing again
</code>```

On three threads, the third thread times out rather than finishing when the first thread does

```<code>2017-07-06 07:13:55.272294 Thread #010 Collection1->Refresh Starting
2017-07-06 07:13:55.272294 Thread #011 Collection1->Checking for refresh thread lock
2017-07-06 07:13:55.272294 Thread #014 Collection1->Checking for refresh thread lock
2017-07-06 07:13:55.323755 Thread #010 Collection1->Finished refreshing
2017-07-06 07:13:55.325258 Thread #011 Collection1->Finished refreshing on other thread so not refreshing again
2017-07-06 07:14:00.872013 Thread #014 Collection1->Refresh in already in progress on another thread.  Aborting refresh
</code>```

My goal is that if a refresh starts on one thread, and while it is executing, other threads want to refresh that same data they all wait for the first thread to finish, then all return true.  Is there a better synchronization object to accomplish what I want?

答:
It seems that when there are multiple threads paused at the same WaitOne method, the Set method will allow one of them to pass, but not all of them.

Since my goal was to just return as if the method had completed, I just needed to add another Set on the branch after the WaitOne.

```<code>public virtual bool Refresh()
{
    if (SetRefreshThread() == RefreshLockStatus.AlreadyRefreshing) {
        DebugLogging("Checking for refresh thread lock", ClassDebugLevel.CollectionRefresh);
        if (RefreshLock.WaitOne(5000) == false) {
            DebugLogging("Refresh in already in progress on another thread.  Aborting refresh");
            return false;
        } else {
            DebugLogging("Finished refreshing on other thread so not refreshing again");
            RefreshLock.Set //Let next thread that is waiting pass
            return true;
        }
    }
    DebugLogging("Refresh Starting");
    //Refresh code here
    DebugLogging("Finished refreshing");
    ClearRefreshThread();
    return true;
}
</code>```

This gives me my desired log of

```<code>2017-07-07 06:35:28.115506 Thread #011 Collection1->Refresh Starting
2017-07-07 06:35:28.115506 Thread #014 Collection1->Checking for refresh thread lock
2017-07-07 06:35:28.115506 Thread #010 Collection1->Checking for refresh thread lock
2017-07-07 06:35:28.203229 Thread #011 Collection1->Finished refreshing
2017-07-07 06:35:28.204233 Thread #010 Collection1->Finished refreshing on other thread so not refreshing again
2017-07-07 06:35:28.204734 Thread #014 Collection1->Finished refreshing on other thread so not refreshing again
</code>```

Title: AutoResetEvent with multiple threads

Body:
I have an multiuser application with a SQL back end.  Certain key data needs to be kept current between users, so I have a background refresh on those collection classes.  My current refresh code is as follows.

public virtual bool Refresh()
{
    if (SetRefreshThread() == RefreshLockStatus.AlreadyRefreshing) {
        DebugLogging("Checking for refresh thread lock", ClassDebugLevel.CollectionRefresh);
        if (RefreshLock.WaitOne(5000) == false) {
            DebugLogging("Refresh in already in progress on another thread.  Aborting refresh");
            return false;
        } else {
            DebugLogging("Finished refreshing on other thread so not refreshing again");
            return true;
        }
    }
    DebugLogging("Refresh Starting");
    //Refresh code here
    DebugLogging("Finished refreshing");
    ClearRefreshThread();
    return true;
}
protected RefreshLockStatus SetRefreshThread()
{
    lock (RefreshSyncLock) {
        if (_RefreshThread != null) {
            return RefreshLockStatus.AlreadyRefreshing;
        }
        _RefreshThread = Threading.Thread.CurrentThread;
        RefreshLock.Reset();
        return RefreshLockStatus.Allowed;
    }
}
protected void ClearRefreshThread()
{
    lock (RefreshSyncLock) {
        _RefreshThread = null;
        RefreshLock.Set();
    }
}
private readonly Threading.AutoResetEvent RefreshLock = new Threading.AutoResetEvent(true);

This works fine when called by a single thread, I get the log:

2017-07-06 07:13:55.272294 Thread #010 Collection1->Refresh Starting
2017-07-06 07:13:55.323755 Thread #010 Collection1->Finished refreshing

On two threads, I get also get the expected results:

2017-07-06 07:13:55.272294 Thread #010 Collection1->Refresh Starting
2017-07-06 07:13:55.272294 Thread #011 Collection1->Checking for refresh thread lock
2017-07-06 07:13:55.323755 Thread #010 Collection1->Finished refreshing
2017-07-06 07:13:55.325258 Thread #011 Collection1->Finished refreshing on other thread so not refreshing again

On three threads, the third thread times out rather than finishing when the first thread does

2017-07-06 07:13:55.272294 Thread #010 Collection1->Refresh Starting
2017-07-06 07:13:55.272294 Thread #011 Collection1->Checking for refresh thread lock
2017-07-06 07:13:55.272294 Thread #014 Collection1->Checking for refresh thread lock
2017-07-06 07:13:55.323755 Thread #010 Collection1->Finished refreshing
2017-07-06 07:13:55.325258 Thread #011 Collection1->Finished refreshing on other thread so not refreshing again
2017-07-06 07:14:00.872013 Thread #014 Collection1->Refresh in already in progress on another thread.  Aborting refresh

My goal is that if a refresh starts on one thread, and while it is executing, other threads want to refresh that same data they all wait for the first thread to finish, then all return true.  Is there a better synchronization object to accomplish what I want?

Body:
It seems that when there are multiple threads paused at the same WaitOne method, the Set method will allow one of them to pass, but not all of them.

Since my goal was to just return as if the method had completed, I just needed to add another Set on the branch after the WaitOne.

public virtual bool Refresh()
{
    if (SetRefreshThread() == RefreshLockStatus.AlreadyRefreshing) {
        DebugLogging("Checking for refresh thread lock", ClassDebugLevel.CollectionRefresh);
        if (RefreshLock.WaitOne(5000) == false) {
            DebugLogging("Refresh in already in progress on another thread.  Aborting refresh");
            return false;
        } else {
            DebugLogging("Finished refreshing on other thread so not refreshing again");
            RefreshLock.Set //Let next thread that is waiting pass
            return true;
        }
    }
    DebugLogging("Refresh Starting");
    //Refresh code here
    DebugLogging("Finished refreshing");
    ClearRefreshThread();
    return true;
}

This gives me my desired log of

2017-07-07 06:35:28.115506 Thread #011 Collection1->Refresh Starting
2017-07-07 06:35:28.115506 Thread #014 Collection1->Checking for refresh thread lock
2017-07-07 06:35:28.115506 Thread #010 Collection1->Checking for refresh thread lock
2017-07-07 06:35:28.203229 Thread #011 Collection1->Finished refreshing
2017-07-07 06:35:28.204233 Thread #010 Collection1->Finished refreshing on other thread so not refreshing again
2017-07-07 06:35:28.204734 Thread #014 Collection1->Finished refreshing on other thread so not refreshing again


问:
bash script to handle multiple files at once
I have files with multiple extension in a folder like .txt, .update, .text. The file names are like

out1.txt,
out1.text,
out1.update,

out2.txt,
out2.text,
out2.update

and so on....My command looks like this:

```<code>./script.pl out1.txt out1.text out1.update
</code>```

I would like to put this command in the loop for every file. I have tried to use a loop like:

```<code>for i in *.{txt,text,update}
</code>```

But it takes the full name including the extension so I couldn't figure out how to deduce the specific extension files in the command.

Thanks!

答:
you can use :</p>

```<code>for f in *.txt;
do
    b=${f%.txt} # the trick is there
    ./script.pl $b.txt $b.text $b.update
done
</code>```

Body:
I have files with multiple extension in a folder like .txt, .update, .text. The file names are like

out1.txt,
out1.text,
out1.update,

out2.txt,
out2.text,
out2.update

and so on....My command looks like this:

./script.pl out1.txt out1.text out1.update

I would like to put this command in the loop for every file. I have tried to use a loop like:

for i in *.{txt,text,update}

But it takes the full name including the extension so I couldn't figure out how to deduce the specific extension files in the command.

Thanks!

Body:
you can use :

for f in *.txt;
do
    b=${f%.txt} # the trick is there
    ./script.pl $b.txt $b.text $b.update
done


问:
SAS - Advanced querying
I have one SQL table with the data in SAS.  The first column is a datetime, and there is one row for each second. The set spans for about 20 minutes.  The other columns contain integer values.

Here is what I need:

For example, Let's pick 50.  How many times did the integer value go from below 50 to above 50 and stay above 50 for at least n seconds.

Is it possible to conduct such analysis with proc sql?  If yes, how so, and if not, how else?

I am new to SAS, so any help is appreciated.  Let me know if you need more info!

Thanks!

答:
How many times did the integer value go from below/above 50

I think this could be solution to first part of the question. Resolution is maybe the best obtained by comparing current value with prior

```<code>data begin; /*Some test data...*/
    input int_in_question;
    datalines;
    51
    51
    49
    55
    55
    40
    40
    60
    40
    ;
run;

data With_calc;
    set begin;
    if int_in_question < 50 and
        lag(int_in_question)>=50
            then Times_below_50+1;
run;
</code>```

Title: SAS - Advanced querying

Body:
How many times did the integer value go from below/above 50

I think this could be solution to first part of the question. Resolution is maybe the best obtained by comparing current value with prior

data begin; /*Some test data...*/
    input int_in_question;
    datalines;
    51
    51
    49
    55
    55
    40
    40
    60
    40
    ;
run;

data With_calc;
    set begin;
    if int_in_question < 50 and
        lag(int_in_question)>=50
            then Times_below_50+1;
run;


问:
c++11: enum member initialization
I have a class defined as follows

```<code>struct X {
    X() : data() {}

    int data;

    enum class Zzz : int { zero, one, two };
    Zzz  zzz;
};
...
X xval;
</code>```

What is the value of xval.zzz - is undefined or X::Zzz.zero ? I know it will be undefined for regular enums and I am wondering whether typed enums behave differently.

答:
It's uninitialised.

Since the backing type is an int and that can contain a trap representation, the reading of xval.zzz prior to initialisation is undefined. (Out of interest, if the backing type was a char, unsigned char, or signed char, then the behaviour would be merely implementation defined.)

Title: c++11: enum member initialization

Body:
I have a class defined as follows

struct X {
    X() : data() {}

    int data;

    enum class Zzz : int { zero, one, two };
    Zzz  zzz;
};
...
X xval;

What is the value of xval.zzz - is undefined or X::Zzz.zero ? I know it will be undefined for regular enums and I am wondering whether typed enums behave differently.


问:
SQL - Source Control and Schema/Script management
My company has just gone though its annual review process, and I have finally convinced them that it is time to find a better solution to manage our SQL schema/scripts.  Currently, we only have a few scripts to manually update.

I've worked with VS2008 Database Edition at a different company and that is an awesome product. My boss has asked me to take a look at SQL Compare by Redgate and to look for any other products that may be better.  SQL Compare appears to be a great product also.  However, it does not look like they have support for Perforce.

Have you used a variety of products for this?

What tools do you use to manage SQL?

What should be included in the requirements before my company makes a purchase?

答: I am usually use MS Server Management Studio for managing sql, working with data, developing databases and debug its, if i need to export some data as sql script or i need to create some difficult object in database, i use EMS SQL Management Studio for SQL Server, because there I can more clearly see the narrow sections of my code and visual design in this environment gives me easier</p>


问:
Stream video from Raspberry pi to Opencv application on remote computer
What I am trying to achieve is, I have a raspberry 3 with pi camera v2 connected to my local wifi. I want to transmit a live video from the raspberry pi to a computer running Ubuntu. On my computer I am trying to process that video with opencv in real time. The code below is just a sample code to test the video coming from the raspberry pi on my Ubuntu computer. I am using netcat to stream the video and I have listed the shell script below the code.

```<code>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;

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

    VideoCapture cap;
    cap.open("/dev/stdin");
    if (!cap.isOpened())
        return -1;

    Mat edges;
    namedWindow("edges",1);
    for(;;){
        Mat frame;
        cap>>frame;
        imshow("edges",frame);
        if(waitKey(30)>=0)break;
    }

    return 0;
}
</code>```

This is the code to play the stream in opencv.

First I redirect the stream to my opencv app using.
nc -l -p 5001 | ./app

then run I the raspberry camera and stream it using netcat
raspivid -t 999999 -o | nc x.x.x.x 5001  x being the client pc ip address.

This doesn't work for me but I have tried it with mplayer
by running nc -l -p 5001 | mplayer -fps 31 -cache 1024 - and it works perfectly.

I think my problem is I am not capturing the stream properly on my opencv application. I need help please.

答:
I spent around 4 hours trying to make this work and got it working in the end. I am not certain which was the key step, nor why, but I found it all works if I install the following packages on my Ubuntu 16 LTS VirtualBox:

```<code>libtbb2
ffmpeg
libavcodec
libavcodec-dev
libavformat-dev
libtbb-dev
libswscale-dev
libgtk2.0-dev
libtbb-dev
libjpeg-dev
libpng-dev
libtiff-dev
libjasper-dev
libdc1394-22-dev
libv4l-dev
libx264-dev
</code>```

and run the camera on my Raspberry Pi with:

```<code>raspivid -ih -w 1024 -h 768 -o - | nc 192.168.0.98 5001
</code>```

Keywords: Raspberry Pi, RASPI, raspivid, camera, OpenCV, stream, streaming, netcat, nc, network, video

Body:
What I am trying to achieve is, I have a raspberry 3 with pi camera v2 connected to my local wifi. I want to transmit a live video from the raspberry pi to a computer running Ubuntu. On my computer I am trying to process that video with opencv in real time. The code below is just a sample code to test the video coming from the raspberry pi on my Ubuntu computer. I am using netcat to stream the video and I have listed the shell script below the code.

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;

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

    VideoCapture cap;
    cap.open("/dev/stdin");
    if (!cap.isOpened())
        return -1;

    Mat edges;
    namedWindow("edges",1);
    for(;;){
        Mat frame;
        cap>>frame;
        imshow("edges",frame);
        if(waitKey(30)>=0)break;
    }

    return 0;
}

This is the code to play the stream in opencv.

First I redirect the stream to my opencv app using.
nc -l -p 5001 | ./app

then run I the raspberry camera and stream it using netcat
raspivid -t 999999 -o | nc x.x.x.x 5001  x being the client pc ip address.

This doesn't work for me but I have tried it with mplayer
by running nc -l -p 5001 | mplayer -fps 31 -cache 1024 - and it works perfectly.

I think my problem is I am not capturing the stream properly on my opencv application. I need help please.

Body:
I spent around 4 hours trying to make this work and got it working in the end. I am not certain which was the key step, nor why, but I found it all works if I install the following packages on my Ubuntu 16 LTS VirtualBox:

libtbb2
ffmpeg
libavcodec
libavcodec-dev
libavformat-dev
libtbb-dev
libswscale-dev
libgtk2.0-dev
libtbb-dev
libjpeg-dev
libpng-dev
libtiff-dev
libjasper-dev
libdc1394-22-dev
libv4l-dev
libx264-dev

and run the camera on my Raspberry Pi with:

raspivid -ih -w 1024 -h 768 -o - | nc 192.168.0.98 5001

Keywords: Raspberry Pi, RASPI, raspivid, camera, OpenCV, stream, streaming, netcat, nc, network, video


问:
Nested loops with depth parameter in python
How do I make a number of nested loops where depth is a parameter.
I am thinking of a function which takes depth as a parameter

```<code>def make_nested_loops(depth):
    ...
</code>```

And, the result for depth=3 is the following

```<code>for i1 in range(10):
    for i2 in range(i1 + 1, 10):
        for i3 in range(i2 + 1, 10):
            # do stuff
</code>```

So far I've been able to do this using strings building and exec command. But I think there is better and more efficient way to do it.

答: The max number of nested loops you can have is 21 I think. So what you could do is have 21 nested loops in your function, and check if desired depth has been achieved at each loop. If not, add one to current depth variable.</p>

Body:
How do I make a number of nested loops where depth is a parameter.
I am thinking of a function which takes depth as a parameter

def make_nested_loops(depth):
    ...

And, the result for depth=3 is the following

for i1 in range(10):
    for i2 in range(i1 + 1, 10):
        for i3 in range(i2 + 1, 10):
            # do stuff

So far I've been able to do this using strings building and exec command. But I think there is better and more efficient way to do it.


问:
Android - Programmatically retrieve certificate (manually installed) from keystore
On my android device, I manually installed a certificate which goal is to allow me access to a specific website.

When I look in Security -- User certs, I see can see my certificate.

My website is displayed into a webview, so I have to use the following code

```<code>@Override
public void onReceivedClientCertRequest(WebView view, final ClientCertRequest request) {
    if (mCertificates == null || mPrivateKey == null) {
        loadCertificateAndPrivateKey();
    }
    request.proceed(mPrivateKey, mCertificates);
}
</code>```

In my loadCertificateAndPrivateKey() function, I am to get certificate like this

```<code>KeyStore ks = KeyStore.getInstance("AndroidCAStore");
if (ks != null)
{
    ks.load(null, null);
    Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements())
    {
        String alias = (String) aliases.nextElement();
        java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) ks.getCertificate(alias);
        if(cert.getIssuerDN().getName().contains("TOTO")){
            mCertificates = new X509Certificate[1];
            mCertificates[0] = (X509Certificate)cert;

            mPrivateKey = ??;

        }
    }
</code>```

But I don't know how to get the private key...

I tried this way, but key object is null (the same code works when I load my certificate directly from my app)

```<code>Key key = keyStore.getKey(alias, password.toCharArray());
if (key instanceof PrivateKey) {
    mPrivateKey = (PrivateKey)key;
}
</code>```

So I have few questions :

Is it the correct way to retrieve the certificate ?

Why is it not possible to retrieve private key with the certificate's password ?

How to retrieve this privateKey ?

Tkanks for your answers !

答:
I found the way to do that, hope that it'll help somebody.

I followed this link that explain how to implement the entire processus.

Finally, I've got the code bolow.
First, define a KeyChainAliasCallback and call the KainChain.choosePrivateKeyAlias that display an activity to have the user authorization to access certificates store.

```<code>KeyChainAliasCallback keyChainAliasCallback = new KeyChainAliasCallback() {
    @Override
    public void alias(@Nullable String s) {
        Log.d(TAG, "selected alias = " + s);
        asyncTask.execute();
    }
};
KeyChain.choosePrivateKeyAlias(this, keyChainAliasCallback, null, null, null, -1, CERT_ALIAS);
</code>```

Then, you're able to retrieve private key and certificates chains from the internal store (you have to use an async function)

```<code>AsyncTask<Void, Void, Boolean> asyncTask = new AsyncTask<Void, Void, Boolean>() {

    private Exception error;

    @Override
    protected Boolean doInBackground(Void... arg) {
        try {

            PrivateKey pk = KeyChain.getPrivateKey(mContext, CERT_ALIAS);
            X509Certificate[] chain = KeyChain.getCertificateChain(mContext, CERT_ALIAS);

            byte[] data = "foobar".getBytes("ASCII");
            Signature sig = Signature.getInstance("SHA1withRSA");
            sig.initSign(pk);
            sig.update(data);
            byte[] signed = sig.sign();

            PublicKey pubk = chain[0].getPublicKey();
            sig.initVerify(pubk);
            sig.update(data);
            boolean valid = sig.verify(signed);
            Log.d(TAG, "signature is valid: " + valid);

            if(valid) {
                mPrivateKey = pk;
                mCertificates = chain;
            }

            return valid;
        } catch (Exception e) {
            e.printStackTrace();
            error = e;

            return null;
        }
    }

    @Override
    protected void onPostExecute(Boolean valid) {
        if (error != null) {
            Toast.makeText(mContext, "Error: " + error.getMessage(),
                    Toast.LENGTH_LONG).show();

            return;
        } else {
            Toast.makeText(mContext, "Signature is valid: " + valid,
                    Toast.LENGTH_SHORT).show();
            mWebView.loadUrl("https://blablabla.com");
        }

    }
};
</code>```

Then, you're able to give certificate with this function :

```<code>@Override
public void onReceivedClientCertRequest(WebView view, final ClientCertRequest request) {
    request.proceed(mPrivateKey, mCertificates);
}
</code>```

Last thing I have to find is how to display the choosePrivateKeyAlias dialog just one time (the first).

Body:
On my android device, I manually installed a certificate which goal is to allow me access to a specific website.

When I look in Security -- User certs, I see can see my certificate.

My website is displayed into a webview, so I have to use the following code

@Override
public void onReceivedClientCertRequest(WebView view, final ClientCertRequest request) {
    if (mCertificates == null || mPrivateKey == null) {
        loadCertificateAndPrivateKey();
    }
    request.proceed(mPrivateKey, mCertificates);
}

In my loadCertificateAndPrivateKey() function, I am to get certificate like this

KeyStore ks = KeyStore.getInstance("AndroidCAStore");
if (ks != null)
{
    ks.load(null, null);
    Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements())
    {
        String alias = (String) aliases.nextElement();
        java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) ks.getCertificate(alias);
        if(cert.getIssuerDN().getName().contains("TOTO")){
            mCertificates = new X509Certificate[1];
            mCertificates[0] = (X509Certificate)cert;

            mPrivateKey = ??;

        }
    }

But I don't know how to get the private key...

I tried this way, but key object is null (the same code works when I load my certificate directly from my app)

Key key = keyStore.getKey(alias, password.toCharArray());
if (key instanceof PrivateKey) {
    mPrivateKey = (PrivateKey)key;
}

So I have few questions :

Is it the correct way to retrieve the certificate ?

Why is it not possible to retrieve private key with the certificate's password ?

How to retrieve this privateKey ?

Tkanks for your answers !

Body:
I found the way to do that, hope that it'll help somebody.

I followed this link that explain how to implement the entire processus.

Finally, I've got the code bolow.
First, define a KeyChainAliasCallback and call the KainChain.choosePrivateKeyAlias that display an activity to have the user authorization to access certificates store.

KeyChainAliasCallback keyChainAliasCallback = new KeyChainAliasCallback() {
    @Override
    public void alias(@Nullable String s) {
        Log.d(TAG, "selected alias = " + s);
        asyncTask.execute();
    }
};
KeyChain.choosePrivateKeyAlias(this, keyChainAliasCallback, null, null, null, -1, CERT_ALIAS);

Then, you're able to retrieve private key and certificates chains from the internal store (you have to use an async function)

AsyncTask<Void, Void, Boolean> asyncTask = new AsyncTask<Void, Void, Boolean>() {

    private Exception error;

    @Override
    protected Boolean doInBackground(Void... arg) {
        try {

            PrivateKey pk = KeyChain.getPrivateKey(mContext, CERT_ALIAS);
            X509Certificate[] chain = KeyChain.getCertificateChain(mContext, CERT_ALIAS);

            byte[] data = "foobar".getBytes("ASCII");
            Signature sig = Signature.getInstance("SHA1withRSA");
            sig.initSign(pk);
            sig.update(data);
            byte[] signed = sig.sign();

            PublicKey pubk = chain[0].getPublicKey();
            sig.initVerify(pubk);
            sig.update(data);
            boolean valid = sig.verify(signed);
            Log.d(TAG, "signature is valid: " + valid);

            if(valid) {
                mPrivateKey = pk;
                mCertificates = chain;
            }

            return valid;
        } catch (Exception e) {
            e.printStackTrace();
            error = e;

            return null;
        }
    }

    @Override
    protected void onPostExecute(Boolean valid) {
        if (error != null) {
            Toast.makeText(mContext, "Error: " + error.getMessage(),
                    Toast.LENGTH_LONG).show();

            return;
        } else {
            Toast.makeText(mContext, "Signature is valid: " + valid,
                    Toast.LENGTH_SHORT).show();
            mWebView.loadUrl("https://blablabla.com");
        }

    }
};

Then, you're able to give certificate with this function :

@Override
public void onReceivedClientCertRequest(WebView view, final ClientCertRequest request) {
    request.proceed(mPrivateKey, mCertificates);
}

Last thing I have to find is how to display the choosePrivateKeyAlias dialog just one time (the first).


问:
Why does git on Windows fail to recognise remote branches
I use git on Linux all the time without any issue. However I recently had to use git on Windows so I installed the command line client because that's how I work most happily.

My problem is that I tried to checkout a branch that I'd created on Linux using git checkout mybranchname but it didn't work. I had to specify git checkout -b mybranchname --track origin/mybranchname.

Since then, whenever I go to push I get told

```<code>fatal: The upstream branch of your current branch does not match
the name of your current branch.  To push to the upstream branch
on the remote, use

    git push origin HEAD:mybranchname

To push to the branch of the same name on the remote, use

    git push origin mybranchname

To choose either option permanently, see push.default in 'git help config'.
</code>```

Does anyone know why this happened or how to resolve it?

I'm using git version 2.12.0.windows.1 and 2.11.0 on Linux. My origin is GitHub Enterprise over SSH in both cases.

答:
The answer is that git for Windows had somehow added a unicode character to the branch name that cannot be displayed in the command prompt.

One of my branches was called mybranchname but for some unknown reason the remote branch was called \u0096mybranchname (I had not asked for that!)

Solution: Delete Windows and never again make the mistake of using that dreadful OS with it's awful small file IO and random ignoring of characters in command windows.

Body:
I use git on Linux all the time without any issue. However I recently had to use git on Windows so I installed the command line client because that's how I work most happily.

My problem is that I tried to checkout a branch that I'd created on Linux using git checkout mybranchname but it didn't work. I had to specify git checkout -b mybranchname --track origin/mybranchname.

Since then, whenever I go to push I get told

fatal: The upstream branch of your current branch does not match
the name of your current branch.  To push to the upstream branch
on the remote, use

    git push origin HEAD:mybranchname

To push to the branch of the same name on the remote, use

    git push origin mybranchname

To choose either option permanently, see push.default in 'git help config'.

Does anyone know why this happened or how to resolve it?

I'm using git version 2.12.0.windows.1 and 2.11.0 on Linux. My origin is GitHub Enterprise over SSH in both cases.


问:
Ext.Ajax.request vs model.save cross origin cookies
I'm having an issue with model.save not sending the cookies back with my cross origin request, but Ext.Ajax.request has no issue sending back the cookies.  In our local development at work, we override the beforerequest on all Ajax requests (which includes model actions) to set withCredentials = true and useDefaultXhrHeader = false, which helps with CORS on a normal Ext.Ajax.request.

From what I understand, having a proxy of type ajax is similar to doing Ext.Ajax.request, and that's apparent because model.save hits the beforerequest (you'll see this in the example below).  You'll also notice in the example that the model.save sends an OPTIONS call first, and then never follows up with the POST (but that's most likely because of the server)... either way, OPTIONS instead of POST seems a little fishy.

Here's the example:

```<code>Ext.Ajax.on({
    beforerequest: function (conn, options, eOpts) {
        console.log('here', conn, options)
        options.useDefaultXhrHeader = false;
        options.withCredentials = true;
    }
});
Ext.define('MyModel', {
    extend: 'Ext.data.Model',
    fields: ['test'],
    proxy: {
        type: 'ajax',
        url: 'https://docs.sencha.com'
    }
});
var model = Ext.create('MyModel');
// This will fire off an OPTIONS call and not send the cookies
model.save();
// This will fire off with the POST and send the cookies
Ext.Ajax.request({
    url: 'https://docs.sencha.com',
    method: 'POST'
});
</code>```

Is there any way to get model.save to send the cookies to the cross domain?

答:
Thanks to Mitchell Simoens over on the Sencha Forums, he helped me figure out the root cause of the issue, which is the proxy's writer.  I needed to create a custom writer in order to solve this issue.

Fiddle:

```<code>Ext.define('Ux.data.writer.Json', {
    extend : 'Ext.data.writer.Json',
    alias  : 'writer.ux-json',

    config : {
        /**
         * @cfg {Boolean} useJsonData
         * If {@link #allowSingle} is `true` and only one model is being
         * saved, this will control if the request will set the data using
         * `params` or `jsonData`.
         */
        useJsonData : false
    },

    writeRecords: function(request, data) {
        var me = this,
            root = me.getRootProperty(),
            transform = this.getTransform(),
            json, single;

        if (me.getExpandData()) {
            data = me.getExpandedData(data);
        }

        if (me.getAllowSingle() && data.length === 1) {
            // convert to single object format
            data = data[0];
            single = true;
        }

        if (transform) {
            data = transform(data, request);
        }

        if (me.getEncode()) {
            if (root) {
                // sending as a param, need to encode
                request.setParam(root, Ext.encode(data));
            } else {
                //<debug>
                Ext.raise('Must specify a root when using encode');
                //</debug>
            }
        } else if (single && !me.getUseJsonData()) {
            request.setParams(Ext.apply(request.getParams(), data));
        } else if (single || (data && data.length)) {
            // send as jsonData
            json = request.getJsonData() || {};

            if (root) {
                json[root] = data;
            } else {
                json = data;
            }

            request.setJsonData(json);
        }

        return request;
    }
});

Ext.Ajax.on({
    beforerequest: function (conn, options, eOpts) {
        console.log(options.url, options);

        options.useDefaultXhrHeader = false;
        options.withCredentials = true;
    }
});

Ext.define('MyModel', {
    extend: 'Ext.data.Model',
    fields: ['blah'],
    proxy: {
        type: 'ajax',
        url: 'https://docs.sencha.com',
        writer: {
            type: 'ux-json'
        }
    }
});

var model = Ext.create('MyModel', {
    blah : 2
});
model.save();

Ext.Ajax.request({
    url: 'https://docs.sencha.com',
    method: 'POST',
    params: {
        blah: 1
    }
});
</code>```

Body:
I'm having an issue with model.save not sending the cookies back with my cross origin request, but Ext.Ajax.request has no issue sending back the cookies.  In our local development at work, we override the beforerequest on all Ajax requests (which includes model actions) to set withCredentials = true and useDefaultXhrHeader = false, which helps with CORS on a normal Ext.Ajax.request.

From what I understand, having a proxy of type ajax is similar to doing Ext.Ajax.request, and that's apparent because model.save hits the beforerequest (you'll see this in the example below).  You'll also notice in the example that the model.save sends an OPTIONS call first, and then never follows up with the POST (but that's most likely because of the server)... either way, OPTIONS instead of POST seems a little fishy.

Here's the example:

Ext.Ajax.on({
    beforerequest: function (conn, options, eOpts) {
        console.log('here', conn, options)
        options.useDefaultXhrHeader = false;
        options.withCredentials = true;
    }
});
Ext.define('MyModel', {
    extend: 'Ext.data.Model',
    fields: ['test'],
    proxy: {
        type: 'ajax',
        url: 'https://docs.sencha.com'
    }
});
var model = Ext.create('MyModel');
// This will fire off an OPTIONS call and not send the cookies
model.save();
// This will fire off with the POST and send the cookies
Ext.Ajax.request({
    url: 'https://docs.sencha.com',
    method: 'POST'
});

Is there any way to get model.save to send the cookies to the cross domain?

Body:
Thanks to Mitchell Simoens over on the Sencha Forums, he helped me figure out the root cause of the issue, which is the proxy's writer.  I needed to create a custom writer in order to solve this issue.

Fiddle:

Ext.define('Ux.data.writer.Json', {
    extend : 'Ext.data.writer.Json',
    alias  : 'writer.ux-json',

    config : {
        /**
         * @cfg {Boolean} useJsonData
         * If {@link #allowSingle} is `true` and only one model is being
         * saved, this will control if the request will set the data using
         * `params` or `jsonData`.
         */
        useJsonData : false
    },

    writeRecords: function(request, data) {
        var me = this,
            root = me.getRootProperty(),
            transform = this.getTransform(),
            json, single;

        if (me.getExpandData()) {
            data = me.getExpandedData(data);
        }

        if (me.getAllowSingle() && data.length === 1) {
            // convert to single object format
            data = data[0];
            single = true;
        }

        if (transform) {
            data = transform(data, request);
        }

        if (me.getEncode()) {
            if (root) {
                // sending as a param, need to encode
                request.setParam(root, Ext.encode(data));
            } else {
                //<debug>
                Ext.raise('Must specify a root when using encode');
                //</debug>
            }
        } else if (single && !me.getUseJsonData()) {
            request.setParams(Ext.apply(request.getParams(), data));
        } else if (single || (data && data.length)) {
            // send as jsonData
            json = request.getJsonData() || {};

            if (root) {
                json[root] = data;
            } else {
                json = data;
            }

            request.setJsonData(json);
        }

        return request;
    }
});

Ext.Ajax.on({
    beforerequest: function (conn, options, eOpts) {
        console.log(options.url, options);

        options.useDefaultXhrHeader = false;
        options.withCredentials = true;
    }
});

Ext.define('MyModel', {
    extend: 'Ext.data.Model',
    fields: ['blah'],
    proxy: {
        type: 'ajax',
        url: 'https://docs.sencha.com',
        writer: {
            type: 'ux-json'
        }
    }
});

var model = Ext.create('MyModel', {
    blah : 2
});
model.save();

Ext.Ajax.request({
    url: 'https://docs.sencha.com',
    method: 'POST',
    params: {
        blah: 1
    }
});