问:
How to turn this LinearLayout and RelativeLayout into ConstraintLayout?
I am trying to start using ConstrainLayout, but find it difficult to use. I have a layout for setting like screen, and it is using LinearLayout and RelativeLayout, very simple and easy to implement. Here is the layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tv_stay_awake"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Stay awake"
            android:padding="10dp"/>
        <Switch
            android:id="@+id/switch_stay_awake"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"/>
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tv_notification"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Enable Notification"
            android:padding="10dp"/>
        <Switch
            android:id="@+id/switch_notification"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"/>
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tv_location"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Enable location"
            android:padding="10dp"/>
        <Switch
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"/>
    </RelativeLayout>

</LinearLayout>
</code>```

and this is how it looks:

Now I want to build the same settings UI, but using ConstrainLayout, and here is the ConstrainLayout I have for this settings UI.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <TextView
        android:id="@+id/tv_stay_awake"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Stay awake"/>
    <Switch
        android:id="@+id/switch_stay_awake"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent" />

    <TextView
        android:id="@+id/tv_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Enable Notification"
        app:layout_constraintTop_toBottomOf="@+id/tv_stay_awake"/>

    <Switch
        android:id="@+id/switch_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch_stay_awake"/>

    <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Enable location"
        app:layout_constraintTop_toBottomOf="@+id/tv_notification"/>
    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch_notification"/>

</android.support.constraint.ConstraintLayout>
</code>```

and it turns out like this:

As you can see, the Switch buttons are not aligned with the TextView. How can I align them with the TextView on the same line level, so it will look the same as the one I did with LinearyLayout and RelativeLayout? I know I can put the TextView and Switch button in a RelativeLayout for each line, but if I do that, there is no reason to use the ConstrainLayout.

答:
You can try this .

Add app:layout_constraintBaseline_toBaselineOf="@+id/tv_notification" in your Switch XML code .

```<code><android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_stay_awake"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Stay awake"/>

    <Switch
        android:id="@+id/switch_stay_awake"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBaseline_toBaselineOf="@+id/tv_stay_awake"
        app:layout_constraintRight_toRightOf="parent"/>

    <TextView
        android:id="@+id/tv_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Enable Notification"
        app:layout_constraintTop_toBottomOf="@+id/tv_stay_awake"/>

    <Switch
        android:id="@+id/switch_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBaseline_toBaselineOf="@+id/tv_notification"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch_stay_awake"/>

    <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Enable location"
        app:layout_constraintTop_toBottomOf="@+id/tv_notification"/>

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBaseline_toBaselineOf="@+id/tv_location"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch_notification"/>

</android.support.constraint.ConstraintLayout>
</code>```

OUTPUT

Body:
I am trying to start using ConstrainLayout, but find it difficult to use. I have a layout for setting like screen, and it is using LinearLayout and RelativeLayout, very simple and easy to implement. Here is the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tv_stay_awake"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Stay awake"
            android:padding="10dp"/>
        <Switch
            android:id="@+id/switch_stay_awake"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"/>
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tv_notification"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Enable Notification"
            android:padding="10dp"/>
        <Switch
            android:id="@+id/switch_notification"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"/>
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tv_location"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Enable location"
            android:padding="10dp"/>
        <Switch
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"/>
    </RelativeLayout>

</LinearLayout>

and this is how it looks:

Now I want to build the same settings UI, but using ConstrainLayout, and here is the ConstrainLayout I have for this settings UI.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <TextView
        android:id="@+id/tv_stay_awake"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Stay awake"/>
    <Switch
        android:id="@+id/switch_stay_awake"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent" />

    <TextView
        android:id="@+id/tv_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Enable Notification"
        app:layout_constraintTop_toBottomOf="@+id/tv_stay_awake"/>

    <Switch
        android:id="@+id/switch_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch_stay_awake"/>

    <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Enable location"
        app:layout_constraintTop_toBottomOf="@+id/tv_notification"/>
    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch_notification"/>

</android.support.constraint.ConstraintLayout>

and it turns out like this:

As you can see, the Switch buttons are not aligned with the TextView. How can I align them with the TextView on the same line level, so it will look the same as the one I did with LinearyLayout and RelativeLayout? I know I can put the TextView and Switch button in a RelativeLayout for each line, but if I do that, there is no reason to use the ConstrainLayout.

Body:
You can try this .

Add app:layout_constraintBaseline_toBaselineOf="@+id/tv_notification" in your Switch XML code .

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_stay_awake"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Stay awake"/>

    <Switch
        android:id="@+id/switch_stay_awake"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBaseline_toBaselineOf="@+id/tv_stay_awake"
        app:layout_constraintRight_toRightOf="parent"/>

    <TextView
        android:id="@+id/tv_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Enable Notification"
        app:layout_constraintTop_toBottomOf="@+id/tv_stay_awake"/>

    <Switch
        android:id="@+id/switch_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBaseline_toBaselineOf="@+id/tv_notification"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch_stay_awake"/>

    <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Enable location"
        app:layout_constraintTop_toBottomOf="@+id/tv_notification"/>

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBaseline_toBaselineOf="@+id/tv_location"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch_notification"/>

</android.support.constraint.ConstraintLayout>

OUTPUT


来源: stackexchange

问:
Share `node_modules` between Meteor 1.6 server & Angular CLI client Angular-Meteor subprojects?
I have been using Meteor 1.3.x-1.5.x for the server in an Angular-Meteor project with a web client built via Angular CLI. Up until Meteor 1.6, I have been able to use a single node_modules directory shared via a symlink to reduce the size of and easily keep in sync the many shared dependencies between the client and server, following the example of the Angular-Meteor starter applications.

However, from the new package-lock.json file appearing in the root of the server directory, Meteor 1.6 appears to install its own dependencies in node_modules, including many  @angular/* dependencies, which result in me get the following errors due to the multiple, conflicting package installations. Any recommendations?

```<code>```
ERROR in ./clients/browser/main.ts
Module build failed: Error: Angular Compiler was detected but it was an instance of the wrong class.
This likely means you have several @ngtools/webpack packages installed. You can check this with `npm ls @ngtools/webpack`, and then remove the extra copies.
at Object.ngcLoader (/Users/keith.gillette/Code/TaskTrain/node_modules/@ngtools/webpack/src/loader.js:458:19)
@ multi webpack-dev-server/client?http://0.0.0.0:0 ./clients/browser/main.ts

ERROR in ./clients/browser/polyfills.ts
Module build failed: Error: Angular Compiler was detected but it was an instance of the wrong class.
This likely means you have several @ngtools/webpack packages installed. You can check this with `npm ls @ngtools/webpack`, and then remove the extra copies.
at Object.ngcLoader (/Users/keith.gillette/Code/TaskTrain/node_modules/@ngtools/webpack/src/loader.js:458:19)
@ multi ./clients/browser/polyfills.ts

ERROR in Error: Error encountered resolving symbol values statically.
 Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 194:50 in the original .ts file), resolving symbol NgModule in .../node_modules/ng-http-loader/node_modules/@angular/core/core.d.ts, resolving symbol NgHttpLoaderModule in .../node_modules/ng-http-loader/ng-http-loader.module.d.ts, resolving symbol NgHttpLoaderModule in .../node_modules/ng-http-loader/ng-http-loader.module.d.ts
at positionalError (.../node_modules/@angular/compiler/bundles/compiler.umd.js:25134:35)
at simplifyInContext (.../node_modules/@angular/compiler/bundles/compiler.umd.js:24977:27)
at StaticReflector.simplify (.../node_modules/@angular/compiler/bundles/compiler.umd.js:24991:13)
at StaticReflector.annotations (.../node_modules/@angular/compiler/bundles/compiler.umd.js:24418:41)
at _getNgModuleMetadata (../node_modules/@angular/compiler-cli/src/ngtools_impl.js:138:31)
at _extractLazyRoutesFromStaticModule (.../node_modules/@angular/compiler-cli/src/ngtools_impl.js:109:26)
at .../node_modules/@angular/compiler-cli/src/ngtools_impl.js:129:27
at Array.reduce (native)
at _extractLazyRoutesFromStaticModule (.../node_modules/@angular/compiler-cli/src/ngtools_impl.js:128:10)
at Object.listLazyRoutesOfModule (.../node_modules/@angular/compiler-cli/src/ngtools_impl.js:53:22)
at Function.NgTools_InternalApi_NG_2.listLazyRoutes (.../node_modules/@angular/compiler-cli/src/ngtools_api.js:91:39)
at AotPlugin._getLazyRoutesFromNgtools (.../node_modules/@angular/cli/node_modules/@ngtools/webpack/src/plugin.js:241:66)
at _donePromise.Promise.resolve.then.then.then.then.then (.../node_modules/@angular/cli/node_modules/@ngtools/webpack/src/plugin.js:495:24)
at process._tickCallback (internal/process/next_tick.js:109:7)
```
</code>```

答:
I was able to resolve this by:

updating to node@8.8.1 globally to match the version bundled with Meteor 1.6

updating to Meteor 1.6

adding symlinks to the root package.json & package-lock.json inside the Meteor directory

deleting the node_modules folder and performing an npm install on the root package.json

avoiding any calls to meteor npm install (which I had been doing in a postinstall npm script to build the bcrypt binary)

ContentLicense: CC BY-SA 3.0

Body:
I have been using Meteor 1.3.x-1.5.x for the server in an Angular-Meteor project with a web client built via Angular CLI. Up until Meteor 1.6, I have been able to use a single node_modules directory shared via a symlink to reduce the size of and easily keep in sync the many shared dependencies between the client and server, following the example of the Angular-Meteor starter applications.

However, from the new package-lock.json file appearing in the root of the server directory, Meteor 1.6 appears to install its own dependencies in node_modules, including many  @angular/* dependencies, which result in me get the following errors due to the multiple, conflicting package installations. Any recommendations?

```
ERROR in ./clients/browser/main.ts
Module build failed: Error: Angular Compiler was detected but it was an instance of the wrong class.
This likely means you have several @ngtools/webpack packages installed. You can check this with `npm ls @ngtools/webpack`, and then remove the extra copies.
at Object.ngcLoader (/Users/keith.gillette/Code/TaskTrain/node_modules/@ngtools/webpack/src/loader.js:458:19)
@ multi webpack-dev-server/client?http://0.0.0.0:0 ./clients/browser/main.ts

ERROR in ./clients/browser/polyfills.ts
Module build failed: Error: Angular Compiler was detected but it was an instance of the wrong class.
This likely means you have several @ngtools/webpack packages installed. You can check this with `npm ls @ngtools/webpack`, and then remove the extra copies.
at Object.ngcLoader (/Users/keith.gillette/Code/TaskTrain/node_modules/@ngtools/webpack/src/loader.js:458:19)
@ multi ./clients/browser/polyfills.ts

ERROR in Error: Error encountered resolving symbol values statically.
 Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 194:50 in the original .ts file), resolving symbol NgModule in .../node_modules/ng-http-loader/node_modules/@angular/core/core.d.ts, resolving symbol NgHttpLoaderModule in .../node_modules/ng-http-loader/ng-http-loader.module.d.ts, resolving symbol NgHttpLoaderModule in .../node_modules/ng-http-loader/ng-http-loader.module.d.ts
at positionalError (.../node_modules/@angular/compiler/bundles/compiler.umd.js:25134:35)
at simplifyInContext (.../node_modules/@angular/compiler/bundles/compiler.umd.js:24977:27)
at StaticReflector.simplify (.../node_modules/@angular/compiler/bundles/compiler.umd.js:24991:13)
at StaticReflector.annotations (.../node_modules/@angular/compiler/bundles/compiler.umd.js:24418:41)
at _getNgModuleMetadata (../node_modules/@angular/compiler-cli/src/ngtools_impl.js:138:31)
at _extractLazyRoutesFromStaticModule (.../node_modules/@angular/compiler-cli/src/ngtools_impl.js:109:26)
at .../node_modules/@angular/compiler-cli/src/ngtools_impl.js:129:27
at Array.reduce (native)
at _extractLazyRoutesFromStaticModule (.../node_modules/@angular/compiler-cli/src/ngtools_impl.js:128:10)
at Object.listLazyRoutesOfModule (.../node_modules/@angular/compiler-cli/src/ngtools_impl.js:53:22)
at Function.NgTools_InternalApi_NG_2.listLazyRoutes (.../node_modules/@angular/compiler-cli/src/ngtools_api.js:91:39)
at AotPlugin._getLazyRoutesFromNgtools (.../node_modules/@angular/cli/node_modules/@ngtools/webpack/src/plugin.js:241:66)
at _donePromise.Promise.resolve.then.then.then.then.then (.../node_modules/@angular/cli/node_modules/@ngtools/webpack/src/plugin.js:495:24)
at process._tickCallback (internal/process/next_tick.js:109:7)
```


问:
C++ Creating array based on what functions were called
For example lets say I have this simple code:

```<code>using namespace std;
char re = 'y';
void mult(int one, int two)
{
    int mult = 1;
    mult = one * two;
    cout << mult << endl;
}

void add(int one, int two)
{
    int add = 0;
    add = one + two;
    cout << add << endl;
}

void rep(int one, int two)
{
}

void ask()
{
    int re;
    cout << "do you want return to the menu? (1/2)" << endl;
    cin >> re;
}

int main()
{
    char re;
    int one;
    int two;

    cout << "enter the number one:" << endl;
    cin >> one;
    cout << "enter the number two:" << endl;
    cin >> two;
    cout << endl;

    cout << "Multiply - 1" << endl;
    cout << "Add      - 2" << endl;
    cout << "Reprint  - 3" << endl;
    cout << endl;
    int menu;
    if (re == 'y')
    {
        cout << "select the function ";
        cin >> menu;
        switch (menu)
        {
            case 1:
                mult(one, two);
                ask();
                break;
            case 2:
                add(one, two);
                ask();
                break;
            case 3:
                rep(one, two);
                break;
            default:
                cout << "no such thing" << endl;
                break;
        }
    }

    else if (re != 'y')
    {
    }
    return 0;
}
</code>```

I need a way function rep to print out the answer of previously called functions.

For example if function mult was called it should print mult answer, IF mult and add were called then it should print mult and add function answers, if only add then only add.

I was thinking about creating a zero array and changing it whether function one or two was called out, and then somehow call the answers out. But no idea how to do it.

答:
You could use a global variable.

```<code>int last_result = 0;
void mult(int a, int b)
{
  last_result = a * b;
  std::cout << last_result << std::endl;
}

void add(int a, int b)
{
  last_result = a + b;
  std::cout << last_result << std::endl;
}

void rep()
{
  std::cout << "Last result: " << last_result << std::endl;
}
</code>```

You could also have the mult and add functions return a result and store the result in main (and pass it to the rep function).

You could pass the last_result variable by reference to the add and mult functions.

Body:
For example lets say I have this simple code:

using namespace std;
char re = 'y';
void mult(int one, int two)
{
    int mult = 1;
    mult = one * two;
    cout << mult << endl;
}

void add(int one, int two)
{
    int add = 0;
    add = one + two;
    cout << add << endl;
}

void rep(int one, int two)
{
}

void ask()
{
    int re;
    cout << "do you want return to the menu? (1/2)" << endl;
    cin >> re;
}

int main()
{
    char re;
    int one;
    int two;

    cout << "enter the number one:" << endl;
    cin >> one;
    cout << "enter the number two:" << endl;
    cin >> two;
    cout << endl;

    cout << "Multiply - 1" << endl;
    cout << "Add      - 2" << endl;
    cout << "Reprint  - 3" << endl;
    cout << endl;
    int menu;
    if (re == 'y')
    {
        cout << "select the function ";
        cin >> menu;
        switch (menu)
        {
            case 1:
                mult(one, two);
                ask();
                break;
            case 2:
                add(one, two);
                ask();
                break;
            case 3:
                rep(one, two);
                break;
            default:
                cout << "no such thing" << endl;
                break;
        }
    }

    else if (re != 'y')
    {
    }
    return 0;
}

I need a way function rep to print out the answer of previously called functions.

For example if function mult was called it should print mult answer, IF mult and add were called then it should print mult and add function answers, if only add then only add.

I was thinking about creating a zero array and changing it whether function one or two was called out, and then somehow call the answers out. But no idea how to do it.

Body:
You could use a global variable.

int last_result = 0;
void mult(int a, int b)
{
  last_result = a * b;
  std::cout << last_result << std::endl;
}

void add(int a, int b)
{
  last_result = a + b;
  std::cout << last_result << std::endl;
}

void rep()
{
  std::cout << "Last result: " << last_result << std::endl;
}

You could also have the mult and add functions return a result and store the result in main (and pass it to the rep function).

You could pass the last_result variable by reference to the add and mult functions.


问:
How to feed a list of unquoted column names into `lapply` (so that I can use it with a `dplyr` function)
I am trying to write a function in tidyverse/dplyr that I want to eventually use with lapply (or map). (I had been working on it to answer this question, but came upon an interesting result/dead-end. Please don't mark this as a duplicate - this question is an extension/departure from the answers that you see there.)

Is there

1) a way to get a list of quoted variables to work inside a dplyr function

(and not use the deprecated SE_ functions)  or is there

2) some way to feed a list of unquoted strings through an lapply or map

I have used the Programming in Dplyr vignette to construct what I believe is a function most in line with the current standard
for working with the NSE.

The sample data:

```<code>sample_data <-
    read.table(text = "REVENUEID AMOUNT  YEAR REPORT_CODE PAYMENT_METHOD INBOUND_CHANNEL  AMOUNT_CAT
               1 rev-24985629     30  FY18           S          Check            Mail     25,50
               2 rev-22812413      1  FY16           Q          Other      Canvassing   0.01,10
               3 rev-23508794    100  FY17           Q    Credit_card             Web   100,250
               4 rev-23506121    300  FY17           S    Credit_card            Mail   250,500
               5 rev-23550444    100  FY17           S    Credit_card             Web   100,250
               6 rev-21508672     25  FY14           J          Check            Mail     25,50
               7 rev-24981769    500  FY18           S    Credit_card             Web 500,1e+03
               8 rev-23503684     50  FY17           R          Check            Mail     50,75
               9 rev-24982087     25  FY18           R          Check            Mail     25,50
               10 rev-24979834     50  FY18           R    Credit_card             Web    50,75
                      ", header = TRUE, stringsAsFactors = FALSE)
</code>```

A report generating function

```<code>report <- function(report_cat){
    report_cat <- enquo(report_cat)
    sample_data %>%
    group_by(!!report_cat, YEAR) %>%
    summarize(num=n(),total=sum(AMOUNT)) %>%
    rename(REPORT_VALUE = !!report_cat) %>%
    mutate(REPORT_CATEGORY := as.character(quote(!!report_cat))[2])
}
</code>```

Which works fine for generating a single report:

```<code>> report(REPORT_CODE)
# A tibble: 7 x 5
# Groups:   REPORT_VALUE [4]
  REPORT_VALUE  YEAR   num total REPORT_CATEGORY
         <chr> <chr> <int> <int>           <chr>
1            J  FY14     1    25     REPORT_CODE
2            Q  FY16     1     1     REPORT_CODE
3            Q  FY17     1   100     REPORT_CODE
4            R  FY17     1    50     REPORT_CODE
5            R  FY18     2    75     REPORT_CODE
6            S  FY17     2   400     REPORT_CODE
7            S  FY18     2   530     REPORT_CODE
</code>```

It is when I try and set up a list of all 4 of the reports to generate, that everything breaks down. (Though admittedly the code required in that last line of the function - to return a string with which to then fill the column - should be clue enough that I have wandered off in the wrong direction.)

```<code>#the other reports
cat.list <- c("REPORT_CODE","PAYMENT_METHOD","INBOUND_CHANNEL","AMOUNT_CAT")

# Applying and Mapping attempts
lapply(cat.list, report)
map_df(cat.list, report)
</code>```

Which results in:

```<code>> lapply(cat.list, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated

> map_df(cat.list, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated
</code>```

I have also tried to convert the list of strings to names before handing it over to apply and map:

```<code>library(rlang)
cat.names <- lapply(cat.list, sym)
lapply(cat.names, report)
map_df(cat.names, report)
</code>```

```<code>> lapply(cat.names, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated
> map_df(cat.names, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated
</code>```

In any case, the reason I am asking this question is that I think that I have written the function to the currently documented standards, but ultimately I can then see no way to utilize a member of the apply or even of the purrr::map family with such a function. Short of rewriting the function to use names like useR has done here https://stackoverflow.com/a/47316151/5088194 is there a way to get this function to work with apply or map?

I am hoping to see this as a result:

```<code># A tibble: 27 x 5
# Groups:   REPORT_VALUE [16]
   REPORT_VALUE  YEAR   num total REPORT_CATEGORY
          <chr> <chr> <int> <int>           <chr>
 1            J  FY14     1    25     REPORT_CODE
 2            Q  FY16     1     1     REPORT_CODE
 3            Q  FY17     1   100     REPORT_CODE
 4            R  FY17     1    50     REPORT_CODE
 5            R  FY18     2    75     REPORT_CODE
 6            S  FY17     2   400     REPORT_CODE
 7            S  FY18     2   530     REPORT_CODE
 8        Check  FY14     1    25  PAYMENT_METHOD
 9        Check  FY17     1    50  PAYMENT_METHOD
10        Check  FY18     2    55  PAYMENT_METHOD
# ... with 17 more rows
</code>```

答:
as.name will convert a string to a name and that can be passed to report:

```<code>lapply(cat.list, function(x) do.call("report", list(as.name(x))))
</code>```

character argument An alternative is to rewrite report so that it accepts a character string argument:

```<code>report_ch <- function(colname) {
    report_cat <- rlang::sym(colname)   # as.name(colname) would also work here
    sample_data %>%
                group_by(!!report_cat, YEAR) %>%
                summarize(num = n(), total = sum(AMOUNT)) %>%
                rename(REPORT_VALUE = !!report_cat) %>%
                mutate(REPORT_CATEGORY = colname)
}

lapply(cat.list, report_ch)
</code>```

wrapr An alternate approach is to rewrite report using the wrapr package which is an alternative to rlang/tidyeval:

```<code>library(dplyr)
library(wrapr)

report_wrapr <- function(colname)
  let(c(COLNAME = colname),
      sample_data %>%
                  group_by(COLNAME, YEAR) %>%
                  summarize(num = n(), total = sum(AMOUNT)) %>%
                  rename(REPORT_VALUE = COLNAME) %>%
                  mutate(REPORT_CATEGORY = colname)
   )

lapply(cat.list, report_wrapr)
</code>```

Of course, this whole problem would go away if you used a different framework, e.g.

plyr

```<code>library(plyr)

report_plyr <- function(colname)
  ddply(sample_data, c(REPORT_VALUE = colname, "YEAR"), function(x)
     data.frame(num = nrow(x), total = sum(x$AMOUNT), REPORT_CATEOGRY = colname))

lapply(cat.list, report_plyr)
</code>```

sqldf

```<code>library(sqldf)

report_sql <- function(colname, envir = parent.frame(), ...)
  fn$sqldf("select [$colname] REPORT_VALUE,
                   YEAR,
                   count(*) num,
                   sum(AMOUNT) total,
                   '$colname' REPORT_CATEGORY
            from sample_data
            group by [$colname], YEAR", envir = envir, ...)

lapply(cat.list, report_sql)
</code>```

base - by

```<code>report_base_by <- function(colname)
      do.call("rbind",
        by(sample_data, sample_data[c(colname, "YEAR")], function(x)
            data.frame(REPORT_VALUE = x[1, colname],
                       YEAR = x$YEAR[1],
                       num = nrow(x),
                       total = sum(x$AMOUNT),
                       REPORT_CATEGORY = colname)
         )
      )

lapply(cat.list, report_base_by)
</code>```

data.table The data.table package provides another alternative but that has already been covered by another answer.

Update: Added additional alternatives.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a function in tidyverse/dplyr that I want to eventually use with lapply (or map). (I had been working on it to answer this question, but came upon an interesting result/dead-end. Please don't mark this as a duplicate - this question is an extension/departure from the answers that you see there.)

Is there

1) a way to get a list of quoted variables to work inside a dplyr function

(and not use the deprecated SE_ functions)  or is there

2) some way to feed a list of unquoted strings through an lapply or map

I have used the Programming in Dplyr vignette to construct what I believe is a function most in line with the current standard
for working with the NSE.

The sample data:

sample_data <-
    read.table(text = "REVENUEID AMOUNT  YEAR REPORT_CODE PAYMENT_METHOD INBOUND_CHANNEL  AMOUNT_CAT
               1 rev-24985629     30  FY18           S          Check            Mail     25,50
               2 rev-22812413      1  FY16           Q          Other      Canvassing   0.01,10
               3 rev-23508794    100  FY17           Q    Credit_card             Web   100,250
               4 rev-23506121    300  FY17           S    Credit_card            Mail   250,500
               5 rev-23550444    100  FY17           S    Credit_card             Web   100,250
               6 rev-21508672     25  FY14           J          Check            Mail     25,50
               7 rev-24981769    500  FY18           S    Credit_card             Web 500,1e+03
               8 rev-23503684     50  FY17           R          Check            Mail     50,75
               9 rev-24982087     25  FY18           R          Check            Mail     25,50
               10 rev-24979834     50  FY18           R    Credit_card             Web    50,75
                      ", header = TRUE, stringsAsFactors = FALSE)

A report generating function

report <- function(report_cat){
    report_cat <- enquo(report_cat)
    sample_data %>%
    group_by(!!report_cat, YEAR) %>%
    summarize(num=n(),total=sum(AMOUNT)) %>%
    rename(REPORT_VALUE = !!report_cat) %>%
    mutate(REPORT_CATEGORY := as.character(quote(!!report_cat))[2])
}

Which works fine for generating a single report:

> report(REPORT_CODE)
# A tibble: 7 x 5
# Groups:   REPORT_VALUE [4]
  REPORT_VALUE  YEAR   num total REPORT_CATEGORY
         <chr> <chr> <int> <int>           <chr>
1            J  FY14     1    25     REPORT_CODE
2            Q  FY16     1     1     REPORT_CODE
3            Q  FY17     1   100     REPORT_CODE
4            R  FY17     1    50     REPORT_CODE
5            R  FY18     2    75     REPORT_CODE
6            S  FY17     2   400     REPORT_CODE
7            S  FY18     2   530     REPORT_CODE

It is when I try and set up a list of all 4 of the reports to generate, that everything breaks down. (Though admittedly the code required in that last line of the function - to return a string with which to then fill the column - should be clue enough that I have wandered off in the wrong direction.)

#the other reports
cat.list <- c("REPORT_CODE","PAYMENT_METHOD","INBOUND_CHANNEL","AMOUNT_CAT")

# Applying and Mapping attempts
lapply(cat.list, report)
map_df(cat.list, report)

Which results in:

> lapply(cat.list, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated

> map_df(cat.list, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated

I have also tried to convert the list of strings to names before handing it over to apply and map:

library(rlang)
cat.names <- lapply(cat.list, sym)
lapply(cat.names, report)
map_df(cat.names, report)

> lapply(cat.names, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated
> map_df(cat.names, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated

In any case, the reason I am asking this question is that I think that I have written the function to the currently documented standards, but ultimately I can then see no way to utilize a member of the apply or even of the purrr::map family with such a function. Short of rewriting the function to use names like useR has done here https://stackoverflow.com/a/47316151/5088194 is there a way to get this function to work with apply or map?

I am hoping to see this as a result:

# A tibble: 27 x 5
# Groups:   REPORT_VALUE [16]
   REPORT_VALUE  YEAR   num total REPORT_CATEGORY
          <chr> <chr> <int> <int>           <chr>
 1            J  FY14     1    25     REPORT_CODE
 2            Q  FY16     1     1     REPORT_CODE
 3            Q  FY17     1   100     REPORT_CODE
 4            R  FY17     1    50     REPORT_CODE
 5            R  FY18     2    75     REPORT_CODE
 6            S  FY17     2   400     REPORT_CODE
 7            S  FY18     2   530     REPORT_CODE
 8        Check  FY14     1    25  PAYMENT_METHOD
 9        Check  FY17     1    50  PAYMENT_METHOD
10        Check  FY18     2    55  PAYMENT_METHOD
# ... with 17 more rows

Body:
as.name will convert a string to a name and that can be passed to report:

lapply(cat.list, function(x) do.call("report", list(as.name(x))))

character argument An alternative is to rewrite report so that it accepts a character string argument:

report_ch <- function(colname) {
    report_cat <- rlang::sym(colname)   # as.name(colname) would also work here
    sample_data %>%
                group_by(!!report_cat, YEAR) %>%
                summarize(num = n(), total = sum(AMOUNT)) %>%
                rename(REPORT_VALUE = !!report_cat) %>%
                mutate(REPORT_CATEGORY = colname)
}

lapply(cat.list, report_ch)

wrapr An alternate approach is to rewrite report using the wrapr package which is an alternative to rlang/tidyeval:

library(dplyr)
library(wrapr)

report_wrapr <- function(colname)
  let(c(COLNAME = colname),
      sample_data %>%
                  group_by(COLNAME, YEAR) %>%
                  summarize(num = n(), total = sum(AMOUNT)) %>%
                  rename(REPORT_VALUE = COLNAME) %>%
                  mutate(REPORT_CATEGORY = colname)
   )

lapply(cat.list, report_wrapr)

Of course, this whole problem would go away if you used a different framework, e.g.

plyr

library(plyr)

report_plyr <- function(colname)
  ddply(sample_data, c(REPORT_VALUE = colname, "YEAR"), function(x)
     data.frame(num = nrow(x), total = sum(x$AMOUNT), REPORT_CATEOGRY = colname))

lapply(cat.list, report_plyr)

sqldf

library(sqldf)

report_sql <- function(colname, envir = parent.frame(), ...)
  fn$sqldf("select [$colname] REPORT_VALUE,
                   YEAR,
                   count(*) num,
                   sum(AMOUNT) total,
                   '$colname' REPORT_CATEGORY
            from sample_data
            group by [$colname], YEAR", envir = envir, ...)

lapply(cat.list, report_sql)

base - by

report_base_by <- function(colname)
      do.call("rbind",
        by(sample_data, sample_data[c(colname, "YEAR")], function(x)
            data.frame(REPORT_VALUE = x[1, colname],
                       YEAR = x$YEAR[1],
                       num = nrow(x),
                       total = sum(x$AMOUNT),
                       REPORT_CATEGORY = colname)
         )
      )

lapply(cat.list, report_base_by)

data.table The data.table package provides another alternative but that has already been covered by another answer.

Update: Added additional alternatives.


问:
Web Api 2 : How to make ModelState recognize optional parameters?
I currently have this controller

```<code>[RoutePrefix("api/Home")]
public class HomeController : ApiController
{

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id, [FromUri]int? AnotherId ){

        if (!ModelState.IsValid) //From ApiController.ModelState
        {
            return BadRequest(ModelState);
        }
    }
}
</code>```

When I try to access /api/Home?id=&AnotherId=1 or /api/Home?id=1&AnotherId=, it returns the following error A value is required but was not present in the request. I have clearly indicated that id or AnotherId should be an optional value.

Why is the ModelState not valid? What am I doing wrong?

答:
It seems like ModelState in Web Api doesn't recognize this kind of parameter ?a=&b=. Not exactly sure why but we need to add a [BinderType] to [FormUri] like this:

```<code>[RoutePrefix("api/Home")]
public class HomeController : ApiController
{

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetByIdAndAnotherID(
        [FromUri(BinderType = typeof(TypeConverterModelBinder))]int? ID = null,
        [FromUri(BinderType = typeof(TypeConverterModelBinder))]int? AnotherID = null){

        if (!ModelState.IsValid) //From ApiController.ModelState
        {
            return BadRequest(ModelState);
        }
    }
}
</code>```

Body:
I currently have this controller

[RoutePrefix("api/Home")]
public class HomeController : ApiController
{

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id, [FromUri]int? AnotherId ){

        if (!ModelState.IsValid) //From ApiController.ModelState
        {
            return BadRequest(ModelState);
        }
    }
}

When I try to access /api/Home?id=&AnotherId=1 or /api/Home?id=1&AnotherId=, it returns the following error A value is required but was not present in the request. I have clearly indicated that id or AnotherId should be an optional value.

Why is the ModelState not valid? What am I doing wrong?

Body:
It seems like ModelState in Web Api doesn't recognize this kind of parameter ?a=&b=. Not exactly sure why but we need to add a [BinderType] to [FormUri] like this:

[RoutePrefix("api/Home")]
public class HomeController : ApiController
{

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetByIdAndAnotherID(
        [FromUri(BinderType = typeof(TypeConverterModelBinder))]int? ID = null,
        [FromUri(BinderType = typeof(TypeConverterModelBinder))]int? AnotherID = null){

        if (!ModelState.IsValid) //From ApiController.ModelState
        {
            return BadRequest(ModelState);
        }
    }
}


问:
9933272057275866 is it a magic number?
I faced problem and I can't quite explain it. Actually I'm quite surprised.
When I try to increment the number 9933272057275866 by 1, it automatically adds 2!!!
Please see following code:

```<code>let test = 9933272057275866;
let test2 = test+1;
console.log('Before:', test);
console.log('After:', test2);
console.log('Sub:', test2-test);
</code>```

And respective output:

```<code>Before: 9933272057275866
After: 9933272057275868
Sub: 2
</code>```

How can this be possible?

Environment is Javascript. I found this problem when I submitted a challenge at Hackerrank, then I also tried to do the same in my own environment on node.js. Same result!

What is happening?

答:
Basically, it's because 64 bits (*) aren't enough to represent the number accurately.

4341 A521 1037 32ED: 9.933272057275866 ⨉ 1015

4341 A521 1037 32EE: 9.933272057275868 ⨉ 1015

See how it skips one integer between them. In IEEE 754, the higher you go, the more the numbers are spread out along the number line. One thing to keep in mind is that floating point numbers are approximations. This is why you get this result:

```<code>0.1 + 0.2 === 0.3    // false
</code>```

The max safe integer in IEEE 754 is 9007199254740991.

More fun facts with floating point arithmetics:

```<code>A + B == B + A              // true, commutative, except when A or B is NaN
(A + B) + C == A + (B + C)  // false, not associative
</code>```

* It is worth mentioning that numbers in JavaScript (ECMAScript) are represented as 64 bit IEEE 754 doubles. ref

Title: 9933272057275866 is it a magic number?

Body:
I faced problem and I can't quite explain it. Actually I'm quite surprised.
When I try to increment the number 9933272057275866 by 1, it automatically adds 2!!!
Please see following code:

let test = 9933272057275866;
let test2 = test+1;
console.log('Before:', test);
console.log('After:', test2);
console.log('Sub:', test2-test);

And respective output:

Before: 9933272057275866
After: 9933272057275868
Sub: 2

How can this be possible?

Environment is Javascript. I found this problem when I submitted a challenge at Hackerrank, then I also tried to do the same in my own environment on node.js. Same result!

What is happening?

Body:
Basically, it's because 64 bits (*) aren't enough to represent the number accurately.

4341 A521 1037 32ED: 9.933272057275866 ⨉ 1015

4341 A521 1037 32EE: 9.933272057275868 ⨉ 1015

See how it skips one integer between them. In IEEE 754, the higher you go, the more the numbers are spread out along the number line. One thing to keep in mind is that floating point numbers are approximations. This is why you get this result:

0.1 + 0.2 === 0.3    // false

The max safe integer in IEEE 754 is 9007199254740991.

More fun facts with floating point arithmetics:

A + B == B + A              // true, commutative, except when A or B is NaN
(A + B) + C == A + (B + C)  // false, not associative

* It is worth mentioning that numbers in JavaScript (ECMAScript) are represented as 64 bit IEEE 754 doubles. ref


问:
Visual Studio loading the right (x86 or x64) dll
I'm working on Visual Studio in an x86. I would like to build my application for both x32 and x64. But I need to use the sqlite .net connector which has a dll for x86 apps and another dll for x64 apps.

How do I configure my Visual Studio to load a reference when my configuration is x64 and another when my configuration is x86?

答: You can also build your application for "Any CPU" and dynamically choose which DLL to load.</p>

ContentLicense: CC BY-SA 2.5


问:
Why can pointers be NULL
In C or C++, isn't NULL just the constant integer 0? Why are we allowed to assign some pointer to the value NULL if it a constant integer? Wouldn't a compiler say that the two types don't match? </p>

答:
The interpretation of the constant 0 depends on the context. If it's being used in a context where a number is required, it's the number zero. If it's being used in a context where a pointer is required, it's treated as a null pointer. So if you have the code:

```<code>int n = 0; // assigns zero
int *p = 0; // assigns null pointer
somefunc((char *)0); // passes null pointer to the function
</code>```

In C, the macro NULL is permitted to expand into either an integer constant 0 or such a constant cast to void *. In C++ pre-11, it can expand into either an integer constant that evaluates to 0. In C++-11 it can expand into an integer literal with value 0 or a prvalue of type std::nullptr_t (e.g. nullptr).

See http://en.cppreference.com/w/cpp/types/NULL for the C++ description, http://en.cppreference.com/w/c/types/NULL for the C description.

Title: Why can pointers be NULL

Body:
The interpretation of the constant 0 depends on the context. If it's being used in a context where a number is required, it's the number zero. If it's being used in a context where a pointer is required, it's treated as a null pointer. So if you have the code:

int n = 0; // assigns zero
int *p = 0; // assigns null pointer
somefunc((char *)0); // passes null pointer to the function

In C, the macro NULL is permitted to expand into either an integer constant 0 or such a constant cast to void *. In C++ pre-11, it can expand into either an integer constant that evaluates to 0. In C++-11 it can expand into an integer literal with value 0 or a prvalue of type std::nullptr_t (e.g. nullptr).

See http://en.cppreference.com/w/cpp/types/NULL for the C++ description, http://en.cppreference.com/w/c/types/NULL for the C description.


问:
Why isn't 'false' equal to 'nil'?
false is not equal to nil, for example:

```<code>false == nil # => false
</code>```

The same goes for false and 0:

```<code>false == 0 # => false
</code>```

You get the same result for nil and 0:

```<code>nil == 0 # => false
</code>```

Why does Ruby act like this?

答:
Nil and False (Equality)

Despite what many people new to the language may expect, nil and false are objects rather than language keywords. Consider FalseClass which says:

The global value false is the only instance of class FalseClass and represents a logically false value in boolean expressions.

Likewise, NilClass is:

[t]he class of the singleton object nil.

When you use a method like Comparable#== to compare them, Ruby invokes the spaceship operator <=> on the instances since neither class defines the #== method. Because nil and false are not the same objects, and because neither overrides the basic equality operator, the expression false == nil will always be false.

Likewise, an Integer like 0 is neither an instance of FalseClass nor NilClass. Both false == 0 and nil == 0 are therefore also false because neither instance evaluates to zero.

Truthy and Falsey (Conditionals)

For branching purposes, both false and nil evaluate as false in a conditional expression. Everything else evaluates as true.

Consider the following non-idiomatic, contrived, but hopefully illustrative example of Ruby's basic truth tables:

```<code>def truth_table value
  if value
    true
  else
    false
  end
end

truth_table nil
#=> false

truth_table false
#=> false

truth_table true
#=> true

truth_table 'a'
#=> true

truth_table 0
#=> true

truth_table 1
#=> true
</code>```

Boolean Evaluation

Nil and false are semantically different in Ruby, and descend from different base classes. They are also not equal to each other. However, they can both be treated as "not true" for branching purposes or within a Boolean context. For example, consider the following idioms for casting a result as a Boolean true or false value:

```<code>!(nil)
#=> true

!!(nil)
#=> false
</code>```

You can use this idiom to shorten the previous truth table example to:

```<code># Convert any value to a Boolean.
def truth_table value
  !!value
end

# Test our truth table again in a more compact but less readable way.
table = {}
[nil, false, true, 'a', 0, 1].map { |v| table[v] = truth_table(v) }; table
#=> {nil=>false, false=>false, true=>true, "a"=>true, 0=>true, 1=>true}
</code>```

Title: Why isn't 'false' equal to 'nil'?

Body:
false is not equal to nil, for example:

false == nil # => false

The same goes for false and 0:

false == 0 # => false

You get the same result for nil and 0:

nil == 0 # => false

Why does Ruby act like this?

Body:
Nil and False (Equality)

Despite what many people new to the language may expect, nil and false are objects rather than language keywords. Consider FalseClass which says:

The global value false is the only instance of class FalseClass and represents a logically false value in boolean expressions.

Likewise, NilClass is:

[t]he class of the singleton object nil.

When you use a method like Comparable#== to compare them, Ruby invokes the spaceship operator <=> on the instances since neither class defines the #== method. Because nil and false are not the same objects, and because neither overrides the basic equality operator, the expression false == nil will always be false.

Likewise, an Integer like 0 is neither an instance of FalseClass nor NilClass. Both false == 0 and nil == 0 are therefore also false because neither instance evaluates to zero.

Truthy and Falsey (Conditionals)

For branching purposes, both false and nil evaluate as false in a conditional expression. Everything else evaluates as true.

Consider the following non-idiomatic, contrived, but hopefully illustrative example of Ruby's basic truth tables:

def truth_table value
  if value
    true
  else
    false
  end
end

truth_table nil
#=> false

truth_table false
#=> false

truth_table true
#=> true

truth_table 'a'
#=> true

truth_table 0
#=> true

truth_table 1
#=> true

Boolean Evaluation

Nil and false are semantically different in Ruby, and descend from different base classes. They are also not equal to each other. However, they can both be treated as "not true" for branching purposes or within a Boolean context. For example, consider the following idioms for casting a result as a Boolean true or false value:

!(nil)
#=> true

!!(nil)
#=> false

You can use this idiom to shorten the previous truth table example to:

# Convert any value to a Boolean.
def truth_table value
  !!value
end

# Test our truth table again in a more compact but less readable way.
table = {}
[nil, false, true, 'a', 0, 1].map { |v| table[v] = truth_table(v) }; table
#=> {nil=>false, false=>false, true=>true, "a"=>true, 0=>true, 1=>true}


问:
Scrapy: USER_AGENT and ROBOTSTXT_OBEY are properly set, but I still get error 403
Hello and thanks in advance for the help or direction you can bring. This is my scraper:

```<code>import scrapy
class RakutenSpider(scrapy.Spider):
    name = "rak"
    allowed_domains = ["rakuten.com"]
    start_urls = ['https://www.rakuten.com/deals?omadtrack=hp_deals_viewmore']
    def parse(self, response):
        for sel in response.xpath('//div[@class="page-bottom"]/div'):
            yield {
                'titles': sel.xpath("//div[@class='slider-prod-title']").extract_first(),
                'prices': sel.xpath("//span[@class='price-bold']").extract_first(),
                'images': sel.xpath("//div[@class='deal-img']/img").extract_first()
            }
</code>```

And this is part of my settings.py

```<code>USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
CONCURRENT_REQUESTS = 1
DOWNLOAD_DELAY = 5
# Obey robots.txt rules
ROBOTSTXT_OBEY = 'False'
</code>```

and this is part of the log:

```<code>DEBUG: Crawled (403) <GET https://www.rakuten.com/deals?omadtrack=hp_deals_viewmore> (referer: None)
</code>```

I have tried almost all solutions I found in s/o

log file: This is a new log after installing Firefox driver. Now I get an ERROR: Error downloading https://www.rakuten.com/deals?omadtrack=hp_deals_viewmore>

```<code>2017-11-17 00:38:45 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: scrapybot)
2017-11-17 00:38:45 [scrapy.utils.log] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'deals.spiders', 'CONCURRENT_REQUESTS': 1, 'SPIDER_MODULES': ['deals.spiders'], 'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36', 'TELNETCONSOLE_ENABLED': False, 'DOWNLOAD_DELAY': 5}
2017-11-17 00:38:45 [py.warnings] WARNING: :0: UserWarning: You do not have a working installation of the service_identity module: 'No module named cryptography.x509'.  Please install it from <https://pypi.python.org/pypi/service_identity> and make sure all of its dependencies are satisfied.  Without the service_identity module and a recent enough pyOpenSSL to support it, Twisted can perform only rudimentary TLS client hostname verification.  Many valid certificate/hostname mappings may be rejected.

2017-11-17 00:38:45 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.feedexport.FeedExporter',
 'scrapy.extensions.memusage.MemoryUsage',
 'scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.corestats.CoreStats']
2017-11-17 00:38:45 [scrapy.middleware] INFO: Enabled downloader middlewares:
['deals.middlewares.JSMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-11-17 00:38:45 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-11-17 00:38:45 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2017-11-17 00:38:45 [scrapy.core.engine] INFO: Spider opened
2017-11-17 00:38:45 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-11-17 00:38:45 [scrapy.core.scraper] ERROR: Error downloading <GET https://www.rakuten.com/deals?omadtrack=hp_deals_viewmore>
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1128, in _inlineCallbacks
    result = g.send(result)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/core/downloader/middleware.py", line 37, in process_request
    response = yield method(request=request, spider=spider)
  File "/home/seealldeals/tmp/scrapy/deals/deals/middlewares.py", line 63, in process_request
    driver = webdriver.Firefox()
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 144, in __init__
    self.service.start()
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 74, in start
    stdout=self.log_file, stderr=self.log_file)
  File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception
OSError: [Errno 8] Exec format error
2017-11-17 00:38:45 [scrapy.core.engine] INFO: Closing spider (finished)
2017-11-17 00:38:45 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/exception_count': 1,
 'downloader/exception_type_count/exceptions.OSError': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 11, 17, 5, 38, 45, 328366),
 'log_count/ERROR': 1,
 'log_count/INFO': 7,
 'log_count/WARNING': 1,
 'memusage/max': 33509376,
 'memusage/startup': 33509376,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 11, 17, 5, 38, 45, 112667)}
2017-11-17 00:38:45 [scrapy.core.engine] INFO: Spider closed (finished)
</code>```

答:
What's wrong

rakuten.com had integrated with Google Analytics which has anti-spider feature.

If your request can't process rakuten.com's analytics.js properly, you will be blocked from the site and have a 403 error code.

How to fix it

Use Javascript rendering technique

Solution 1: (Integrate scrapy with scrapy-splash)

Here is Scrapy-splash github repository

Install scrapy-splash from pypi:

```<code>pip install scrapy-splash
</code>```

Install Docker to your machine

Run a scrapy-splash container:

```<code>docker run -p 8050:8050 scrapinghub/splash
</code>```

Add following lines to your settings.py

```<code>SPLASH_URL = 'http://192.168.59.103:8050'
</code>```

Append splash download middleware to your settings.py

```<code>DOWNLOADER_MIDDLEWARES = {
    'scrapy_splash.SplashCookiesMiddleware': 723,
    'scrapy_splash.SplashMiddleware': 725,
    'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}
</code>```

Change your spider's code to

```<code>import scrapy
from scrapy_splash import SplashRequest

class RakutenSpider(scrapy.Spider):
    name = "rak"
    allowed_domains = ["rakuten.com"]
    start_urls = ['https://www.rakuten.com/deals?omadtrack=hp_deals_viewmore']

    def start_requests(self):
        for url in self.start_urls:
            yield SplashRequest(url, self.parse, args={'wait': 0.5})

    def parse(self, response):
        for sel in response.xpath('//div[@class="page-bottom"]/div'):
            yield {
                'titles': sel.xpath("//div[@class='slider-prod-title']").extract_first(),
                'prices': sel.xpath("//span[@class='price-bold']").extract_first(),
                'images': sel.xpath("//div[@class='deal-img']/img").extract_first()
            }
</code>```

Solution 2: (Integrate scrapy with selenium webdriver as a middleware)

Selenium web driver python binding documentation

Install Selenium from pypi:

```<code>pip install selenium
</code>```

If you want to use Firefox Browser, Install Firefox's Geckodriver to your PATH.

Download Mozilla Geckodriver here

If you want to use Chrome Browser, Install Chrome driver to your PATH.

Download Chromedriver

If you want to use PhantomJS Browser, Install phantomJS from Homebrew.

```<code>   brew install phantomjs
</code>```

Add a JSmiddleware class to your middlewares.py

```<code>    from scrapy.http import HtmlResponse
    from selenium import webdriver

    class JSMiddleware(object):
        def process_request(self, request, spider):
            driver = webdriver.Firefox()
            driver.get(request.url)

            body = driver.page_source
            return HtmlResponse(driver.current_url, body=body, encoding='utf-8', request=request)
</code>```

Append selenium download middleware to your settings.py

```<code>    DOWNLOADER_MIDDLEWARES = {
        'youproject.middlewares.JSMiddleware': 200
    }
</code>```

Use your original spider's code

```<code>    import scrapy

    class RakutenSpider(scrapy.Spider):
        name = "rak"
        allowed_domains = ["rakuten.com"]
        start_urls = ['https://www.rakuten.com/deals?omadtrack=hp_deals_viewmore']

        def parse(self, response):
            for sel in response.xpath('//div[@class="page-bottom"]/div'):
                yield {
                    'titles': sel.xpath("//div[@class='slider-prod-title']").extract_first(),
                    'prices': sel.xpath("//span[@class='price-bold']").extract_first(),
                    'images': sel.xpath("//div[@class='deal-img']/img").extract_first()
                }
</code>```

More

If you wan to use Chrome Browser with Headless mode, check this tutorial

Body:
Hello and thanks in advance for the help or direction you can bring. This is my scraper:

import scrapy
class RakutenSpider(scrapy.Spider):
    name = "rak"
    allowed_domains = ["rakuten.com"]
    start_urls = ['https://www.rakuten.com/deals?omadtrack=hp_deals_viewmore']
    def parse(self, response):
        for sel in response.xpath('//div[@class="page-bottom"]/div'):
            yield {
                'titles': sel.xpath("//div[@class='slider-prod-title']").extract_first(),
                'prices': sel.xpath("//span[@class='price-bold']").extract_first(),
                'images': sel.xpath("//div[@class='deal-img']/img").extract_first()
            }

And this is part of my settings.py

USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
CONCURRENT_REQUESTS = 1
DOWNLOAD_DELAY = 5
# Obey robots.txt rules
ROBOTSTXT_OBEY = 'False'

and this is part of the log:

DEBUG: Crawled (403) <GET https://www.rakuten.com/deals?omadtrack=hp_deals_viewmore> (referer: None)

I have tried almost all solutions I found in s/o

log file: This is a new log after installing Firefox driver. Now I get an ERROR: Error downloading https://www.rakuten.com/deals?omadtrack=hp_deals_viewmore>

2017-11-17 00:38:45 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: scrapybot)
2017-11-17 00:38:45 [scrapy.utils.log] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'deals.spiders', 'CONCURRENT_REQUESTS': 1, 'SPIDER_MODULES': ['deals.spiders'], 'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36', 'TELNETCONSOLE_ENABLED': False, 'DOWNLOAD_DELAY': 5}
2017-11-17 00:38:45 [py.warnings] WARNING: :0: UserWarning: You do not have a working installation of the service_identity module: 'No module named cryptography.x509'.  Please install it from <https://pypi.python.org/pypi/service_identity> and make sure all of its dependencies are satisfied.  Without the service_identity module and a recent enough pyOpenSSL to support it, Twisted can perform only rudimentary TLS client hostname verification.  Many valid certificate/hostname mappings may be rejected.

2017-11-17 00:38:45 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.feedexport.FeedExporter',
 'scrapy.extensions.memusage.MemoryUsage',
 'scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.corestats.CoreStats']
2017-11-17 00:38:45 [scrapy.middleware] INFO: Enabled downloader middlewares:
['deals.middlewares.JSMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-11-17 00:38:45 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-11-17 00:38:45 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2017-11-17 00:38:45 [scrapy.core.engine] INFO: Spider opened
2017-11-17 00:38:45 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-11-17 00:38:45 [scrapy.core.scraper] ERROR: Error downloading <GET https://www.rakuten.com/deals?omadtrack=hp_deals_viewmore>
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1128, in _inlineCallbacks
    result = g.send(result)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/core/downloader/middleware.py", line 37, in process_request
    response = yield method(request=request, spider=spider)
  File "/home/seealldeals/tmp/scrapy/deals/deals/middlewares.py", line 63, in process_request
    driver = webdriver.Firefox()
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 144, in __init__
    self.service.start()
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 74, in start
    stdout=self.log_file, stderr=self.log_file)
  File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception
OSError: [Errno 8] Exec format error
2017-11-17 00:38:45 [scrapy.core.engine] INFO: Closing spider (finished)
2017-11-17 00:38:45 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/exception_count': 1,
 'downloader/exception_type_count/exceptions.OSError': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 11, 17, 5, 38, 45, 328366),
 'log_count/ERROR': 1,
 'log_count/INFO': 7,
 'log_count/WARNING': 1,
 'memusage/max': 33509376,
 'memusage/startup': 33509376,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 11, 17, 5, 38, 45, 112667)}
2017-11-17 00:38:45 [scrapy.core.engine] INFO: Spider closed (finished)

Body:
What's wrong

rakuten.com had integrated with Google Analytics which has anti-spider feature.

If your request can't process rakuten.com's analytics.js properly, you will be blocked from the site and have a 403 error code.

How to fix it

Use Javascript rendering technique

Solution 1: (Integrate scrapy with scrapy-splash)

Here is Scrapy-splash github repository

Install scrapy-splash from pypi:

pip install scrapy-splash

Install Docker to your machine

Run a scrapy-splash container:

docker run -p 8050:8050 scrapinghub/splash

Add following lines to your settings.py

SPLASH_URL = 'http://192.168.59.103:8050'

Append splash download middleware to your settings.py

DOWNLOADER_MIDDLEWARES = {
    'scrapy_splash.SplashCookiesMiddleware': 723,
    'scrapy_splash.SplashMiddleware': 725,
    'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}

Change your spider's code to

import scrapy
from scrapy_splash import SplashRequest

class RakutenSpider(scrapy.Spider):
    name = "rak"
    allowed_domains = ["rakuten.com"]
    start_urls = ['https://www.rakuten.com/deals?omadtrack=hp_deals_viewmore']

    def start_requests(self):
        for url in self.start_urls:
            yield SplashRequest(url, self.parse, args={'wait': 0.5})

    def parse(self, response):
        for sel in response.xpath('//div[@class="page-bottom"]/div'):
            yield {
                'titles': sel.xpath("//div[@class='slider-prod-title']").extract_first(),
                'prices': sel.xpath("//span[@class='price-bold']").extract_first(),
                'images': sel.xpath("//div[@class='deal-img']/img").extract_first()
            }

Solution 2: (Integrate scrapy with selenium webdriver as a middleware)

Selenium web driver python binding documentation

Install Selenium from pypi:

pip install selenium

If you want to use Firefox Browser, Install Firefox's Geckodriver to your PATH.

Download Mozilla Geckodriver here

If you want to use Chrome Browser, Install Chrome driver to your PATH.

Download Chromedriver

If you want to use PhantomJS Browser, Install phantomJS from Homebrew.

   brew install phantomjs

Add a JSmiddleware class to your middlewares.py

    from scrapy.http import HtmlResponse
    from selenium import webdriver

    class JSMiddleware(object):
        def process_request(self, request, spider):
            driver = webdriver.Firefox()
            driver.get(request.url)

            body = driver.page_source
            return HtmlResponse(driver.current_url, body=body, encoding='utf-8', request=request)

Append selenium download middleware to your settings.py

    DOWNLOADER_MIDDLEWARES = {
        'youproject.middlewares.JSMiddleware': 200
    }

Use your original spider's code

    import scrapy

    class RakutenSpider(scrapy.Spider):
        name = "rak"
        allowed_domains = ["rakuten.com"]
        start_urls = ['https://www.rakuten.com/deals?omadtrack=hp_deals_viewmore']

        def parse(self, response):
            for sel in response.xpath('//div[@class="page-bottom"]/div'):
                yield {
                    'titles': sel.xpath("//div[@class='slider-prod-title']").extract_first(),
                    'prices': sel.xpath("//span[@class='price-bold']").extract_first(),
                    'images': sel.xpath("//div[@class='deal-img']/img").extract_first()
                }

More

If you wan to use Chrome Browser with Headless mode, check this tutorial


问:
Allocate EIP to EC2 instance
Attempting to associate an EIP (console allocated but not attached to any instance) to a running instance.  This instance has an IAM policy that allows it to AllocateAddress, AssociateAddress, DescribeInstances, DisassociateAddress, DescribeInstances, and iam:PassRole.

Expect to be able to call ec2-associate-address -i i-some_instance_id some_eip.

[NOTE]: some-eip actually does exist. I can see it on the aws dashboard

Yet keep getting the error Client.AuthFailure: The address 'some_eip' does not belong to you.

Also when I attempt to run ec2-describe-addresses some_eip I get this response Client.InvalidAddress.NotFound: Address 'some_eip' not found.

On the other hand, I am able to run ec2-describe-instances --region us-east-1 as that returns all the instances in the supplied region.

The role was setup by our SysAdmin - and his permissions are different from mine. Would the above errors have anything to do with us having different user permissions?

答:
This took a while but finally figured out region needs to specified for this to work. So correct method call is ec2-associate-address -i i-some_instance_id some_eip --region some_region.

The documentation for the method ec2-associate-address ec2-api-tools does not indicate this though (thanks amazon).

PS: Please see the comments by John Rotenstein regarding the use of ec2-api-tools vs awscli. I am leaving this answer up because the tool I used was ec2-api-tools and not awscli.

Title: Allocate EIP to EC2 instance


问:
Redux (with React) Reducer switch statement NOT updating State
As the title suggests, I'm struggling to get my Redux state to update using the reducer. I'm also using Redux with React. In this context, I'm using the Redux state to hold the boolean value of whether a user is signed in with a JWT token. I'm fairly certain I have my reducers correctly set up because I can console log out the initial authenticated state which is set to false by default. BUT when I run the AUTH_USER action which tells the reducer to update the state to have authenticated = true, nothing happens. When logging the redux state of auth, it remains false even after I've run the action for AUTH_USER. It seems to make it into the switch statement in the reducer correctly because the console.log shows up in the terminal. I am getting my console log from my header component's componentDidMount lifecycle method which renders on every part of my React application.

Index.js of Reducers (/src/reducers/index.js)

```<code>import { combineReducers } from 'redux';
import authReducer from './reducer_auth';

const rootReducer = combineReducers({
  auth: authReducer
});

export default rootReducer;
</code>```

The Authentication Reducer (/src/reducers/reducer_auth.js)

```<code>import { AUTH_USER, DEAUTH_USER } from '../actions/types';

export default function (state = { authenticated: false, error: "" },
action) {
  switch(action.type) {
    case AUTH_USER:
      console.log('THIS DOES SHOW UP IN CONSOLE')
      return {...state, error: "", authenticated: true };
    case DEAUTH_USER:
      return {...state, error: "", authenticated: false };
    default:
      return state;
  }
}
</code>```

The Action Creator for signing in (/src/actions/index.js)

```<code>import axios from 'axios';
import history from '../utils/historyUtils';

import { AUTH_USER, DEAUTH_USER } from './types';

const ROOT_URL = 'http://localhost:8888';

export function signInUser(username, password) {
  const signInRequest = axios.post(`${ROOT_URL}/wp-json/jwt-auth/v1/token`, {
    "username": username,
    "password": password
  });

  return (dispatch) => {
    return signInRequest.then(response => {
      localStorage.setItem('token', JSON.stringify(response.data.token));

      dispatch({
        type: AUTH_USER,
        payload: { authenticated : true }
      })

      history.push('/');
      history.go();
    })
  }
}
</code>```

Header Component (/src/containers/header.js)

```<code>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { signOutUser } from '../actions';

import '../styles/header.css';

class Header extends Component {
  componentDidMount() {
    console.log('authenticated from header: ', this.props.authenticated)
  }

  handleLogout(event) {
    event.preventDefault();
    localStorage.removeItem('token');

  }

  render() {
    return (
      <div className="container">
        <header>
          <div id="branding">
            <h1><Link to="/">INSERT BRAND HERE</Link></h1>
          </div>
          <nav>
            <ul>
              <li><Link to="/">Home</Link></li>
              <li><Link to="/contact">Contact</Link></li>
              <li><Link to="/services">Services</Link></li>
              <li><Link to="/Portfolio">Portfolio</Link></li>
              <li><Link to="/about">About</Link></li>
              <li><Link to="/blog">Blog</Link></li>
              {/* {this.props.authenticated ? <li>Logout</li> : <li><Link to="/signin">Login</Link></li>} */}
              <li><Link to="/signin">Login</Link></li>
            </ul>
          </nav>
        </header>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    authenticated: state.auth
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    signOutUser
  }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Header);
</code>```

Index.js that holds Routes (/src/index.js)

```<code>import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import reduxThunk from 'redux-thunk';

import reducers from './reducers';
import Home from './components/home';
import About from './components/about';
import Blog from './containers/blog';
import Contact from './components/contact';
import Portfolio from './components/portfolio';
import Services from './components/services';
import registerServiceWorker from './registerServiceWorker';
import SignIn from './containers/signIn_form';

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <BrowserRouter>
      <div>
        <Switch>
          <Route path="/about" component={About} />
          <Route path="/blog" component={Blog} />
          <Route path="/contact" component={Contact} />
          <Route path="/portfolio" component={Portfolio} />
          <Route path="/services" component={Services} />
          <Route path="/signin" component={SignIn} />
          <Route path="/" component={Home} />
        </Switch>
      </div>
    </BrowserRouter>
  </Provider>
, document.getElementById('root'));
registerServiceWorker();
</code>```

If anyone could help shed some light on this issue, I would be super grateful!

答: Thanks everyone for the comments, you're all awesome! It helped me realize that the history npm module I was using for programatic navigation in my action creator was resetting my redux state for some reason (if anyone's curious, here's the link for the github of the history module: https://github.com/ReactTraining/history). After removing the module from my application, the redux state now updates and stays updated as expected.</p>

Body:
As the title suggests, I'm struggling to get my Redux state to update using the reducer. I'm also using Redux with React. In this context, I'm using the Redux state to hold the boolean value of whether a user is signed in with a JWT token. I'm fairly certain I have my reducers correctly set up because I can console log out the initial authenticated state which is set to false by default. BUT when I run the AUTH_USER action which tells the reducer to update the state to have authenticated = true, nothing happens. When logging the redux state of auth, it remains false even after I've run the action for AUTH_USER. It seems to make it into the switch statement in the reducer correctly because the console.log shows up in the terminal. I am getting my console log from my header component's componentDidMount lifecycle method which renders on every part of my React application.

Index.js of Reducers (/src/reducers/index.js)

import { combineReducers } from 'redux';
import authReducer from './reducer_auth';

const rootReducer = combineReducers({
  auth: authReducer
});

export default rootReducer;

The Authentication Reducer (/src/reducers/reducer_auth.js)

import { AUTH_USER, DEAUTH_USER } from '../actions/types';

export default function (state = { authenticated: false, error: "" },
action) {
  switch(action.type) {
    case AUTH_USER:
      console.log('THIS DOES SHOW UP IN CONSOLE')
      return {...state, error: "", authenticated: true };
    case DEAUTH_USER:
      return {...state, error: "", authenticated: false };
    default:
      return state;
  }
}

The Action Creator for signing in (/src/actions/index.js)

import axios from 'axios';
import history from '../utils/historyUtils';

import { AUTH_USER, DEAUTH_USER } from './types';

const ROOT_URL = 'http://localhost:8888';

export function signInUser(username, password) {
  const signInRequest = axios.post(`${ROOT_URL}/wp-json/jwt-auth/v1/token`, {
    "username": username,
    "password": password
  });

  return (dispatch) => {
    return signInRequest.then(response => {
      localStorage.setItem('token', JSON.stringify(response.data.token));

      dispatch({
        type: AUTH_USER,
        payload: { authenticated : true }
      })

      history.push('/');
      history.go();
    })
  }
}

Header Component (/src/containers/header.js)

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { signOutUser } from '../actions';

import '../styles/header.css';

class Header extends Component {
  componentDidMount() {
    console.log('authenticated from header: ', this.props.authenticated)
  }

  handleLogout(event) {
    event.preventDefault();
    localStorage.removeItem('token');

  }

  render() {
    return (

<Link to="/">INSERT BRAND HERE</Link>

<Link to="/">Home</Link>

<Link to="/contact">Contact</Link>

<Link to="/services">Services</Link>

<Link to="/Portfolio">Portfolio</Link>

<Link to="/about">About</Link>

<Link to="/blog">Blog</Link>

              {/* {this.props.authenticated ?
Logout
 :
<Link to="/signin">Login</Link>
} */}

<Link to="/signin">Login</Link>

    );
  }
}

function mapStateToProps(state) {
  return {
    authenticated: state.auth
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    signOutUser
  }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Header);

Index.js that holds Routes (/src/index.js)

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import reduxThunk from 'redux-thunk';

import reducers from './reducers';
import Home from './components/home';
import About from './components/about';
import Blog from './containers/blog';
import Contact from './components/contact';
import Portfolio from './components/portfolio';
import Services from './components/services';
import registerServiceWorker from './registerServiceWorker';
import SignIn from './containers/signIn_form';

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <BrowserRouter>

        <Switch>
          <Route path="/about" component={About} />
          <Route path="/blog" component={Blog} />
          <Route path="/contact" component={Contact} />
          <Route path="/portfolio" component={Portfolio} />
          <Route path="/services" component={Services} />
          <Route path="/signin" component={SignIn} />
          <Route path="/" component={Home} />
        </Switch>

    </BrowserRouter>
  </Provider>
, document.getElementById('root'));
registerServiceWorker();

If anyone could help shed some light on this issue, I would be super grateful!


问:
Disable Prev Control on first slide and disable Next control on last slide
using Slick and looking for a way to have the prev control disabled and hidden until the user clicks the next arrow. Similarly I want the Next control to become disabled and hidden once the user reaches the last slide.

A good illustration of what I'm trying to accomplish is here

Does slick have an attribute already for this that I have overlooked? Is this something that maybe can be accomplished using CSS by adding a disabled class?

The only thing similar I have found is this

```<code>$('.pages .slider').slick({
    autoplay: true,
    autoplaySpeed: 5000,
    infinite: false,
    onAfterChange: function(slide, index) {
        if(index == 4){
        $('.pages .slider').slickPause();
</code>```

But its not exactly what I am looking for.

答:
A very simple solution is:

set the infinite to false. eg

```<code>$('.my-slider').slick({
 infinite: false });
</code>```

add the following css

.slick-disabled {
  display: none;
  pointer-events:none;
}

and that is it.

Body:
using Slick and looking for a way to have the prev control disabled and hidden until the user clicks the next arrow. Similarly I want the Next control to become disabled and hidden once the user reaches the last slide.

A good illustration of what I'm trying to accomplish is here

Does slick have an attribute already for this that I have overlooked? Is this something that maybe can be accomplished using CSS by adding a disabled class?

The only thing similar I have found is this

$('.pages .slider').slick({
    autoplay: true,
    autoplaySpeed: 5000,
    infinite: false,
    onAfterChange: function(slide, index) {
        if(index == 4){
        $('.pages .slider').slickPause();

But its not exactly what I am looking for.

Body:
A very simple solution is:

set the infinite to false. eg

$('.my-slider').slick({
 infinite: false });

add the following css

.slick-disabled {
  display: none;
  pointer-events:none;
}

and that is it.


问:
Symfony2 check user role in Service
How can I check user role in code of a symfony2 Service? Should I simply send a user roles object to a Service or is there solution which allows me to do the check from Service level?</p>

答:
BE CAREFUL...

Be very careful about what you are doing when it comes to Security.. DO NOT DO THIS.

This is because, you need to understand that the TokenInterface is not the same as UserInterface.

TokenInterface is the interface for the user authentication
  information.

You must use it - If you don't have the token made available in your current service, use the SecurityContext or the AccessDecisionManager.

Note: In Symfony > 2.6, some improvements were made, and SecurityContext was deprecated, and split into TokenStorage and AuthorizationChecker. So, you can go ahead and use AuthorizationChecker now.

Look! Even FOSUserBundle implementation talks about it:

```<code>/**
 * Never use this to check if this user has access to anything!
 *
 * Use the SecurityContext, or an implementation of AccessDecisionManager
 * instead, e.g.
 *
 *         $securityContext->isGranted('ROLE_USER');
 *
 * @param string $role
 * @return Boolean
 */
function hasRole($role);
</code>```

Look how it works, look at things like getRoles, Hierarchical roles for example.

ROLES in the database are not to be trusted - if you get a User object from the database, and use your getRoles() or even worse the special isGranted($role) you have created, they will NOT have the roles you expect your user to have.

This should be your bible, and now you can understand the differences between:

1 $user->getRoles()

```<code>array(2) {
    [0]=> string(10) "ROLE_ADMIN"
    [1]=> string(9) "ROLE_USER"
}
</code>```

2 $this->token->getRoles()

```<code>array(2) {
    [0]=> object(Symfony\Component\Security\Core\Role\Role)
        (1) { ["role":"Symfony\Component\Security\Core\Role\Role":private]=> string(10) "ROLE_ADMIN" }
    [1]=> object(Symfony\Component\Security\Core\Role\Role)
        (1) { ["role":"Symfony\Component\Security\Core\Role\Role":private]=> string(22) "ROLE_ALLOWED_TO_SWITCH" }
    [2]=> object(Symfony\Component\Security\Core\Role\Role)
        (1) { ["role":"Symfony\Component\Security\Core\Role\Role":private]=> string(9) "ROLE_USER" }

}
</code>```

3 $this->token->getUser->getRoles()

```<code>array(2) {
    [0]=> string(10) "ROLE_ADMIN"
    [1]=> string(22) "ROLE_ALLOWED_TO_SWITCH"
    [2]=> string(9) "ROLE_USER"
}
</code>```

When you have security.yml

```<code>security:
    role_hierarchy:
        ROLE_ADMIN: [ROLE_ALLOWED_TO_SWITCH]
</code>```

Title: Symfony2 check user role in Service

Body:
BE CAREFUL...

Be very careful about what you are doing when it comes to Security.. DO NOT DO THIS.

This is because, you need to understand that the TokenInterface is not the same as UserInterface.

TokenInterface is the interface for the user authentication
  information.

You must use it - If you don't have the token made available in your current service, use the SecurityContext or the AccessDecisionManager.

Note: In Symfony > 2.6, some improvements were made, and SecurityContext was deprecated, and split into TokenStorage and AuthorizationChecker. So, you can go ahead and use AuthorizationChecker now.

Look! Even FOSUserBundle implementation talks about it:

/**
 * Never use this to check if this user has access to anything!
 *
 * Use the SecurityContext, or an implementation of AccessDecisionManager
 * instead, e.g.
 *
 *         $securityContext->isGranted('ROLE_USER');
 *
 * @param string $role
 * @return Boolean
 */
function hasRole($role);

Look how it works, look at things like getRoles, Hierarchical roles for example.

ROLES in the database are not to be trusted - if you get a User object from the database, and use your getRoles() or even worse the special isGranted($role) you have created, they will NOT have the roles you expect your user to have.

This should be your bible, and now you can understand the differences between:

1 $user->getRoles()

array(2) {
    [0]=> string(10) "ROLE_ADMIN"
    [1]=> string(9) "ROLE_USER"
}

2 $this->token->getRoles()

array(2) {
    [0]=> object(Symfony\Component\Security\Core\Role\Role)
        (1) { ["role":"Symfony\Component\Security\Core\Role\Role":private]=> string(10) "ROLE_ADMIN" }
    [1]=> object(Symfony\Component\Security\Core\Role\Role)
        (1) { ["role":"Symfony\Component\Security\Core\Role\Role":private]=> string(22) "ROLE_ALLOWED_TO_SWITCH" }
    [2]=> object(Symfony\Component\Security\Core\Role\Role)
        (1) { ["role":"Symfony\Component\Security\Core\Role\Role":private]=> string(9) "ROLE_USER" }

}

3 $this->token->getUser->getRoles()

array(2) {
    [0]=> string(10) "ROLE_ADMIN"
    [1]=> string(22) "ROLE_ALLOWED_TO_SWITCH"
    [2]=> string(9) "ROLE_USER"
}

When you have security.yml

security:
    role_hierarchy:
        ROLE_ADMIN: [ROLE_ALLOWED_TO_SWITCH]


问:
How to extract value of DIV tag by a label in JMeter
I'm trying to extract the value of Document Status in the sample HTML below using JMeter. In this case the value I want to extract is Current.

Is it better to use a regex extractor or an XPath extractor? Can someone please provide the syntax to extract this value?

```<code>      <div class="spacing--after-s"><div>
      <b>Document status</b>
      <div>  <div class="paragraph">
        <div>
          <b>Status</b>
          <div>Current</div>
        </div>

      </div>
    </div>
  </div>
</div>
</code>```

答:
This XPath,

```<code>//b[.='Status']/following-sibling::div/text()
</code>```

will select the text node child of the div element that follows the b label whose string value is 'Status'.

If that label appears elsewhere in your document, let us know and we can refine the XPath to select only the one you want.

Body:
I'm trying to extract the value of Document Status in the sample HTML below using JMeter. In this case the value I want to extract is Current.

Is it better to use a regex extractor or an XPath extractor? Can someone please provide the syntax to extract this value?

      Document status

          Status

Current

Body:
This XPath,

//b[.='Status']/following-sibling::div/text()

will select the text node child of the div element that follows the b label whose string value is 'Status'.

If that label appears elsewhere in your document, let us know and we can refine the XPath to select only the one you want.


问:
Is this common behaviour of the iPad device?
I have developed an iPad application which runs good in simulator with both orientations.

When i rotate the simulator , the corresponding view gets loaded according to the orientation.

But the same application when running on real iPad device,  when i rotate the device fastly, the corresponding view is not getting loaded. it takes time to load the correct view according to the device orientation.

why this happening? is this common behaviour in the ipad device?

Please let me know your views.

答: It may be that the iPad does not have enough memory, unlike the simulator which runs in your computer and uses the computer's memory</p>


问:
Can't install pip packages inside a docker container with Ubuntu
I'm following the fig guide to using docker with a python application, but when docker gets up to the command

```<code>RUN pip install -r requirements.txt
</code>```

I get the following error message:

```<code>Step 3 : RUN pip install -r requirements.txt
 ---> Running in fe0b84217ad1
Collecting blinker==1.3 (from -r requirements.txt (line 1))
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/blinker/
</code>```

This repeats several times and then I get another message:

```<code>Could not find any downloads that satisfy the requirement blinker==1.3 (from -r requirements.txt (line 1))
  No distributions at all found for blinker==1.3 (from -r requirements.txt (line 1))
</code>```

So for some reason pip can't access any packages from inside a docker container. Is there anything I need to do to allow it internet access?

However pip works fine to install things outside of the docker container, and worked fine even with that exact package (blinker==1.3) so that's not the problem. Also this problem isn't specific to that package. I get the same issue with any pip install command for any package.

Does anyone have any idea what's going on here?

答:
For me, I was unable to install pip due to the docker's DNS not configured properly. I've tried the above steps, however, configuring docker DNS to Google DNS does not work for my laptop. Docker's DNS can be properly configured only if I set its DNS to my laptop's assigned IP.

If you use Ubuntu, you can use the following steps to configure your docker's DNS:

Find out your device's assigned IP. You can find this by either

Checking the inet addr of your ethernet or wlan in ifconfig

Choosing any address in nmcli dev show | grep 'DNS'

Edit dns in /etc/docker/daemon.json (create this file if it doesn't exist previously)

```<code>{
    "dns": ["your_ip_in_step_1"]
}
</code>```

Restart docker: sudo service docker restart

Body:
I'm following the fig guide to using docker with a python application, but when docker gets up to the command

RUN pip install -r requirements.txt

I get the following error message:

Step 3 : RUN pip install -r requirements.txt
 ---> Running in fe0b84217ad1
Collecting blinker==1.3 (from -r requirements.txt (line 1))
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/blinker/

This repeats several times and then I get another message:

Could not find any downloads that satisfy the requirement blinker==1.3 (from -r requirements.txt (line 1))
  No distributions at all found for blinker==1.3 (from -r requirements.txt (line 1))

So for some reason pip can't access any packages from inside a docker container. Is there anything I need to do to allow it internet access?

However pip works fine to install things outside of the docker container, and worked fine even with that exact package (blinker==1.3) so that's not the problem. Also this problem isn't specific to that package. I get the same issue with any pip install command for any package.

Does anyone have any idea what's going on here?

Body:
For me, I was unable to install pip due to the docker's DNS not configured properly. I've tried the above steps, however, configuring docker DNS to Google DNS does not work for my laptop. Docker's DNS can be properly configured only if I set its DNS to my laptop's assigned IP.

If you use Ubuntu, you can use the following steps to configure your docker's DNS:

Find out your device's assigned IP. You can find this by either

Checking the inet addr of your ethernet or wlan in ifconfig

Choosing any address in nmcli dev show | grep 'DNS'

Edit dns in /etc/docker/daemon.json (create this file if it doesn't exist previously)

{
    "dns": ["your_ip_in_step_1"]
}

Restart docker: sudo service docker restart