问:
VBA Error Handling Not working
I am writing a vba program to refresh power queries for a number of reports based on a user saying which reports to refresh via a form with checkboxes.

This part of the code refreshes the power query and I want it to capture the error if the refresh isn't successful. It will update a control table "Not Updated" if it wasn't updated and then I want it to resume next.

For some reason the "On Error Goto Error" isn't triggering the error line. It is still throwing the error and stopping the code run.

Any help would be greatly appreciated!

```<code>For Each cell In
wsConfig.ListObjects("tblReportstoRun").ListColumns(2).DataBodyRange
    If cell.Value = True Then
        cell.Offset(, 1).Value = Now()
        cell.Offset(, 2).Value = frmSetting.tbStartDate
        cell.Offset(, 3).Value = frmSetting.tbEnddate

        strCurrWS = cell.Offset(0, -1)
        ThisWorkbook.Sheets(strCurrWS).Activate
        Application.StatusBar = "Updating tab " & strCurrWS

            For Each qt In ThisWorkbook.Sheets(strCurrWS).QueryTables
                qt.Refresh BackgroundQuery:=False
            Next qt

            For Each lo In ThisWorkbook.Sheets(strCurrWS).ListObjects
                On Error GoTo Error
                lo.QueryTable.Refresh BackgroundQuery:=False
            Next lo
    Else
 Error:
    cell.Offset(, 4).Value = "Not Updated"
    If InStr(Err.Description, "Permission Error") Then
    cell.Offset(, 6).Value = "Permission Error. Check Credentials"
    Err.Clear
    End If

    End If
Next cell

Set qt = Nothing
Set wks = Nothing
</code>```

答:
You should have your Errorhandler as the end of your code, and the handler should never be named "Error"

Try...

```<code>For Each cell In
wsConfig.ListObjects("tblReportstoRun").ListColumns(2).DataBodyRange
    If cell.Value = True Then
        cell.Offset(, 1).Value = Now()
        cell.Offset(, 2).Value = frmSetting.tbStartDate
        cell.Offset(, 3).Value = frmSetting.tbEnddate

        strCurrWS = cell.Offset(0, -1)
        ThisWorkbook.Sheets(strCurrWS).Activate
        Application.StatusBar = "Updating tab " & strCurrWS

            For Each qt In ThisWorkbook.Sheets(strCurrWS).QueryTables
                qt.Refresh BackgroundQuery:=False
            Next qt

            For Each lo In ThisWorkbook.Sheets(strCurrWS).ListObjects
                On Error GoTo Errorhandle
                lo.QueryTable.Refresh BackgroundQuery:=False
            Next lo
Next cell

Set qt = Nothing
Set wks = Nothing

Exit Sub

Errorhandle:
    cell.Offset(, 4).Value = "Not Updated"
    If InStr(Err.Description, "Permission Error") Then
        cell.Offset(, 6).Value = "Permission Error. Check Credentials"
        Err.Clear
    End If
</code>```

Title: VBA Error Handling Not working

Body:
I am writing a vba program to refresh power queries for a number of reports based on a user saying which reports to refresh via a form with checkboxes.

This part of the code refreshes the power query and I want it to capture the error if the refresh isn't successful. It will update a control table "Not Updated" if it wasn't updated and then I want it to resume next.

For some reason the "On Error Goto Error" isn't triggering the error line. It is still throwing the error and stopping the code run.

Any help would be greatly appreciated!

For Each cell In
wsConfig.ListObjects("tblReportstoRun").ListColumns(2).DataBodyRange
    If cell.Value = True Then
        cell.Offset(, 1).Value = Now()
        cell.Offset(, 2).Value = frmSetting.tbStartDate
        cell.Offset(, 3).Value = frmSetting.tbEnddate

        strCurrWS = cell.Offset(0, -1)
        ThisWorkbook.Sheets(strCurrWS).Activate
        Application.StatusBar = "Updating tab " & strCurrWS

            For Each qt In ThisWorkbook.Sheets(strCurrWS).QueryTables
                qt.Refresh BackgroundQuery:=False
            Next qt

            For Each lo In ThisWorkbook.Sheets(strCurrWS).ListObjects
                On Error GoTo Error
                lo.QueryTable.Refresh BackgroundQuery:=False
            Next lo
    Else
 Error:
    cell.Offset(, 4).Value = "Not Updated"
    If InStr(Err.Description, "Permission Error") Then
    cell.Offset(, 6).Value = "Permission Error. Check Credentials"
    Err.Clear
    End If

    End If
Next cell

Set qt = Nothing
Set wks = Nothing

Body:
You should have your Errorhandler as the end of your code, and the handler should never be named "Error"

Try...

For Each cell In
wsConfig.ListObjects("tblReportstoRun").ListColumns(2).DataBodyRange
    If cell.Value = True Then
        cell.Offset(, 1).Value = Now()
        cell.Offset(, 2).Value = frmSetting.tbStartDate
        cell.Offset(, 3).Value = frmSetting.tbEnddate

        strCurrWS = cell.Offset(0, -1)
        ThisWorkbook.Sheets(strCurrWS).Activate
        Application.StatusBar = "Updating tab " & strCurrWS

            For Each qt In ThisWorkbook.Sheets(strCurrWS).QueryTables
                qt.Refresh BackgroundQuery:=False
            Next qt

            For Each lo In ThisWorkbook.Sheets(strCurrWS).ListObjects
                On Error GoTo Errorhandle
                lo.QueryTable.Refresh BackgroundQuery:=False
            Next lo
Next cell

Set qt = Nothing
Set wks = Nothing

Exit Sub

Errorhandle:
    cell.Offset(, 4).Value = "Not Updated"
    If InStr(Err.Description, "Permission Error") Then
        cell.Offset(, 6).Value = "Permission Error. Check Credentials"
        Err.Clear
    End If


来源: stackexchange

问:
Disable our add-in in unsupported versions of Office
Is it possible to disable our add-in in unsupported versions/build of Office. So users are not able to search for the add-in in the Store listing in unsupported versions. </p>

答: You can accomplish that with the Requirements element in the add-in's manifest. See this article for details: Specify Office hosts and API requirements.

ContentLicense: CC BY-SA 3.0


问:
Eliminate style loading using media queries
I try to speed up initial loading by eliminating unnecessary downloading.
I split styles in to portrait and landscape css.
And want to load only one style based on media queries.
But is seems they are loading together.

  <link rel="stylesheet" type="text/css" href="style-p.css" media="(orientation: portrait)" />
  <link rel="stylesheet" type="text/css" href="style-l.css" media="(orientation: landscape)" />
```

答:
something like this could work

```<code><link rel="stylesheet" media="screen and (min-device-width: 800px)" href="800.css" />
<link rel='stylesheet' media='screen and (min-width: 701px) and (max-width: 900px)' href='css/medium.css' />
</code>```

try using this solution:

https://stackoverflow.com/a/8101452/1964336

https://stackoverflow.com/a/19675410/1964336

https://css-tricks.com/resolution-specific-stylesheets/

more explanation:
CSS syntax: link: https://www.w3.org/TR/css3-mediaqueries/

```<code><link rel="stylesheet" media="mediatype and|not|only (media feature)" href="mystylesheet.css">
</code>```

media type could be print, screen, all etc.

Body:
something like this could work

<link rel="stylesheet" media="screen and (min-device-width: 800px)" href="800.css" />
<link rel='stylesheet' media='screen and (min-width: 701px) and (max-width: 900px)' href='css/medium.css' />

try using this solution:

https://stackoverflow.com/a/8101452/1964336

https://stackoverflow.com/a/19675410/1964336

https://css-tricks.com/resolution-specific-stylesheets/

more explanation:
CSS syntax: link: https://www.w3.org/TR/css3-mediaqueries/

<link rel="stylesheet" media="mediatype and|not|only (media feature)" href="mystylesheet.css">

media type could be print, screen, all etc.


问:
Bubble sorting in dynamic array of objects in C++
I have class City with following private data: name of city, width,length and height of the city. I have to make dynamic array, which is inserted by constructor by default- City(),when the programs starts.Then the program uses method output() and prints inserted array of cities.

I should use bubble sort to sort the cities by their length. And when this is done, the program should show the sorted cities in increasing lengths.

The problem is that my data are in private(in public everything works excellent but principle of capsulation is violated!) so I can't do bubble sort.

I tried to do another dynamic array of type double double Lengths[n], which content is lengths of first array. Then I do sorting, but program prints only sorted lengths and this is not my goal.

I should print the names of cities sorted by their lengths.

Code:

```<code>class City{
private: char *name;
         double width;
         double length;
         double height;
public:void Output();
    City();
    ~City();
    double GetLength()
    {
        return length;
    }
    double GetWidth(){ return width; }
    double GetHeight(){ return height; }
    char GetName(){ return *name; }

};
City::City()
{
    char ime[20];
    cout << "Name= ";
    cin >> ime;
    name = new char[strlen(ime) + 1];
    for (int i = 0; i <=strlen(ime); i++)
        name[i] = ime[i];

    cout << "Width= ";
    cin >> width;
    cout << "Length= ";
    cin >> length;
    cout << "Height= ";
    cin >> height;
}
void City::Output()
{
    cout << "Name is: " << name << endl;
    cout << " Width is: " << width <<" deg"<< endl;;
    cout << " Length is: " << length << " deg"<<endl;
    cout << " Height is: " << height <<" m"<<endl;
    return;
}
City::~City()
{
    cout << " " << endl;
cout << "Destructor of City!" << endl;
delete[] name;
}

int main()
{
    //City town;

    //town.Input();
    //town.Output();
    int n;
    City *mA;
    cout << "Input number of cities: " << endl;
    cin >> n;
    mA = new City[n];
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }
    cout << "Cities from west to east, sorted by their length" << endl;
    double *Lengths = new double[n];
    for (int j = 0; j < n; j++)
    {
        Lengths[j] = mA[j].GetLength();

    }
int k = 0;//counter
    double max = Lengths[0];
    for (int j = 1; j < n; j++)
    {
        if (Lengths[j - 1] >Lengths[j])
        {
            max = Lengths[j - 1];
            Lengths[j - 1] = Lengths[j];
            Lengths[j] = max;
        }
    }

    for (int j = 0; j < n; j++)//cycle for output
    {
        mA[j].Output();
    }

    delete[]mA;
    return 0;

}
</code>```

答:
I don't see a direct question but I can assume majority of the question by your story. You have multiple options on how to solve this case. One of the simple ways to solve this is create a function within the object that allows you to get the length of a member of an object for example in your case it would be name of city.

Create a method inside the object that you can call to return a private method's length. Create a loop that calls this method and checks each element side by side until you can't refine it any longer. Is there a specific reason your using char instead of string for name?

Body:
I have class City with following private data: name of city, width,length and height of the city. I have to make dynamic array, which is inserted by constructor by default- City(),when the programs starts.Then the program uses method output() and prints inserted array of cities.

I should use bubble sort to sort the cities by their length. And when this is done, the program should show the sorted cities in increasing lengths.

The problem is that my data are in private(in public everything works excellent but principle of capsulation is violated!) so I can't do bubble sort.

I tried to do another dynamic array of type double double Lengths[n], which content is lengths of first array. Then I do sorting, but program prints only sorted lengths and this is not my goal.

I should print the names of cities sorted by their lengths.

Code:

class City{
private: char *name;
         double width;
         double length;
         double height;
public:void Output();
    City();
    ~City();
    double GetLength()
    {
        return length;
    }
    double GetWidth(){ return width; }
    double GetHeight(){ return height; }
    char GetName(){ return *name; }

};
City::City()
{
    char ime[20];
    cout << "Name= ";
    cin >> ime;
    name = new char[strlen(ime) + 1];
    for (int i = 0; i <=strlen(ime); i++)
        name[i] = ime[i];

    cout << "Width= ";
    cin >> width;
    cout << "Length= ";
    cin >> length;
    cout << "Height= ";
    cin >> height;
}
void City::Output()
{
    cout << "Name is: " << name << endl;
    cout << " Width is: " << width <<" deg"<< endl;;
    cout << " Length is: " << length << " deg"<<endl;
    cout << " Height is: " << height <<" m"<<endl;
    return;
}
City::~City()
{
    cout << " " << endl;
cout << "Destructor of City!" << endl;
delete[] name;
}

int main()
{
    //City town;

    //town.Input();
    //town.Output();
    int n;
    City *mA;
    cout << "Input number of cities: " << endl;
    cin >> n;
    mA = new City[n];
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }
    cout << "Cities from west to east, sorted by their length" << endl;
    double *Lengths = new double[n];
    for (int j = 0; j < n; j++)
    {
        Lengths[j] = mA[j].GetLength();

    }
int k = 0;//counter
    double max = Lengths[0];
    for (int j = 1; j < n; j++)
    {
        if (Lengths[j - 1] >Lengths[j])
        {
            max = Lengths[j - 1];
            Lengths[j - 1] = Lengths[j];
            Lengths[j] = max;
        }
    }

    for (int j = 0; j < n; j++)//cycle for output
    {
        mA[j].Output();
    }

    delete[]mA;
    return 0;

}


问:
Why there is a difference between sp_helpfile vs sys.master_files?
Hi while restoring database using restore command in sql server to specific drive, after executing sp_helpfile its showing incorrect file path, however sys.master_files showing right file path ?
why sp_helpfile showing inaccurate path? can somebody please help me to understand this?

答:
Too long to comment.

I suspect you aren't connected to the correct database when you run sp_helpfile. If you query sys.master_files it will return the same thing regardless of what database you are connected to. However, sp_helpfile used the default connection if you don't specify a file name. Thus, if you are connected to [master] it will return results for the files of this database.


问:
Bracket notation property accessor for arrays
In Typescript (and Javascript for that matter), you can access an object's properties using the dot notation or the bracket notation:

```<code>object.property
object['property']
</code>```

Using a concrete example for the latter:

```<code>const user = {
    firstName: 'John',
    lastName: 'Doe'
}
const prop = 'firstName';
console.log(user[prop]);  //"John"
</code>```

My question is if/how bracket notation can be used for array properties where the value in the bracket is a path to an array.  Here is an example:

```<code>const user = {
    firstName: 'John',
    lastName: 'Doe',
    nicknames: [
        { id: 1, value: 'Johnny'},
        { id: 2, value: 'JD'},
        { id: 3, value: 'Dude'}
    ]
}
const prop = 'nicknames[2].value';
console.log(user[prop]);
</code>```

My goal with the console.log() would be to print JD, but this example would fail because there is, of course, no property of user called nicknames[2].value;

How can I use bracket notation in this manner with array properties?

答:
Based on @JanS's suggestion, I was able to accomplish what I needed with the following use of lodash's get() method:

```<code>const prop = 'nicknames[2].value';
console.log(_.get(user, prop));
</code>```

Body:
In Typescript (and Javascript for that matter), you can access an object's properties using the dot notation or the bracket notation:

object.property
object['property']

Using a concrete example for the latter:

const user = {
    firstName: 'John',
    lastName: 'Doe'
}
const prop = 'firstName';
console.log(user[prop]);  //"John"

My question is if/how bracket notation can be used for array properties where the value in the bracket is a path to an array.  Here is an example:

const user = {
    firstName: 'John',
    lastName: 'Doe',
    nicknames: [
        { id: 1, value: 'Johnny'},
        { id: 2, value: 'JD'},
        { id: 3, value: 'Dude'}
    ]
}
const prop = 'nicknames[2].value';
console.log(user[prop]);

My goal with the console.log() would be to print JD, but this example would fail because there is, of course, no property of user called nicknames[2].value;

How can I use bracket notation in this manner with array properties?

Body:
Based on @JanS's suggestion, I was able to accomplish what I needed with the following use of lodash's get() method:

const prop = 'nicknames[2].value';
console.log(_.get(user, prop));


问:
Align TextView on left and center
How do I exactly achieve this? I tried messing around with android:layout_gravity center|left and android:gravity center|left and none seems to work. Does it make any difference that I am using a spannable string?

Here is what I have right now and what I want to achive. I want my Text to align to the red line

Thanks in advance.

My Layout.. It is the TextView with the ID status

```<code><android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <!-- Main layout -->

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <FrameLayout
        android:id="@+id/main_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f2f2f2">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_horizontal"

                >

                <android.support.v4.widget.SwipeRefreshLayout
                    android:id="@+id/swiperefresh"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"

                    >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center"
                        android:orientation="vertical"><![CDATA[
                        >

                        ]]>

                        <include
                            layout="@layout/actionbarmenu"
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:layout_weight="0.64" />

                        <TextView
                            android:id="@+id/textView3"
                            android:layout_width="match_parent"
                            android:layout_height="30dp"
                            android:layout_marginLeft="5dp"
                            android:background="#FAFAFA"
                            android:gravity="center|left"
                            android:text="Notfallübersicht"
                            android:textColor="#c9c9c9"
                            android:textSize="18sp" />

                        <EditText
                            android:id="@+id/Notfall"
                            android:layout_width="match_parent"
                            android:layout_height="70dp"
                            android:layout_weight="0.36"
                            android:background="@drawable/round_grey"
                            android:ellipsize="end"
                            android:gravity="center"
                            android:hint="Notfall-Code Eingabe"
                            android:inputType="text"
                            android:paddingLeft="6dp"
                            android:singleLine="true"
                            android:textAllCaps="false"
                            android:textColor="#585858"
                            android:textColorHint="#c9c9c9"
                            android:textCursorDrawable="@drawable/black_cursor" />

                        <TextView
                            android:id="@+id/textView7"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.70" />

                        <TextView
                            android:id="@+id/status"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="3.63"
                            android:gravity="center"
                            android:textColor="#6f7070"
                            android:textSize="20sp"
                            android:visibility="visible" />

                        <TextView
                            android:id="@+id/abgemeldet"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="10.08"
                            android:text="Bitte melde dich mit deinen Pengueen Log-In Daten an, um die App zu aktivieren.  "
                            android:textSize="24sp" />

                        <TextView
                            android:id="@+id/user"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:layout_weight="0.60"
                            android:text="Angemeldet als :"
                            android:textSize="14sp"
                            android:visibility="invisible" />

                        <TextView
                            android:id="@+id/angemeldet"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:layout_weight="1.09"
                            android:text="Letzte Abfrage vor  1 Minute"
                            android:textSize="14sp"
                            android:textStyle="bold"
                            android:visibility="invisible" />

                        <Button
                            android:id="@+id/button"
                            style="@style/Widget.AppCompat.Button"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:background="#4697c4"
                            android:text="Anmleden"
                            android:textColor="#ffffff"
                            android:visibility="gone" />

                        <RelativeLayout
                            android:layout_width="match_parent"
                            android:layout_height="50dp"
                            android:layout_weight="0.74">

                            <!-- This could be your fragment container, or something -->
                            <FrameLayout
                                android:id="@+id/contentContainer"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_above="@+id/bottomBar" />

                            <com.roughike.bottombar.BottomBar
                                android:id="@+id/bottomBar"
                                android:layout_width="match_parent"
                                android:layout_height="60dp"
                                android:layout_alignParentBottom="true"
                                android:layout_gravity="bottom"
                                app2:bb_activeTabAlpha="1"
                                app2:bb_activeTabColor="#ffffff"
                                app2:bb_inActiveTabAlpha="0.6"
                                app2:bb_inActiveTabColor="#ffffff"
                                app2:bb_tabXmlResource="@xml/bottombar_tabs" />

                        </RelativeLayout>

                    </LinearLayout>
                </android.support.v4.widget.SwipeRefreshLayout>
            </LinearLayout>

    </FrameLayout>

    <!-- The navigation drawer -->

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#51aadd"
        android:choiceMode="singleChoice"
        android:divider="@drawable/list_divider"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="true"
        android:scrollbars="none" />

</android.support.v4.widget.DrawerLayout>
</code>```

答:
android:gravity sets the gravity of the contents  of the View .

android:layout_gravity sets the gravity of the View relative to its parent.

you can see Difference between gravity and layout_gravity on Android

android:gravity of TextView default value is left ,it is what you want , you just need the change the layout_gravity。

when set TextView android:layout_gravity="center_horizontal", you should set android:layout_width="wrap_content", not 'match_parent'。

```<code>android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
</code>```

Title: Align TextView on left and center

Body:
How do I exactly achieve this? I tried messing around with android:layout_gravity center|left and android:gravity center|left and none seems to work. Does it make any difference that I am using a spannable string?

Here is what I have right now and what I want to achive. I want my Text to align to the red line

Thanks in advance.

My Layout.. It is the TextView with the ID status

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <FrameLayout
        android:id="@+id/main_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f2f2f2">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_horizontal"

                >

                <android.support.v4.widget.SwipeRefreshLayout
                    android:id="@+id/swiperefresh"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"

                    >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center"
                        android:orientation="vertical"><![CDATA[
                        >

                        ]]>

                        <include
                            layout="@layout/actionbarmenu"
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:layout_weight="0.64" />

                        <TextView
                            android:id="@+id/textView3"
                            android:layout_width="match_parent"
                            android:layout_height="30dp"
                            android:layout_marginLeft="5dp"
                            android:background="#FAFAFA"
                            android:gravity="center|left"
                            android:text="Notfallübersicht"
                            android:textColor="#c9c9c9"
                            android:textSize="18sp" />

                        <EditText
                            android:id="@+id/Notfall"
                            android:layout_width="match_parent"
                            android:layout_height="70dp"
                            android:layout_weight="0.36"
                            android:background="@drawable/round_grey"
                            android:ellipsize="end"
                            android:gravity="center"
                            android:hint="Notfall-Code Eingabe"
                            android:inputType="text"
                            android:paddingLeft="6dp"
                            android:singleLine="true"
                            android:textAllCaps="false"
                            android:textColor="#585858"
                            android:textColorHint="#c9c9c9"
                            android:textCursorDrawable="@drawable/black_cursor" />

                        <TextView
                            android:id="@+id/textView7"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.70" />

                        <TextView
                            android:id="@+id/status"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="3.63"
                            android:gravity="center"
                            android:textColor="#6f7070"
                            android:textSize="20sp"
                            android:visibility="visible" />

                        <TextView
                            android:id="@+id/abgemeldet"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="10.08"
                            android:text="Bitte melde dich mit deinen Pengueen Log-In Daten an, um die App zu aktivieren.  "
                            android:textSize="24sp" />

                        <TextView
                            android:id="@+id/user"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:layout_weight="0.60"
                            android:text="Angemeldet als :"
                            android:textSize="14sp"
                            android:visibility="invisible" />

                        <TextView
                            android:id="@+id/angemeldet"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="5dp"
                            android:layout_weight="1.09"
                            android:text="Letzte Abfrage vor  1 Minute"
                            android:textSize="14sp"
                            android:textStyle="bold"
                            android:visibility="invisible" />

                        <Button
                            android:id="@+id/button"
                            style="@style/Widget.AppCompat.Button"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:background="#4697c4"
                            android:text="Anmleden"
                            android:textColor="#ffffff"
                            android:visibility="gone" />

                        <RelativeLayout
                            android:layout_width="match_parent"
                            android:layout_height="50dp"
                            android:layout_weight="0.74">

                            <FrameLayout
                                android:id="@+id/contentContainer"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_above="@+id/bottomBar" />

                            <com.roughike.bottombar.BottomBar
                                android:id="@+id/bottomBar"
                                android:layout_width="match_parent"
                                android:layout_height="60dp"
                                android:layout_alignParentBottom="true"
                                android:layout_gravity="bottom"
                                app2:bb_activeTabAlpha="1"
                                app2:bb_activeTabColor="#ffffff"
                                app2:bb_inActiveTabAlpha="0.6"
                                app2:bb_inActiveTabColor="#ffffff"
                                app2:bb_tabXmlResource="@xml/bottombar_tabs" />

                        </RelativeLayout>

                    </LinearLayout>
                </android.support.v4.widget.SwipeRefreshLayout>
            </LinearLayout>

    </FrameLayout>

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#51aadd"
        android:choiceMode="singleChoice"
        android:divider="@drawable/list_divider"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="true"
        android:scrollbars="none" />

</android.support.v4.widget.DrawerLayout>

Body:
android:gravity sets the gravity of the contents  of the View .

android:layout_gravity sets the gravity of the View relative to its parent.

you can see Difference between gravity and layout_gravity on Android

android:gravity of TextView default value is left ,it is what you want , you just need the change the layout_gravity。

when set TextView android:layout_gravity="center_horizontal", you should set android:layout_width="wrap_content", not 'match_parent'。

android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"


问:
Application of DirectoryIndex to an Alias in Apache
How does one apply DirectoryIndex to an Alias in Apache without resulting in error 403?

This results in response header 200:

http://localhost/  Which presents
  http://localhost/index.html

```<code><VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    DirectoryIndex index.html index.php index.xhtml index.htm default.htm
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>
</code>```

This results in error 403, forbidden:

http://localhost/aliasName/wwwrootDevelopmentSubDirectory/

```<code><VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    DirectoryIndex index.html index.php index.xhtml index.htm default.htm
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

    Alias /aliasName/ "/home/user/Dropbox/Level1/Level2/wwwrootDevelopment/"
    <Directory /home/user/Dropbox/Level1/Level2/wwwrootDevelopment>
            DirectoryIndex index.html index.php index.xhtml index.htm default.htm
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            Allow from all
    </Directory>
</code>```

error.log reveals same message seen in the browser.

```<code>[Tue Apr 02 00:19:30 2013] [error] [client 172.x.x.x] (13)Permission denied: access to /aliasName/wwwrootDevelopmentSubDirectory/ denied, referer: http://localhost/
</code>```

答:
DirectoryIndex to an Alias  should be in pirticular directive  for that alias in apache2</p>

```<code>Alias /pma "/var/www/pma"
<Directory "/var/www/pma">
    DirectoryIndex adminer.php
     Options Indexes FollowSymLinks
     AllowOverride All
     Require all granted
</Directory>
</code>```

Body:
How does one apply DirectoryIndex to an Alias in Apache without resulting in error 403?

This results in response header 200:

http://localhost/  Which presents
  http://localhost/index.html

<VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    DirectoryIndex index.html index.php index.xhtml index.htm default.htm
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

This results in error 403, forbidden:

http://localhost/aliasName/wwwrootDevelopmentSubDirectory/

<VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    DirectoryIndex index.html index.php index.xhtml index.htm default.htm
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

    Alias /aliasName/ "/home/user/Dropbox/Level1/Level2/wwwrootDevelopment/"
    <Directory /home/user/Dropbox/Level1/Level2/wwwrootDevelopment>
            DirectoryIndex index.html index.php index.xhtml index.htm default.htm
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            Allow from all
    </Directory>

error.log reveals same message seen in the browser.

[Tue Apr 02 00:19:30 2013] [error] [client 172.x.x.x] (13)Permission denied: access to /aliasName/wwwrootDevelopmentSubDirectory/ denied, referer: http://localhost/

Body:
DirectoryIndex to an Alias  should be in pirticular directive  for that alias in apache2

Alias /pma "/var/www/pma"
<Directory "/var/www/pma">
    DirectoryIndex adminer.php
     Options Indexes FollowSymLinks
     AllowOverride All
     Require all granted
</Directory>


问:
How to create 3 columns in the drop-down list using jQuery UI selectMenu widget?
I was given a task for creating a drop-down list consisting of 3 columns (in each row) as shown in the below image.

Now, I realized that the Selectmenu widget of the jQuery UI will fulfill my requirement and therefore, I used the following code (as given on their official documentation page).

```<code><!doctype html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>selectmenu demo</title>

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">

<style>

label { display: block; }

select { width: 200px; }

.overflow { height: 200px; }

</style>

<script src="//code.jquery.com/jquery-1.12.4.js"></script>

<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>

<body>

<label for="number">Select a number:</label>

<select name="number" id="number">

<option value="1">1</option>

<option value="2" selected>2</option>

<option value="3">3</option>

<option value="4">4</option>

<option value="5">5</option>

<option value="6">6</option>

<option value="7">7</option>

<option value="8">8</option>

<option value="9">9</option>

<option value="10">10</option>

<option value="11">11</option>

<option value="12">12</option>

<option value="13">13</option>

<option value="14">14</option>

<option value="15">15</option>

<option value="16">16</option>

<option value="17">17</option>

<option value="18">18</option>

<option value="19">19</option>

</select>

<script>

$( "#number" )

.selectmenu()

.selectmenu( "menuWidget" )

.addClass( "overflow" );

</script>

</body>

</html>
</code>```

The problem was that I was looking to create 3 columns instead of the 1 default column. So, I tried two options for aligning the text content inside the option tag.

Putting the text inside the span tag.

Putting the text inside a table made of one row and three columns (cells).

Given below is the code which I tried.

```<code><option value="1">
        <span align="left">Apple</span>
        <span align="center">Mango</span>
        <span align="right">Orange</span>
        </option>
      <option value="2" selected>
      <table>
        <tr>
          <td align="left">1</td>
          <td align="center">2</td>
          <td align="right">3</td>
        </tr>
        </table>
      </option>
</code>```

But this didn't fix my problem as I was getting the Output as shown in the below image.

Since I'm a beginner in HTML, CSS, and jQuery, therefore, I have no idea of what to do next for creating a drop-down list containing 3 columns in each row. Please note that I'll select the whole row consisting of all the 3 columns (as shown in the below image) and not any cell of any particular column.Can anyone kindly suggest what can be done to fix this problem and create the dropdown list as shown in the first image?

答:
Firstly, we will want to create a proper HTML Structure. There is an element of select you will want to learn about: <optgroup>. Here is a basic suggested structure.

Select an Option:
<select id="options">
  <optgroup label="PREFERRED OPTIONS">
    <option value="L">Standard Screw Adjustment</option>
  </optgroup>
  <optgroup label="STANDARD OPTIONS">
    <option value="C">Tamper Resistant - Factory Set</option>
    <option value="K">Handknob</option>
  </optgroup>
  <optgroup label="ADDITIONAL OPTIONS">
    <option value="F">Hex Head Screw with Locknut</option>
  </optgroup>
</select>```
</div>
</div>
</p>
<p>This is just the start. You can use <code>$("#options").selectmenu();</code> and you get a lot closer to what you want. We still need to add more elements and incorporate the extra data.</p>
<blockquote>
<p>The selectmenu widget is built with the widget factory and can be extended. When extending widgets, you have the ability to override or add to the behavior of existing methods.</p>
</blockquote>
<p>This is exactly what we will do, taking an example from <code>.autocomplete()</code>. See this example here: http://jqueryui.com/autocomplete/#categories</p>
<p>We will perform the same type of override within <code>.selectmenu()</code>. The widget factory and it's code can be a bit advanced and a bit hard to understand sometimes, so you'll have to dig through this more on your own.</p>
<p><strong>HTML</strong></p>
```Select an Option:
<select id="options">
  <optgroup label="PREFERRED OPTIONS">
    <option data-short="L" data-price="$0.00" value="L">Standard Screw Adjustment</option>
  </optgroup>
  <optgroup label="STANDARD OPTIONS">
    <option data-short="C" data-price="$5.00" value="C">Tamper Resistant - Factory Set</option>
    <option data-short="K" data-price="$6.00" value="K">Handknob</option>
  </optgroup>
  <optgroup label="ADDITIONAL OPTIONS">
    <option data-short="F" data-price="-$4.00" value="F">Hex Head Screw with Locknut</option>
  </optgroup>
</select>
```
<p>What you see above is sort of extended from what we built first. I have added <code>data</code> attributes. They do not mean much to our HTML yet they can be useful for our jQuery. the benefit here is that if we encounter a browser that does not support JavaScript (and hence cannot load the jQuery library), the code will fall back to basic HTML Markup and still be a similar experience for the user.</p>
<p><strong>CSS</strong></p>
```.ui-selectmenu-category {
  color: #5F5F5F;
  padding: .5em .25em;
}
.ui-menu-item {
}
.ui-menu-item .ui-menu-item-wrapper {
  display: inline-block;
  padding: 1em 2px;
}

.ui-menu-item .ui-menu-item-wrapper.ui-state-active {
  border-width: 1px 0 1px 0;
  border-color: #CCCCCC;
  background-color: #E4EBF1;
  color: #000;
}

.ui-menu-item .ui-menu-item-wrapper.ui-state-active.short {
  color: #2E6D99;
}

.ui-menu-item div.ui-menu-item-wrapper {
  width: 295px;
}

.ui-menu-item .short {
  color: #2E6D99;
  font-weight: strong;
  width: 30px;
  padding-left: .5em;
}

.ui-menu-item .price {
  font-weight: strong;
  width: 75px;
  margin-right: -6px;
}
```
<p>We're going to override and extend a number of theme elements for the <code>.selectmenu()</code>. this is all just to help make it fit the look and feel desired.</p>
<p><strong>JavaScript</strong></p>
```$(function() {
  $.widget("custom.mySelectMenu", $.ui.selectmenu, {
    _renderMenu: function(ul, items) {
      var that = this,
        currentCategory = "";
      $.each(items, function(index, item) {
        var li, name, short, price;
        if (item.optgroup != currentCategory) {
          ul.append("
" + item.optgroup + "
");
          currentCategory = item.optgroup;
        }
        li = that._renderItemData(ul, item);
        console.log(ul);
        name = li.text();
        short = item.element.data("short");
        price = item.element.data("price");
        console.log(li, short, price);
        li.prepend($("", {
          class: "short"
        }).html(short));
        li.append($("", {
          class: "price"
        }).html(price));
        if (item.optgroup) {
          li.attr("aria-label", item.optgroup + " : " + item.label);
        }
      });
    }
  });
  $("#options").mySelectMenu({
    width: 400
  });
});
```
<p><strong>Working Example:</strong> https://jsfiddle.net/Twisty/sn1z5vzn/7/</p>
<p>Here is where we're taking the <code>$.ui.selectmenu</code> and extending it to our own use. You can see we're only writing a function for the <code>_renderMenu</code> extension point. Everything else about the selectmenu will be carried through untouched.</p>
<p>This is important since we'll need to define a <code>width</code> option. We need to know the width so that we can create proper columns, essentially.</p>
<p>This will go through each of the <code>items</code> and create <code>li</code> elements to be used with the <code>ul</code> that is created by selectmenu. The resulting items will look like:</p>
```

  L

Standard Screw Adjustment

  $0.00

```
<p>jQuery UI does a lot of extra work for us, assigning unique IDs and applying hover classes, etc. Our additions allow us to style and theme different parts of each item.</p>
<p>The category items don't want to play well. So far, I found if I try to add any HTML element into it's <code>li</code>, it cannot render the rest of the menu properly. I may go back and see if <code>_renderItem</code> will help here.</p>
<p>Easy, right!? Comment if you have questions.</p>
<p><strong>References</strong></p>
<ul>
<li>Selectmenu Widget</li>
<li>Autocomplete Category Demo</li>
<li>HTML <optgroup> Tag</li>
<li>.data()</li>
</ul>
<hr />
<p><strong>Update</strong></p>
<p>If you change your Option like so:</p>
```<option data-icon-url="https://www.gravatar.com/avatar/b3e04a46e85ad3e165d66f5d927eb609?d=monsterid&r=g&s=16" data-price="$0.00" value="L">Standard Screw Adjustment</option>
```
<p>You can then update the <code><span></code> to use this as it's background.</p>
<p><strong>CSS Snippet</strong></p>
```.ui-menu-item .icon {
  background-repeat: no-repeat;
  background-size: 30px;
  background-position: center center;
  color: #2E6D99;
  font-weight: strong;
  width: 30px;
  padding-left: .5em;
}
```
<p><strong>JavaScript Snippet</strong></p>
```    li.prepend($("", {
      class: "icon",
      style: "background-image: url('" + iconUrl + "')"
    }).html(" "));
```

The   renders a Non-breaking Space character.

A common character entity used in HTML is the non-breaking space:

A non-breaking space is a space that will not break into a new line.

Two words separated by a non-breaking space will stick together (not break into a new line). This is handy when breaking the words might be disruptive.

HTML Entities

Working Example: https://jsfiddle.net/Twisty/sn1z5vzn/12/

Body:
I was given a task for creating a drop-down list consisting of 3 columns (in each row) as shown in the below image.

Now, I realized that the Selectmenu widget of the jQuery UI will fulfill my requirement and therefore, I used the following code (as given on their official documentation page).

<!doctype html>

<meta charset="utf-8">

<title>selectmenu demo</title>

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">

Select a number:

<select name="number" id="number">

<option value="1">1</option>

<option value="2" selected>2</option>

<option value="3">3</option>

<option value="4">4</option>

<option value="5">5</option>

<option value="6">6</option>

<option value="7">7</option>

<option value="8">8</option>

<option value="9">9</option>

<option value="10">10</option>

<option value="11">11</option>

<option value="12">12</option>

<option value="13">13</option>

<option value="14">14</option>

<option value="15">15</option>

<option value="16">16</option>

<option value="17">17</option>

<option value="18">18</option>

<option value="19">19</option>

</select>

The problem was that I was looking to create 3 columns instead of the 1 default column. So, I tried two options for aligning the text content inside the option tag.

Putting the text inside the span tag.

Putting the text inside a table made of one row and three columns (cells).

Given below is the code which I tried.

<option value="1">
        Apple
        Mango
        Orange
        </option>
      <option value="2" selected>

          1
          2
          3

      </option>

But this didn't fix my problem as I was getting the Output as shown in the below image.

Since I'm a beginner in HTML, CSS, and jQuery, therefore, I have no idea of what to do next for creating a drop-down list containing 3 columns in each row. Please note that I'll select the whole row consisting of all the 3 columns (as shown in the below image) and not any cell of any particular column.Can anyone kindly suggest what can be done to fix this problem and create the dropdown list as shown in the first image?

Body:
Firstly, we will want to create a proper HTML Structure. There is an element of select you will want to learn about: <optgroup>. Here is a basic suggested structure.

<label for="options">Select an Option:</label>
<select id="options">
  <optgroup label="PREFERRED OPTIONS">
    <option value="L">Standard Screw Adjustment</option>
  </optgroup>
  <optgroup label="STANDARD OPTIONS">
    <option value="C">Tamper Resistant - Factory Set</option>
    <option value="K">Handknob</option>
  </optgroup>
  <optgroup label="ADDITIONAL OPTIONS">
    <option value="F">Hex Head Screw with Locknut</option>
  </optgroup>
</select>

This is just the start. You can use $("#options").selectmenu(); and you get a lot closer to what you want. We still need to add more elements and incorporate the extra data.

The selectmenu widget is built with the widget factory and can be extended. When extending widgets, you have the ability to override or add to the behavior of existing methods.

This is exactly what we will do, taking an example from .autocomplete(). See this example here: http://jqueryui.com/autocomplete/#categories

We will perform the same type of override within .selectmenu(). The widget factory and it's code can be a bit advanced and a bit hard to understand sometimes, so you'll have to dig through this more on your own.

HTML

<label for="options">Select an Option:</label>
<select id="options">
  <optgroup label="PREFERRED OPTIONS">
    <option data-short="L" data-price="$0.00" value="L">Standard Screw Adjustment</option>
  </optgroup>
  <optgroup label="STANDARD OPTIONS">
    <option data-short="C" data-price="$5.00" value="C">Tamper Resistant - Factory Set</option>
    <option data-short="K" data-price="$6.00" value="K">Handknob</option>
  </optgroup>
  <optgroup label="ADDITIONAL OPTIONS">
    <option data-short="F" data-price="-$4.00" value="F">Hex Head Screw with Locknut</option>
  </optgroup>
</select>

What you see above is sort of extended from what we built first. I have added data attributes. They do not mean much to our HTML yet they can be useful for our jQuery. the benefit here is that if we encounter a browser that does not support JavaScript (and hence cannot load the jQuery library), the code will fall back to basic HTML Markup and still be a similar experience for the user.

CSS

.ui-selectmenu-category {
  color: #5F5F5F;
  padding: .5em .25em;
}
.ui-menu-item {
}
.ui-menu-item .ui-menu-item-wrapper {
  display: inline-block;
  padding: 1em 2px;
}

.ui-menu-item .ui-menu-item-wrapper.ui-state-active {
  border-width: 1px 0 1px 0;
  border-color: #CCCCCC;
  background-color: #E4EBF1;
  color: #000;
}

.ui-menu-item .ui-menu-item-wrapper.ui-state-active.short {
  color: #2E6D99;
}

.ui-menu-item div.ui-menu-item-wrapper {
  width: 295px;
}

.ui-menu-item .short {
  color: #2E6D99;
  font-weight: strong;
  width: 30px;
  padding-left: .5em;
}

.ui-menu-item .price {
  font-weight: strong;
  width: 75px;
  margin-right: -6px;
}

We're going to override and extend a number of theme elements for the .selectmenu(). this is all just to help make it fit the look and feel desired.

JavaScript

$(function() {
  $.widget("custom.mySelectMenu", $.ui.selectmenu, {
    _renderMenu: function(ul, items) {
      var that = this,
        currentCategory = "";
      $.each(items, function(index, item) {
        var li, name, short, price;
        if (item.optgroup != currentCategory) {
          ul.append("<li class='ui-selectmenu-category'>" + item.optgroup + "</li>");
          currentCategory = item.optgroup;
        }
        li = that._renderItemData(ul, item);
        console.log(ul);
        name = li.text();
        short = item.element.data("short");
        price = item.element.data("price");
        console.log(li, short, price);
        li.prepend($("<span>", {
          class: "short"
        }).html(short));
        li.append($("<span>", {
          class: "price"
        }).html(price));
        if (item.optgroup) {
          li.attr("aria-label", item.optgroup + " : " + item.label);
        }
      });
    }
  });
  $("#options").mySelectMenu({
    width: 400
  });
});

Working Example: https://jsfiddle.net/Twisty/sn1z5vzn/7/

Here is where we're taking the $.ui.selectmenu and extending it to our own use. You can see we're only writing a function for the _renderMenu extension point. Everything else about the selectmenu will be carried through untouched.

This is important since we'll need to define a width option. We need to know the width so that we can create proper columns, essentially.

This will go through each of the items and create li elements to be used with the ul that is created by selectmenu. The resulting items will look like:

<li aria-label="PREFERRED OPTIONS : Standard Screw Adjustment" class="ui-menu-item">
  <span class="short ui-menu-item-wrapper ui-state-active" id="ui-id-1" tabindex="-1" role="option">L</span>
  <div id="ui-id-2" tabindex="-1" role="option" class="ui-menu-item-wrapper ui-state-active">Standard Screw Adjustment</div>
  <span class="price ui-menu-item-wrapper ui-state-active" id="ui-id-3" tabindex="-1" role="option">$0.00</span>
</li>

jQuery UI does a lot of extra work for us, assigning unique IDs and applying hover classes, etc. Our additions allow us to style and theme different parts of each item.

The category items don't want to play well. So far, I found if I try to add any HTML element into it's li, it cannot render the rest of the menu properly. I may go back and see if _renderItem will help here.

Easy, right!? Comment if you have questions.

References

Selectmenu Widget

Autocomplete Category Demo

HTML <optgroup> Tag

.data()

Update

If you change your Option like so:

<option data-icon-url="https://www.gravatar.com/avatar/b3e04a46e85ad3e165d66f5d927eb609?d=monsterid&r=g&s=16" data-price="$0.00" value="L">Standard Screw Adjustment</option>

You can then update the <span> to use this as it's background.

CSS Snippet

.ui-menu-item .icon {
  background-repeat: no-repeat;
  background-size: 30px;
  background-position: center center;
  color: #2E6D99;
  font-weight: strong;
  width: 30px;
  padding-left: .5em;
}

JavaScript Snippet

    li.prepend($("<span>", {
      class: "icon",
      style: "background-image: url('" + iconUrl + "')"
    }).html("&nbsp;"));

The &nbsp; renders a Non-breaking Space character.

A common character entity used in HTML is the non-breaking space: &nbsp;

A non-breaking space is a space that will not break into a new line.

Two words separated by a non-breaking space will stick together (not break into a new line). This is handy when breaking the words might be disruptive.

HTML Entities

Working Example: https://jsfiddle.net/Twisty/sn1z5vzn/12/


问:
Ionic 2 http.post formdata null values on php server side
I use FormData to send data to the server. I can log in but the values for device and device_token are null on the server side.

Here is the code:

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class Auth{

    credentials = {
        username:'',
        password:'',
        token:'',
        device:'ios',
        device_token:'ios'
    }
    headers:any;
    constructor(public http:Http){
    }

    Login(credentials)
    {
        let newCredentials: FormData = new FormData();
        newCredentials.append("device",credentials.device);
        newCredentials.append("device_token",credentials.device_token);
        newCredentials.append("username",credentials.username);
        newCredentials.append("password",credentials.password);

        return new Promise((resolve,reject) =>{
            let headers = new Headers();
            headers.append('Content-Type','application/x-www-form-urlencoded');
            console.log("body: "+ "username: " + newCredentials.get("username"));
            console.log("body: "+ "password: " + newCredentials.get("password"));
            console.log("body: "+ "device: " + newCredentials.get("device"));
            console.log("body: "+ "device_token: " + newCredentials.get("device_token"));

            this.headers = {headers}
            this.http.post('http://www.example.com/api/login/',newCredentials,this.headers)
            .map(res => res)
            .subscribe(res=>{
                var resJson = res.json();
                this.credentials.token = resJson.token;
                resolve(res);
            },(err) =>{
                reject(err);
                console.log(err.error);
            });
        });
    }
</code>```

I have tried with Postman and the values for device and device_token on the server weren't null.

答:
If you use FormData, the request will automatically be multipart/form-data rather than x-www-form-urlencoded even if you set the header explicitly. This will still work if you are willing to handle the multipart form data on the server side, but it's not really necessary unless you're uploading files. Instead you can use URLSearchParams or even just a query string formatted string.

```<code>    let newCredentials = new URLSearchParams();
    newCredentials.set("device",credentials.device);
    newCredentials.set("device_token",credentials.device_token);
    newCredentials.set("username",credentials.username);
    newCredentials.set("password",credentials.password);
    newCredentials = newCredentials.toString();
</code>```

On another note, you don't need to wrap this in a Promise yourself. Instead, I would suggest returning the observable stream from .http.post:

```<code>return this.http.post(...props).map(res => res.json()).map(resJson => {
  this.credentials.token = resJson.token;
  return resJson;
});
</code>```

Now you will have to use .subscribe in whatever code calls the auth.Login method.

If you really want to use promises, you can also use .toPromise() on this.http.post() which will do what your code is already doing now.

Body:
I use FormData to send data to the server. I can log in but the values for device and device_token are null on the server side.

Here is the code:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class Auth{

    credentials = {
        username:'',
        password:'',
        token:'',
        device:'ios',
        device_token:'ios'
    }
    headers:any;
    constructor(public http:Http){
    }

    Login(credentials)
    {
        let newCredentials: FormData = new FormData();
        newCredentials.append("device",credentials.device);
        newCredentials.append("device_token",credentials.device_token);
        newCredentials.append("username",credentials.username);
        newCredentials.append("password",credentials.password);

        return new Promise((resolve,reject) =>{
            let headers = new Headers();
            headers.append('Content-Type','application/x-www-form-urlencoded');
            console.log("body: "+ "username: " + newCredentials.get("username"));
            console.log("body: "+ "password: " + newCredentials.get("password"));
            console.log("body: "+ "device: " + newCredentials.get("device"));
            console.log("body: "+ "device_token: " + newCredentials.get("device_token"));

            this.headers = {headers}
            this.http.post('http://www.example.com/api/login/',newCredentials,this.headers)
            .map(res => res)
            .subscribe(res=>{
                var resJson = res.json();
                this.credentials.token = resJson.token;
                resolve(res);
            },(err) =>{
                reject(err);
                console.log(err.error);
            });
        });
    }

I have tried with Postman and the values for device and device_token on the server weren't null.

Body:
If you use FormData, the request will automatically be multipart/form-data rather than x-www-form-urlencoded even if you set the header explicitly. This will still work if you are willing to handle the multipart form data on the server side, but it's not really necessary unless you're uploading files. Instead you can use URLSearchParams or even just a query string formatted string.

    let newCredentials = new URLSearchParams();
    newCredentials.set("device",credentials.device);
    newCredentials.set("device_token",credentials.device_token);
    newCredentials.set("username",credentials.username);
    newCredentials.set("password",credentials.password);
    newCredentials = newCredentials.toString();

On another note, you don't need to wrap this in a Promise yourself. Instead, I would suggest returning the observable stream from .http.post:

return this.http.post(...props).map(res => res.json()).map(resJson => {
  this.credentials.token = resJson.token;
  return resJson;
});

Now you will have to use .subscribe in whatever code calls the auth.Login method.

If you really want to use promises, you can also use .toPromise() on this.http.post() which will do what your code is already doing now.


问:
return statement in a function as class
I am confused about the return statement in a function that serves as a class. See the example code below:

```<code><html>
<body>

<script type="text/javascript">
function test() {
    this.abc = 'def';
    return 3;
}

var mytest = new test();

document.write(mytest + ', ' + (typeof mytest) + ', ' + mytest.abc);

</script>

</body>
</html>
</code>```

The code out put: [object Object], object, def.

Here is my question. I wrote 'return 3' in the test() function. Is this statement ignored when 'new test()' is called?

Thanks.

答:
When you call a function with new, you're invoking it as a constructor which automatically returns the new object it constructs.

Your return 3; statement is ignored. What is returned is effectively:

```<code>{ abc:'def' }
</code>```

...with an implicit reference to a prototype object, which in your example doesn't have any enumerable properties because you haven't given it any.

If you did:

```<code>mytest instanceof test;
</code>```

...it would evaluate to true.

If you did:

```<code>function test() {
    this.abc = 'def';
}
test.prototype.ghi = 'jkl';

var mytest = new test();
</code>```

...you could then do:

```<code>mytest.ghi;
</code>```

...which would give you the value 'jkl'.

ContentLicense: CC BY-SA 2.5

Title: return statement in a function as class

Body:
I am confused about the return statement in a function that serves as a class. See the example code below:

The code out put: [object Object], object, def.

Here is my question. I wrote 'return 3' in the test() function. Is this statement ignored when 'new test()' is called?

Thanks.

Body:
When you call a function with new, you're invoking it as a constructor which automatically returns the new object it constructs.

Your return 3; statement is ignored. What is returned is effectively:

{ abc:'def' }

...with an implicit reference to a prototype object, which in your example doesn't have any enumerable properties because you haven't given it any.

If you did:

mytest instanceof test;

...it would evaluate to true.

If you did:

function test() {
    this.abc = 'def';
}
test.prototype.ghi = 'jkl';

var mytest = new test();

...you could then do:

mytest.ghi;

...which would give you the value 'jkl'.


问:
How to replace nth character of a string with another
How could I replace nth character of a String with another one?

```<code>func replace(myString:String, index:Int, newCharac:Character) -> String {
    // Write correct code here
    return modifiedString
}
</code>```

For example, replace("House", 2, "r") should be equal to "Horse".

答:
In Swift 4 it's much easier.

```<code>let newString = oldString.prefix(n) + char + oldString.dropFirst(n + 1)
</code>```

This is an example:

```<code>let oldString = "Hello, playground"
let newString = oldString.prefix(4) + "0" + oldString.dropFirst(5)
</code>```

where the result is

```<code>Hell0, playground
</code>```

The type of newString is Substring. Both prefix and dropFirst return Substring. Substring is a slice of a string, in other words, substrings are fast because you don't need to allocate memory for the content of the string, but the same storage space as the original string is used.

Body:
How could I replace nth character of a String with another one?

func replace(myString:String, index:Int, newCharac:Character) -> String {
    // Write correct code here
    return modifiedString
}

For example, replace("House", 2, "r") should be equal to "Horse".

Body:
In Swift 4 it's much easier.

let newString = oldString.prefix(n) + char + oldString.dropFirst(n + 1)

This is an example:

let oldString = "Hello, playground"
let newString = oldString.prefix(4) + "0" + oldString.dropFirst(5)

where the result is

Hell0, playground

The type of newString is Substring. Both prefix and dropFirst return Substring. Substring is a slice of a string, in other words, substrings are fast because you don't need to allocate memory for the content of the string, but the same storage space as the original string is used.


问:
Why the elements disappear after I use push_back() function of vector
I am trying to use std::vector in a class to realize a muti-way tree.

Each time when I want to add a child in on of the member, I use a function addMember. I'm using VS2017 to debug this program. In this function scope the parent's children vector has actually add the elements by push_back(), but after exiting the function, the address of vector will change and the elements I have added will disappear.

Here's my code:

```<code>#include <iostream>
#include<string>
#include<vector>

using namespace std;

class member {
public:
    string name;
    member* parent;
    vector<member*> children;
    member(string m_name,member* m_parent):name(m_name),parent(m_parent){}
};

class familyTree {
private:
    member ancestor;
public:
    member* getAncestor() { return &ancestor; }
    familyTree(member& m_ancestor):ancestor(m_ancestor){}
    member* searchMember(string name,member* node,bool& flag);
    void addMember(string name, int children_number,vector<string>& children_name);
};

member* familyTree::searchMember(string name, member* node,bool& flag) {
    member* find = NULL;
    if (node) {
        if (node->name == name)
            find = node;
        else {
            if (!flag) {
                for (auto iter = node->children.begin(); iter != node->children.end(); iter++) {
                    find = searchMember(name, *iter, flag);
                    if (flag)
                        break;
                }
            }
        }
    }
    return find;
}

void familyTree::addMember(string name,int children_number,vector<string>& children_name) {
    bool flag = false;
    member* parent = searchMember(name, getAncestor(), flag);
    for (auto i : children_name) {
        member* child = new member(i,parent);
        parent->children.push_back(child);
    }
}
</code>```

答:
I suspect that there is something wrong with the familyTree::searchMember function. Here was what you posted:

```<code>member* familyTree::searchMember(string name, member* node, bool& flag) {
    member* find = NULL;
    if (node) {
        if (node->name == name)
            find = node;
        else {
            if (!flag) {
                for (auto iter = node->children.begin(); iter != node->children.end(); iter++) {
                    find = searchMember(name, *iter, flag);
                    if (flag)
                        break;
                }
            }
        }
    }
    return find;
}
</code>```

Notice that there was no method to set the flag = true once you have found the correct node.

The 2nd if statement should be:

```<code>if (node->name == name) {
    find = node;
    flag = true;
}
</code>```

Otherwise within your for loop,

```<code>for (auto iter = node->children.begin(); iter != node->children.end(); iter++) {
    find = searchMember(name, *iter, flag);
    if (flag)
        break;
}
</code>```

even if there was a successful search, the for loop does not break and so it continues on, and the next child you search is guaranteed to not be a match.

Note that the way your searchMember function is structured results in NULL being returned if you search through a node that does not have a matching name and does not have any children because the for loop is skipped (no children to iterate through). So you end up with a lot of NULL pointers being assigned to parent in addMember.

Body:
I am trying to use std::vector in a class to realize a muti-way tree.

Each time when I want to add a child in on of the member, I use a function addMember. I'm using VS2017 to debug this program. In this function scope the parent's children vector has actually add the elements by push_back(), but after exiting the function, the address of vector will change and the elements I have added will disappear.

Here's my code:

#include <iostream>
#include<string>
#include<vector>

using namespace std;

class member {
public:
    string name;
    member* parent;
    vector<member*> children;
    member(string m_name,member* m_parent):name(m_name),parent(m_parent){}
};

class familyTree {
private:
    member ancestor;
public:
    member* getAncestor() { return &ancestor; }
    familyTree(member& m_ancestor):ancestor(m_ancestor){}
    member* searchMember(string name,member* node,bool& flag);
    void addMember(string name, int children_number,vector<string>& children_name);
};

member* familyTree::searchMember(string name, member* node,bool& flag) {
    member* find = NULL;
    if (node) {
        if (node->name == name)
            find = node;
        else {
            if (!flag) {
                for (auto iter = node->children.begin(); iter != node->children.end(); iter++) {
                    find = searchMember(name, *iter, flag);
                    if (flag)
                        break;
                }
            }
        }
    }
    return find;
}

void familyTree::addMember(string name,int children_number,vector<string>& children_name) {
    bool flag = false;
    member* parent = searchMember(name, getAncestor(), flag);
    for (auto i : children_name) {
        member* child = new member(i,parent);
        parent->children.push_back(child);
    }
}

Body:
I suspect that there is something wrong with the familyTree::searchMember function. Here was what you posted:

member* familyTree::searchMember(string name, member* node, bool& flag) {
    member* find = NULL;
    if (node) {
        if (node->name == name)
            find = node;
        else {
            if (!flag) {
                for (auto iter = node->children.begin(); iter != node->children.end(); iter++) {
                    find = searchMember(name, *iter, flag);
                    if (flag)
                        break;
                }
            }
        }
    }
    return find;
}

Notice that there was no method to set the flag = true once you have found the correct node.

The 2nd if statement should be:

if (node->name == name) {
    find = node;
    flag = true;
}

Otherwise within your for loop,

for (auto iter = node->children.begin(); iter != node->children.end(); iter++) {
    find = searchMember(name, *iter, flag);
    if (flag)
        break;
}

even if there was a successful search, the for loop does not break and so it continues on, and the next child you search is guaranteed to not be a match.

Note that the way your searchMember function is structured results in NULL being returned if you search through a node that does not have a matching name and does not have any children because the for loop is skipped (no children to iterate through). So you end up with a lot of NULL pointers being assigned to parent in addMember.


问:
Defining operator overload on pointer
Given

```<code>struct foo {
    struct node {
        int data;
        node* next, prev;
    };
    friend std::ostream& operator<< (std::ostream& os, const foo::node& n) {
         os << n.data;
         return os;
    }
    // friend node* operator++ (list::node* n) { return n->next; }
};
</code>```

I need to overload ++ that acts on foo::node* only.  Where and how do I define that operator?  My commented-out line above indicates what I'm trying to do.  Thanks.

An example usage is:

```<code>for (list::node* it = f.begin();  it != f.end();  ++it)
     std::cout << *it << ' ';
</code>```

where f is a foo object, and the begin() and end() functions return some foo::node pointers.

答:
C++ doesn't allow you to define operator overloads for primitive types. In this case, foo::node* is  primitive type.

What you can do is create your own wrapper around foo::node* which behaves as you desire:

```<code>struct node_iterator
{
    foo::node* _p;

    // ...

    friend node_iterator operator++(node_iterator n)
    {
        return {n._p->next};
    }
};
</code>```

Title: Defining operator overload on pointer

Body:
Given

struct foo {
    struct node {
        int data;
        node* next, prev;
    };
    friend std::ostream& operator<< (std::ostream& os, const foo::node& n) {
         os << n.data;
         return os;
    }
    // friend node* operator++ (list::node* n) { return n->next; }
};

I need to overload ++ that acts on foo::node* only.  Where and how do I define that operator?  My commented-out line above indicates what I'm trying to do.  Thanks.

An example usage is:

for (list::node* it = f.begin();  it != f.end();  ++it)
     std::cout << *it << ' ';

where f is a foo object, and the begin() and end() functions return some foo::node pointers.

Body:
C++ doesn't allow you to define operator overloads for primitive types. In this case, foo::node* is  primitive type.

What you can do is create your own wrapper around foo::node* which behaves as you desire:

struct node_iterator
{
    foo::node* _p;

    // ...

    friend node_iterator operator++(node_iterator n)
    {
        return {n._p->next};
    }
};


问:
Does hortonworks support Hue?
Recently i heard that apache Ambari support Hue (which is a Cloudera component) but I'm not sure if I can use it on my HDP 2.5, and if it can work well for my cluster with no problem (I use Ambari 2.5) </p>

<p>Does HDP support Hue?   </p>

答:
Based on HDP 2.5.0 Release Notes it does.  At the bottom of the page, you'll see:

Additional component versions:

Cascading 3.0.0

Hue 2.6.0

Title: Does hortonworks support Hue?

Body:
Recently i heard that apache Ambari support Hue (which is a Cloudera component) but I'm not sure if I can use it on my HDP 2.5, and if it can work well for my cluster with no problem (I use Ambari 2.5)

Does HDP support Hue?


问:
Canvas Snow Animation does not work
So a season specific question. I have made a basic animation to simulate some snow. The problem is that the snow only falls once and the screen stays black after that. I have followed a tutorial which put everything inside the window.onload(). THis seems not as good style to me so here is what i came up with:

let sky, ctx;
let W, H;

const maxSnow = 250;
const snow = [];

function init(){
 sky = document.getElementById("sky");
 ctx = sky.getContext("2d");

 sky.width = W = window.innerWidth;
 sky.height = H = window.innerHeight;

 for(let i = 0; i < maxSnow; i++)
 {
  snow.push({
   x: Math.random()*W, //x-coordinate
   y: -50, //y-coordinate
   radius: Math.random()*4+1, //radius
   density: Math.random()*maxSnow //density
  })
 }
}

function draw()
{
 ctx.clearRect(0, 0, W, H);

 ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
 ctx.beginPath();
 for(let i = 0; i < maxSnow; i++)
 {
  var flake = snow[i];
  ctx.moveTo(flake.x, flake.y);
  ctx.arc(flake.x, flake.y, flake.radius, 0, Math.PI*2, true);
 }
 ctx.fill();
 update();
}

//Function to move the snowflakes
//angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes
var angle = 0;
function update()
{
 angle += 0.01;
 for(var i = 0; i < maxSnow; i++)
 {
  var p = snow[i];
  //Updating X and Y coordinates
  //We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards
  //Every particle has its own density which can be used to make the downward movement different for each flake
  //Lets make it more random by adding in the radius
  p.y += Math.cos(angle+p.density) + 1 + p.radius/2;
  p.x += Math.sin(angle) * 2;

  //Sending flakes back from the top when it exits
  //Lets make it a bit more organic and let flakes enter from the left and right also.
  if(p.x > W+5 || p.x < -5 || p.y > H)
  {
   if(i%3 > 0) //66.67% of the flakes
   {
    snow[i] = {x: Math.random()*W, y: -10, r: p.radius, d: p.density};
   }
   else
   {
    //If the flake is exitting from the right
    if(Math.sin(angle) > 0)
    {
     //Enter from the left
     snow[i] = {x: -5, y: Math.random()*H, r: p.radius, d: p.density};
    }
    else
    {
     //Enter from the right
     snow[i] = {x: W+5, y: Math.random()*H, r: p.radius, d: p.density};
    }
   }
  }
 }
}

window.onload = function(){
 init();
 //animation loop
 setInterval(draw, 33);
}

window.addEventListener('resize', function(){
  sky.width = W = window.innerWidth;
  sky.height = H = window.innerHeight;
}, false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
}

body {
  overflow: hidden;
  background-color: rgba(0, 0, 0, 1);
}</code>```

    <link rel="stylesheet" href="style.css">

    <canvas id="sky"></canvas>

```

Does anybody see what the problem is and why the particles are only falling once?
Thank you.

答:
The is because when the snow flakes exit the screen you reset them to a wrong object.

You original object (and all methods) expect x,y,radius and density

But when you update the object you create x,y, r and d.

If you rename r and d to the correct names it works.

let sky, ctx;
let W, H;

const maxSnow = 250;
const snow = [];

function init(){
 sky = document.getElementById("sky");
 ctx = sky.getContext("2d");

 sky.width = W = window.innerWidth;
 sky.height = H = window.innerHeight;

 for(let i = 0; i < maxSnow; i++)
 {
  snow.push({
   x: Math.random()*W, //x-coordinate
   y: -50, //y-coordinate
   radius: Math.random()*4+1, //radius
   density: Math.random()*maxSnow //density
  })
 }
}

function draw()
{
 ctx.clearRect(0, 0, W, H);

 ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
 ctx.beginPath();
 for(let i = 0; i < maxSnow; i++)
 {
  var flake = snow[i];
  ctx.moveTo(flake.x, flake.y);
  ctx.arc(flake.x, flake.y, flake.radius, 0, Math.PI*2, true);
 }
 ctx.fill();
 update();
}

//Function to move the snowflakes
//angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes
var angle = 0;
function update()
{
 angle += 0.01;
 for(var i = 0; i < maxSnow; i++)
 {
  var p = snow[i];
  //Updating X and Y coordinates
  //We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards
  //Every particle has its own density which can be used to make the downward movement different for each flake
  //Lets make it more random by adding in the radius
  p.y += Math.cos(angle+p.density) + 1 + p.radius/2;
  p.x += Math.sin(angle) * 2;

  //Sending flakes back from the top when it exits
  //Lets make it a bit more organic and let flakes enter from the left and right also.
  if(p.x > W+5 || p.x < -5 || p.y > H)
  {
   if(i%3 > 0) //66.67% of the flakes
   {
    snow[i] = {x: Math.random()*W, y: -10, radius: p.radius, density: p.density};
   }
   else
   {
    //If the flake is exitting from the right
    if(Math.sin(angle) > 0)
    {
     //Enter from the left
     snow[i] = {x: -5, y: Math.random()*H, radius: p.radius, density: p.density};
    }
    else
    {
     //Enter from the right
     snow[i] = {x: W+5, y: Math.random()*H, radius: p.radius, density: p.density};
    }
   }
  }
 }
}

window.onload = function(){
 init();
 //animation loop
 setInterval(draw, 33);
}

window.addEventListener('resize', function(){
  sky.width = W = window.innerWidth;
  sky.height = H = window.innerHeight;
}, false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
}

body {
  overflow: hidden;
  background-color: rgba(0, 0, 0, 1);
}</code>```

    <link rel="stylesheet" href="style.css">

    <canvas id="sky"></canvas>

```

Title: Canvas Snow Animation does not work

Body:
So a season specific question. I have made a basic animation to simulate some snow. The problem is that the snow only falls once and the screen stays black after that. I have followed a tutorial which put everything inside the window.onload(). THis seems not as good style to me so here is what i came up with:

let sky, ctx;
let W, H;

const maxSnow = 250;
const snow = [];

function init(){
 sky = document.getElementById("sky");
 ctx = sky.getContext("2d");

 sky.width = W = window.innerWidth;
 sky.height = H = window.innerHeight;

 for(let i = 0; i < maxSnow; i++)
 {
  snow.push({
   x: Math.random()*W, //x-coordinate
   y: -50, //y-coordinate
   radius: Math.random()*4+1, //radius
   density: Math.random()*maxSnow //density
  })
 }
}

function draw()
{
 ctx.clearRect(0, 0, W, H);

 ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
 ctx.beginPath();
 for(let i = 0; i < maxSnow; i++)
 {
  var flake = snow[i];
  ctx.moveTo(flake.x, flake.y);
  ctx.arc(flake.x, flake.y, flake.radius, 0, Math.PI*2, true);
 }
 ctx.fill();
 update();
}

//Function to move the snowflakes
//angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes
var angle = 0;
function update()
{
 angle += 0.01;
 for(var i = 0; i < maxSnow; i++)
 {
  var p = snow[i];
  //Updating X and Y coordinates
  //We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards
  //Every particle has its own density which can be used to make the downward movement different for each flake
  //Lets make it more random by adding in the radius
  p.y += Math.cos(angle+p.density) + 1 + p.radius/2;
  p.x += Math.sin(angle) * 2;

  //Sending flakes back from the top when it exits
  //Lets make it a bit more organic and let flakes enter from the left and right also.
  if(p.x > W+5 || p.x < -5 || p.y > H)
  {
   if(i%3 > 0) //66.67% of the flakes
   {
    snow[i] = {x: Math.random()*W, y: -10, r: p.radius, d: p.density};
   }
   else
   {
    //If the flake is exitting from the right
    if(Math.sin(angle) > 0)
    {
     //Enter from the left
     snow[i] = {x: -5, y: Math.random()*H, r: p.radius, d: p.density};
    }
    else
    {
     //Enter from the right
     snow[i] = {x: W+5, y: Math.random()*H, r: p.radius, d: p.density};
    }
   }
  }
 }
}

window.onload = function(){
 init();
 //animation loop
 setInterval(draw, 33);
}

window.addEventListener('resize', function(){
  sky.width = W = window.innerWidth;
  sky.height = H = window.innerHeight;
}, false);

* {
  margin: 0;
  padding: 0;
}

body {
  overflow: hidden;
  background-color: rgba(0, 0, 0, 1);
}

    <link rel="stylesheet" href="style.css">

    <canvas id="sky"></canvas>

Does anybody see what the problem is and why the particles are only falling once?
Thank you.

Body:
The is because when the snow flakes exit the screen you reset them to a wrong object.

You original object (and all methods) expect x,y,radius and density

But when you update the object you create x,y, r and d.

If you rename r and d to the correct names it works.

let sky, ctx;
let W, H;

const maxSnow = 250;
const snow = [];

function init(){
 sky = document.getElementById("sky");
 ctx = sky.getContext("2d");

 sky.width = W = window.innerWidth;
 sky.height = H = window.innerHeight;

 for(let i = 0; i < maxSnow; i++)
 {
  snow.push({
   x: Math.random()*W, //x-coordinate
   y: -50, //y-coordinate
   radius: Math.random()*4+1, //radius
   density: Math.random()*maxSnow //density
  })
 }
}

function draw()
{
 ctx.clearRect(0, 0, W, H);

 ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
 ctx.beginPath();
 for(let i = 0; i < maxSnow; i++)
 {
  var flake = snow[i];
  ctx.moveTo(flake.x, flake.y);
  ctx.arc(flake.x, flake.y, flake.radius, 0, Math.PI*2, true);
 }
 ctx.fill();
 update();
}

//Function to move the snowflakes
//angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes
var angle = 0;
function update()
{
 angle += 0.01;
 for(var i = 0; i < maxSnow; i++)
 {
  var p = snow[i];
  //Updating X and Y coordinates
  //We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards
  //Every particle has its own density which can be used to make the downward movement different for each flake
  //Lets make it more random by adding in the radius
  p.y += Math.cos(angle+p.density) + 1 + p.radius/2;
  p.x += Math.sin(angle) * 2;

  //Sending flakes back from the top when it exits
  //Lets make it a bit more organic and let flakes enter from the left and right also.
  if(p.x > W+5 || p.x < -5 || p.y > H)
  {
   if(i%3 > 0) //66.67% of the flakes
   {
    snow[i] = {x: Math.random()*W, y: -10, radius: p.radius, density: p.density};
   }
   else
   {
    //If the flake is exitting from the right
    if(Math.sin(angle) > 0)
    {
     //Enter from the left
     snow[i] = {x: -5, y: Math.random()*H, radius: p.radius, density: p.density};
    }
    else
    {
     //Enter from the right
     snow[i] = {x: W+5, y: Math.random()*H, radius: p.radius, density: p.density};
    }
   }
  }
 }
}

window.onload = function(){
 init();
 //animation loop
 setInterval(draw, 33);
}

window.addEventListener('resize', function(){
  sky.width = W = window.innerWidth;
  sky.height = H = window.innerHeight;
}, false);

* {
  margin: 0;
  padding: 0;
}

body {
  overflow: hidden;
  background-color: rgba(0, 0, 0, 1);
}

<html>
  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <canvas id="sky"></canvas>
    <script src="snow.js"></script>
  </body>
</html>


问:
Shiny app path error
I am trying to create an shiny app that uploads an image and then does OCR. The upload part seems to work but the OCR gives an error "Error: path must be URL, filename or raw vector"     Any help is appreciated.

On another but related note, is anyone familiar with the implementation of MSER algorithm in R? I know I can call the python implementation through R.

```<code>library(shiny)
library(magick)
library(magrittr)

ui <- shinyUI(fluidPage(
 titlePanel('Test Code'),
 sidebarLayout(
sidebarPanel(
  fileInput(inputId = 'files',
            label = 'Select an Invoice',
            multiple = FALSE,
            accept=c('image/png', 'image/jpeg')),
  imageOutput('images')
),
mainPanel(

textOutput('extracted')

)
)
))

server <- shinyServer(function(input, output) {
output$files <- renderTable(input$files)

files <- reactive({
files <- input$files
files$datapath <- gsub("\\\\", "/", files$datapath)
files
})

output$extracted<-renderText({
text <- image_read(list(src = files()$datapath[1])) %>%
  image_resize("2000") %>%
  image_convert(colorspace = 'gray') %>%
  image_trim() %>%
  image_ocr()
  cat(text)

})

output$images <- renderImage({
        list(src = files()$datapath[1],
             height = 800,
             width  = 600,
             alt = "Upload an Invoice in an image format")
      }, deleteFile = FALSE)

}
)

 shinyApp(ui=ui,server=server)
</code>```

答:
You need to fix output$extracted as follows:

```<code>  output$extracted <- renderText({
    if (is.null(input$files)) return(NULL)
    # Fix file path
    text <- image_read(files()$datapath[1]) %>%
      image_resize("2000") %>%
      image_convert(colorspace = 'gray') %>%
      image_trim() %>%
      image_ocr()
    # Print to the console
    cat(text)
    # Return value to be rendered in Shiny
    text
  })
</code>```

Title: Shiny app path error

Body:
I am trying to create an shiny app that uploads an image and then does OCR. The upload part seems to work but the OCR gives an error "Error: path must be URL, filename or raw vector"     Any help is appreciated.

On another but related note, is anyone familiar with the implementation of MSER algorithm in R? I know I can call the python implementation through R.

library(shiny)
library(magick)
library(magrittr)

ui <- shinyUI(fluidPage(
 titlePanel('Test Code'),
 sidebarLayout(
sidebarPanel(
  fileInput(inputId = 'files',
            label = 'Select an Invoice',
            multiple = FALSE,
            accept=c('image/png', 'image/jpeg')),
  imageOutput('images')
),
mainPanel(

textOutput('extracted')

)
)
))

server <- shinyServer(function(input, output) {
output$files <- renderTable(input$files)

files <- reactive({
files <- input$files
files$datapath <- gsub("\\\\", "/", files$datapath)
files
})

output$extracted<-renderText({
text <- image_read(list(src = files()$datapath[1])) %>%
  image_resize("2000") %>%
  image_convert(colorspace = 'gray') %>%
  image_trim() %>%
  image_ocr()
  cat(text)

})

output$images <- renderImage({
        list(src = files()$datapath[1],
             height = 800,
             width  = 600,
             alt = "Upload an Invoice in an image format")
      }, deleteFile = FALSE)

}
)

 shinyApp(ui=ui,server=server)

Body:
You need to fix output$extracted as follows:

  output$extracted <- renderText({
    if (is.null(input$files)) return(NULL)
    # Fix file path
    text <- image_read(files()$datapath[1]) %>%
      image_resize("2000") %>%
      image_convert(colorspace = 'gray') %>%
      image_trim() %>%
      image_ocr()
    # Print to the console
    cat(text)
    # Return value to be rendered in Shiny
    text
  })


问:
Schroedinger's label caption update
I have some code in VBA that goes like this:

```<code>Sub UserForm2_Activate()
....
If [statement] then
  Label1.caption = x
  Label2.caption = x*y
Else
...
</code>```

When I activate the UserForm with these labels from the other one (using UserForm2.Show) the results are Label1 = x, Label2 = 0. But when I try "UserForm2.Show" from the Immediate window, everything works pretty good and I get the correct data.

What am I doing wrong?

The actual code:

```<code>If Sheets("SL").Range("B8").Value = True Then
   Label8.Caption = Find_cost(Sheets("SL").Range("b5").Value, Sheets("SL").Range("B4").Value, "ID")
   Label20.Caption = Find_cost(Sheets("SL").Range("b5").Value, Sheets("SL").Range("B4").Value, "ID") * Sheets("SL").Range("b4").Value
Else
   Label8.Caption = "none"
   Label20.Caption = "none"
End If
</code>```

Where "Find_cost" is a custom function

答: Use a userform_initialize event instead of userform_activate. Also, you should save temporary values in variables and debug with breakpoints.</p>

Title: Schroedinger's label caption update

Body:
I have some code in VBA that goes like this:

Sub UserForm2_Activate()
....
If [statement] then
  Label1.caption = x
  Label2.caption = x*y
Else
...

When I activate the UserForm with these labels from the other one (using UserForm2.Show) the results are Label1 = x, Label2 = 0. But when I try "UserForm2.Show" from the Immediate window, everything works pretty good and I get the correct data.

What am I doing wrong?

The actual code:

If Sheets("SL").Range("B8").Value = True Then
   Label8.Caption = Find_cost(Sheets("SL").Range("b5").Value, Sheets("SL").Range("B4").Value, "ID")
   Label20.Caption = Find_cost(Sheets("SL").Range("b5").Value, Sheets("SL").Range("B4").Value, "ID") * Sheets("SL").Range("b4").Value
Else
   Label8.Caption = "none"
   Label20.Caption = "none"
End If

Where "Find_cost" is a custom function


问:
How to overlay views in other apps
Where do I start?

I don't know what functions or permissions will I use to make this.
No root required.

The view look like this, the camera button on the right side, it is floating and visible to other apps, if you push it, it will capture a screenshot.

Note: I will not make make a screenshot app, this is only an example of what I want to achieve.

答:
Try this:

```<code>    if(!isSystemAlertPermissionGranted(MainActivity.this)){
        requestSystemAlertPermission(MainActivity.this,1);
    }

    startService(new Intent(getApplicationContext(), Overlay.class));
</code>```

And:

```<code>public static void requestSystemAlertPermission(Activity context, int requestCode) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
        return;
    final String packageName = context == null ? context.getPackageName() : context.getPackageName();
    final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + packageName));
    if (context != null)
        context.startActivityForResult(intent, requestCode);
    else
        context.startActivityForResult(intent, requestCode);
}
@TargetApi(23)
public static boolean isSystemAlertPermissionGranted(Context context) {
    final boolean result = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || Settings.canDrawOverlays(context);
    return result;
}
</code>```

Title: How to overlay views in other apps

Body:
Try this:

    if(!isSystemAlertPermissionGranted(MainActivity.this)){
        requestSystemAlertPermission(MainActivity.this,1);
    }

    startService(new Intent(getApplicationContext(), Overlay.class));

And:

public static void requestSystemAlertPermission(Activity context, int requestCode) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
        return;
    final String packageName = context == null ? context.getPackageName() : context.getPackageName();
    final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + packageName));
    if (context != null)
        context.startActivityForResult(intent, requestCode);
    else
        context.startActivityForResult(intent, requestCode);
}
@TargetApi(23)
public static boolean isSystemAlertPermissionGranted(Context context) {
    final boolean result = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || Settings.canDrawOverlays(context);
    return result;
}