问:
Some Views can be enabled/disabled while others cannot
I have a layout here that has some nested layouts which contain various Views that I want to enable/disable. I thought it would be as straight-forward as calling setEnabled() on them but I've found that only works on the Textviews and Switches. The Seekbars, Togglebuttons, and Imagebuttons don't react to setEnabled() programmatically and don't have android:enabled="" available to them in XML. What am I missing here?

```<code><ScrollView 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">

    <!-- ***** Zoom ***** -->
    <RelativeLayout
        android:id="@+id/RL_zoom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="1dp"
        android:background="@drawable/layout_bg_transluscent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textview_zoomLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_centerInParent="true"
            android:text="Zoom"
            android:textColor="#ff43b7ff"
            android:textSize="20sp" />

        <ImageButton
            android:id="@+id/imagebutton_zoomOut"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="15dp"
            android:layout_toEndOf="@+id/textview_zoomLabel"
            android:background="@null"
            android:src="@drawable/ic_zoom_out_white_24dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_toEndOf="@+id/imagebutton_zoomOut"
            android:layout_toStartOf="@+id/imagebutton_zoomIn"
            android:orientation="horizontal">

            <SeekBar
                android:id="@+id/seekbar_zoom"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>

        <TextView
            android:id="@+id/textview_zoomValue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="5dp"
            android:layout_toStartOf="@+id/textview_zoomPercentageLabel"
            android:text="50" />

        <TextView
            android:id="@+id/textview_zoomPercentageLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerInParent="true"
            android:text="%" />

        <ImageButton
            android:id="@+id/imagebutton_zoomIn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_toStartOf="@id/textview_zoomValue"
            android:background="@null"
            android:src="@drawable/ic_zoom_in_white_24dp" />
    </RelativeLayout>

    <!--   *****  Focus ***** -->
    <RelativeLayout
        android:id="@+id/RL_focus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/RL_zoom"
        android:layout_marginTop="2dp"
        android:background="@drawable/layout_bg_transluscent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textview_focusLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/togglebutton_autofocus"
            android:layout_centerInParent="true"
            android:text="Focus"
            android:textColor="#ff43b7ff"
            android:textSize="20sp" />

        <ImageButton
            android:id="@+id/imagebutton_focusOut"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="14dp"
            android:layout_toEndOf="@+id/textview_focusLabel"
            android:background="@null"
            android:src="@drawable/ic_zoom_out_white_24dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_toEndOf="@+id/imagebutton_focusOut"
            android:layout_toStartOf="@+id/imagebutton_focusIn"
            android:orientation="horizontal">

            <SeekBar
                android:id="@+id/seekbar_focus"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>

        <TextView
            android:id="@+id/textview_focusValue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="5dp"
            android:layout_toStartOf="@+id/textview_focusPercentageLabel"
            android:text="50" />

        <TextView
            android:id="@+id/textview_focusPercentageLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_toStartOf="@+id/togglebutton_autofocus"
            android:text="%" />

        <ImageButton
            android:id="@+id/imagebutton_focusIn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_toStartOf="@id/textview_focusValue"
            android:background="@null"
            android:src="@drawable/ic_zoom_in_white_24dp" />

        <ToggleButton
            android:id="@+id/togglebutton_autofocus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerInParent="true"
            android:layout_marginLeft="3dp"
            android:minHeight="1dp"
            android:minWidth="1dp"
            android:textAllCaps="false"
            android:textColor="#ff43b7ff"
            android:textOff="AF
Off"
            android:textOn="AF
On" />
    </RelativeLayout>

    <!--   *****  Iris ***** -->
    <RelativeLayout
        android:id="@+id/RL_iris"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/RL_focus"
        android:layout_marginTop="2dp"
        android:background="@drawable/layout_bg_transluscent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textview_irisLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/togglebutton_autoiris"
            android:layout_centerInParent="true"
            android:text="Iris"
            android:textColor="#ff43b7ff"
            android:textSize="20sp" />

        <ImageButton
            android:id="@+id/imagebutton_irisOut"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="41dp"
            android:layout_toEndOf="@+id/textview_irisLabel"
            android:background="@null"
            android:src="@drawable/ic_zoom_out_white_24dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_toEndOf="@+id/imagebutton_irisOut"
            android:layout_toStartOf="@+id/imagebutton_irisIn"
            android:orientation="horizontal">

            <SeekBar
                android:id="@+id/seekbar_iris"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>

        <TextView
            android:id="@+id/textview_irisValue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="5dp"
            android:layout_toStartOf="@+id/textview_irisPercentageLabel"
            android:text="50" />

        <TextView
            android:id="@+id/textview_irisPercentageLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_toStartOf="@+id/togglebutton_autoiris"
            android:text="%" />

        <ImageButton
            android:id="@+id/imagebutton_irisIn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_toStartOf="@id/textview_irisValue"
            android:background="@null"
            android:src="@drawable/ic_zoom_in_white_24dp" />

        <ToggleButton
            android:id="@+id/togglebutton_autoiris"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerInParent="true"
            android:layout_marginLeft="3dp"
            android:minHeight="1dp"
            android:minWidth="1dp"
            android:textAllCaps="false"
            android:textColor="#ff43b7ff"
            android:textOff="AI
Off"
            android:textOn="AI
On" />
    </RelativeLayout>

    <!--   *****  On/Off ***** -->
    <RelativeLayout
        android:id="@+id/RL_device_tools_on_off"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/RL_iris"
        android:layout_marginTop="2dp"
        android:background="@drawable/layout_bg_transluscent"
        android:orientation="horizontal">

        <Switch
            android:id="@+id/switch_device_power_on_off"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            android:text="Device Power"
            android:textColor="#ff43b7ff" />

        <ImageButton
            android:id="@+id/imagebutton_device_refresh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@+id/switch_device_power_on_off"
            android:src="@drawable/ic_refresh_white_24dp" />
    </RelativeLayout>

</RelativeLayout>
</code>```

答:
While every view has a setEnabled method, the interpretation of the value set through it varies by subclass.

In your case, TextView, Switch, and ToggleButton have logic to respond to this value when it is set. The others don't. In a similar fashion, you're only able to set the android:enabled attribute on the these because it is defined as an attribute that can be used with TextViews.

If you'd like to have Seekbar and ImageButton respond to the setEnabled value, you can create custom views which extend each of those, override the setEnabled method, then implement how you'd like each of these views to react.

Body:
I have a layout here that has some nested layouts which contain various Views that I want to enable/disable. I thought it would be as straight-forward as calling setEnabled() on them but I've found that only works on the Textviews and Switches. The Seekbars, Togglebuttons, and Imagebuttons don't react to setEnabled() programmatically and don't have android:enabled="" available to them in XML. What am I missing here?

<ScrollView 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">

    <RelativeLayout
        android:id="@+id/RL_zoom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="1dp"
        android:background="@drawable/layout_bg_transluscent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textview_zoomLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_centerInParent="true"
            android:text="Zoom"
            android:textColor="#ff43b7ff"
            android:textSize="20sp" />

        <ImageButton
            android:id="@+id/imagebutton_zoomOut"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="15dp"
            android:layout_toEndOf="@+id/textview_zoomLabel"
            android:background="@null"
            android:src="@drawable/ic_zoom_out_white_24dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_toEndOf="@+id/imagebutton_zoomOut"
            android:layout_toStartOf="@+id/imagebutton_zoomIn"
            android:orientation="horizontal">

            <SeekBar
                android:id="@+id/seekbar_zoom"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>

        <TextView
            android:id="@+id/textview_zoomValue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="5dp"
            android:layout_toStartOf="@+id/textview_zoomPercentageLabel"
            android:text="50" />

        <TextView
            android:id="@+id/textview_zoomPercentageLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerInParent="true"
            android:text="%" />

        <ImageButton
            android:id="@+id/imagebutton_zoomIn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_toStartOf="@id/textview_zoomValue"
            android:background="@null"
            android:src="@drawable/ic_zoom_in_white_24dp" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/RL_focus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/RL_zoom"
        android:layout_marginTop="2dp"
        android:background="@drawable/layout_bg_transluscent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textview_focusLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/togglebutton_autofocus"
            android:layout_centerInParent="true"
            android:text="Focus"
            android:textColor="#ff43b7ff"
            android:textSize="20sp" />

        <ImageButton
            android:id="@+id/imagebutton_focusOut"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="14dp"
            android:layout_toEndOf="@+id/textview_focusLabel"
            android:background="@null"
            android:src="@drawable/ic_zoom_out_white_24dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_toEndOf="@+id/imagebutton_focusOut"
            android:layout_toStartOf="@+id/imagebutton_focusIn"
            android:orientation="horizontal">

            <SeekBar
                android:id="@+id/seekbar_focus"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>

        <TextView
            android:id="@+id/textview_focusValue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="5dp"
            android:layout_toStartOf="@+id/textview_focusPercentageLabel"
            android:text="50" />

        <TextView
            android:id="@+id/textview_focusPercentageLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_toStartOf="@+id/togglebutton_autofocus"
            android:text="%" />

        <ImageButton
            android:id="@+id/imagebutton_focusIn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_toStartOf="@id/textview_focusValue"
            android:background="@null"
            android:src="@drawable/ic_zoom_in_white_24dp" />

        <ToggleButton
            android:id="@+id/togglebutton_autofocus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerInParent="true"
            android:layout_marginLeft="3dp"
            android:minHeight="1dp"
            android:minWidth="1dp"
            android:textAllCaps="false"
            android:textColor="#ff43b7ff"
            android:textOff="AF
Off"
            android:textOn="AF
On" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/RL_iris"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/RL_focus"
        android:layout_marginTop="2dp"
        android:background="@drawable/layout_bg_transluscent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textview_irisLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/togglebutton_autoiris"
            android:layout_centerInParent="true"
            android:text="Iris"
            android:textColor="#ff43b7ff"
            android:textSize="20sp" />

        <ImageButton
            android:id="@+id/imagebutton_irisOut"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="41dp"
            android:layout_toEndOf="@+id/textview_irisLabel"
            android:background="@null"
            android:src="@drawable/ic_zoom_out_white_24dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_toEndOf="@+id/imagebutton_irisOut"
            android:layout_toStartOf="@+id/imagebutton_irisIn"
            android:orientation="horizontal">

            <SeekBar
                android:id="@+id/seekbar_iris"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>

        <TextView
            android:id="@+id/textview_irisValue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="5dp"
            android:layout_toStartOf="@+id/textview_irisPercentageLabel"
            android:text="50" />

        <TextView
            android:id="@+id/textview_irisPercentageLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_toStartOf="@+id/togglebutton_autoiris"
            android:text="%" />

        <ImageButton
            android:id="@+id/imagebutton_irisIn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_toStartOf="@id/textview_irisValue"
            android:background="@null"
            android:src="@drawable/ic_zoom_in_white_24dp" />

        <ToggleButton
            android:id="@+id/togglebutton_autoiris"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerInParent="true"
            android:layout_marginLeft="3dp"
            android:minHeight="1dp"
            android:minWidth="1dp"
            android:textAllCaps="false"
            android:textColor="#ff43b7ff"
            android:textOff="AI
Off"
            android:textOn="AI
On" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/RL_device_tools_on_off"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/RL_iris"
        android:layout_marginTop="2dp"
        android:background="@drawable/layout_bg_transluscent"
        android:orientation="horizontal">

        <Switch
            android:id="@+id/switch_device_power_on_off"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            android:text="Device Power"
            android:textColor="#ff43b7ff" />

        <ImageButton
            android:id="@+id/imagebutton_device_refresh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@+id/switch_device_power_on_off"
            android:src="@drawable/ic_refresh_white_24dp" />
    </RelativeLayout>

</RelativeLayout>


来源: stackexchange

问:
How to uninstall global package with npm?
I have installed webpack in this way:

```<code>npm install -g webpack
</code>```

Now want to uninstall it:

```<code>npm uninstall -g webpack
</code>```

Check it again, it didn't been uninstalled:

```<code>webpack -v
3.1.0
</code>```

Why?

And, I use this way can't find webpack:

```<code>npm list -g | grep webpack
</code>```

This also didn't work:

```<code>npm uninstall -g webpack --save
</code>```

After run this under a directory which included package.json:

```<code>npm uninstall webpack
npm WARN babel-loader@6.4.1 requires a peer of webpack@1 || 2 || ^2.1.0-beta || ^2.2.0-rc but none was installed.
npm WARN uglifyjs-webpack-plugin@0.3.1 requires a peer of uglify-js@^2.8.0 but none was installed.
npm WARN uglifyjs-webpack-plugin@0.3.1 requires a peer of webpack@^1.9 || ^2 || ^2.1.0-beta || ^2.2.0-rc but none was installed.
</code>```

答:
Try </p>

```<code>chown -R "$(whoami)": "$(npm root -g)"
</code>```

<p>(you may need sudo for it) and then npm uninstall -g  again</p>

ContentLicense: CC BY-SA 3.0

Body:
I have installed webpack in this way:

npm install -g webpack

Now want to uninstall it:

npm uninstall -g webpack

Check it again, it didn't been uninstalled:

webpack -v
3.1.0

Why?

And, I use this way can't find webpack:

npm list -g | grep webpack

This also didn't work:

npm uninstall -g webpack --save

After run this under a directory which included package.json:

npm uninstall webpack
npm WARN babel-loader@6.4.1 requires a peer of webpack@1 || 2 || ^2.1.0-beta || ^2.2.0-rc but none was installed.
npm WARN uglifyjs-webpack-plugin@0.3.1 requires a peer of uglify-js@^2.8.0 but none was installed.
npm WARN uglifyjs-webpack-plugin@0.3.1 requires a peer of webpack@^1.9 || ^2 || ^2.1.0-beta || ^2.2.0-rc but none was installed.

Body:
Try

chown -R "$(whoami)": "$(npm root -g)"

(you may need sudo for it) and then npm uninstall -g  again


问:
pandas: within groupby functions to select rows with some criteria paris
Buddys: I have a dataframe like:

```<code>df = pd.DataFrame({'code':'A','A','A','A','A','A','B','B','B', 'B','B','B'), 'Times': (1,2,3,4,5,6,1,2,3,4,5,6),'Figure':(2.3,4.1,5.2,7.0,1.8,9.0,4.2,7.9,4.6,1.4,9.7,1.2)})
</code>```

so the structure like this:

```<code>>>> df
    Figure  Times code
0      2.3      1    A
1      4.1      2    A
2      5.2      3    A
3      7.0      4    A
4      1.8      5    A
5      9.0      6    A
6      4.2      1    B
7      7.9      2    B
8      4.6      3    B
9      1.4      4    B
10     9.7      5    B
11     1.2      6    B
</code>```

Now I want to within each code group ('A', 'B'), calculate differences of Figure only when Times pairs in [[4,1],[6,1],[3,2]]. So the desired new dataframe would like this:

```<code>>>> newdf
  code  diffFigure diffTimes
0    A         4.7       4-1
1    A         6.7       3-2
2    A         1.1       6-1
3    B        -3.3       4-1
4    B        -2.8       3-2
5    B        -3.0       6-1
</code>```

Of course, I would like to use groupby functions and apply a function:

```<code>def f(x):
    myList = [[4,1],[6,1],[3,2]]
    for i in x.itertuples():
        for j in x.itertuples():
            if (i.Times, j.Times) in myList:
                print (i.code + ": " + str(i.Times) + "-" + str(j.Times) + "=" + str(i.Figure - j.Figure))
newdf = df.groupby('code').apply(f)
</code>```

But I cant get the desired dataframe. Here two problems: Firstly any possible ways not using itertuples to enumerate around all rows? Secondly in the function f, how to design return format to get the desired dataframe?

Many Thanks

答:
Two possible solutions:

Either make use of .unstack():

```<code>df = pd.DataFrame({'code':('A','A','A','A','A','A','B','B','B', 'B','B','B'), 'Times': (1,2,3,4,5,6,1,2,3,4,5,6),'Figure':(2.3,4.1,5.2,7.0,1.8,9.0,4.2,7.9,4.6,1.4,9.7,1.2)})
df = df.set_index(["code","Times"]).unstack()
</code>```

and manually concatenate the differences in a for loop, i.e.:

```<code>myList = [[4,1],[6,1],[3,2]]
pd.concat(((df[('Figure',d1)] - df[('Figure',d0)]).to_frame('diffFigure').assign(diffTimes="{}-{}".format(d1,d0)) for (d1,d0) in myList))
</code>```

or make a list of all the possible combinations within each code:

```<code>df0 = df.merge(df, on = 'code')
</code>```

Then take the subset of pairs which is in myList by turning myList into a dataframe and doing an inner join operation:

```<code>df0 = df0.merge(pd.DataFrame(myList, columns = ['Times_x','Times_y']))
df0['diffFigure'] = df0.Figure_x - df0.Figure_y
df0['diffTimes'] = df0.Times_x.astype(str) + '-' + df0.Times_y.astype(str)

df0[['code','diffFigure','diffTimes']]
</code>```

Body:
Buddys: I have a dataframe like:

df = pd.DataFrame({'code':'A','A','A','A','A','A','B','B','B', 'B','B','B'), 'Times': (1,2,3,4,5,6,1,2,3,4,5,6),'Figure':(2.3,4.1,5.2,7.0,1.8,9.0,4.2,7.9,4.6,1.4,9.7,1.2)})

so the structure like this:

>>> df
    Figure  Times code
0      2.3      1    A
1      4.1      2    A
2      5.2      3    A
3      7.0      4    A
4      1.8      5    A
5      9.0      6    A
6      4.2      1    B
7      7.9      2    B
8      4.6      3    B
9      1.4      4    B
10     9.7      5    B
11     1.2      6    B

Now I want to within each code group ('A', 'B'), calculate differences of Figure only when Times pairs in [[4,1],[6,1],[3,2]]. So the desired new dataframe would like this:

>>> newdf
  code  diffFigure diffTimes
0    A         4.7       4-1
1    A         6.7       3-2
2    A         1.1       6-1
3    B        -3.3       4-1
4    B        -2.8       3-2
5    B        -3.0       6-1

Of course, I would like to use groupby functions and apply a function:

def f(x):
    myList = [[4,1],[6,1],[3,2]]
    for i in x.itertuples():
        for j in x.itertuples():
            if (i.Times, j.Times) in myList:
                print (i.code + ": " + str(i.Times) + "-" + str(j.Times) + "=" + str(i.Figure - j.Figure))
newdf = df.groupby('code').apply(f)

But I cant get the desired dataframe. Here two problems: Firstly any possible ways not using itertuples to enumerate around all rows? Secondly in the function f, how to design return format to get the desired dataframe?

Many Thanks

Body:
Two possible solutions:

Either make use of .unstack():

df = pd.DataFrame({'code':('A','A','A','A','A','A','B','B','B', 'B','B','B'), 'Times': (1,2,3,4,5,6,1,2,3,4,5,6),'Figure':(2.3,4.1,5.2,7.0,1.8,9.0,4.2,7.9,4.6,1.4,9.7,1.2)})
df = df.set_index(["code","Times"]).unstack()

and manually concatenate the differences in a for loop, i.e.:

myList = [[4,1],[6,1],[3,2]]
pd.concat(((df[('Figure',d1)] - df[('Figure',d0)]).to_frame('diffFigure').assign(diffTimes="{}-{}".format(d1,d0)) for (d1,d0) in myList))

or make a list of all the possible combinations within each code:

df0 = df.merge(df, on = 'code')

Then take the subset of pairs which is in myList by turning myList into a dataframe and doing an inner join operation:

df0 = df0.merge(pd.DataFrame(myList, columns = ['Times_x','Times_y']))
df0['diffFigure'] = df0.Figure_x - df0.Figure_y
df0['diffTimes'] = df0.Times_x.astype(str) + '-' + df0.Times_y.astype(str)

df0[['code','diffFigure','diffTimes']]


问:
postgres trigger function only inserts few records in another table
I have 2 tables hourly and daily and my aim is to calculate average of values from hourly table and save it to daily table. I have written a trigger function like this -

```<code>CREATE OR REPLACE FUNCTION public.calculate_daily_avg()
RETURNS trigger AS
$BODY$
DECLARE chrly CURSOR for
SELECT device, date(datum) datum, avg(cpu_util) cpu_util
FROM chourly WHERE date(datum) = current_date group by device, date(datum);

BEGIN

    FOR chrly_rec IN chrly
    LOOP

    insert into cdaily (device, datum, cpu_util)
    values (chrly_rec.device, chrly_rec.datum, chrly_rec.cpu_util)
        on conflict (device, datum) do update set
        device=chrly_rec.device, datum=chrly_rec.datum, cpu_util=chrly_rec.cpu_util;

    return NEW;

    END LOOP;
    EXCEPTION
        WHEN NO_DATA_FOUND THEN
        RAISE NOTICE 'NO DATA IN chourly FOR %', current_date;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION public.calculate_daily_avg()
  OWNER TO postgres;
</code>```

and a trigger on hourly table like this -

```<code>CREATE TRIGGER calculate_daily_avg_trg
  BEFORE INSERT OR UPDATE
  ON public.chourly
  FOR EACH ROW
  EXECUTE PROCEDURE public.calculate_daily_avg();
</code>```

But when I try to insert or update about 3000 records in the hourly table only 3 or 4 devices are inserted and not 3000. (also in trigger I have already tried AFTER INSERT OR UPDATE but even that gives the same result) What I am doing wrong here? Please suggest any better way to write the trigger if you feel I have written it wrongly. Thanks!

答:
I don't suggest using TRIGGER for calculation when INSERT. Try different approach using function execute by cron hourly or daily.

WHY?

Because everytime you INSERT one row. the postgres will always do aggregate function AVG() and LOOPING for insert (based on your flow).

That mean another INSERT statement will waiting until Previous INSERT commited that will suffer your database performance for highly INSERT Transaction. If somehow you manage to BREAK the rule (maybe from configuration) you will get inconsistent data like what happened to you right now.

Body:
I have 2 tables hourly and daily and my aim is to calculate average of values from hourly table and save it to daily table. I have written a trigger function like this -

CREATE OR REPLACE FUNCTION public.calculate_daily_avg()
RETURNS trigger AS
$BODY$
DECLARE chrly CURSOR for
SELECT device, date(datum) datum, avg(cpu_util) cpu_util
FROM chourly WHERE date(datum) = current_date group by device, date(datum);

BEGIN

    FOR chrly_rec IN chrly
    LOOP

    insert into cdaily (device, datum, cpu_util)
    values (chrly_rec.device, chrly_rec.datum, chrly_rec.cpu_util)
        on conflict (device, datum) do update set
        device=chrly_rec.device, datum=chrly_rec.datum, cpu_util=chrly_rec.cpu_util;

    return NEW;

    END LOOP;
    EXCEPTION
        WHEN NO_DATA_FOUND THEN
        RAISE NOTICE 'NO DATA IN chourly FOR %', current_date;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION public.calculate_daily_avg()
  OWNER TO postgres;

and a trigger on hourly table like this -

CREATE TRIGGER calculate_daily_avg_trg
  BEFORE INSERT OR UPDATE
  ON public.chourly
  FOR EACH ROW
  EXECUTE PROCEDURE public.calculate_daily_avg();

But when I try to insert or update about 3000 records in the hourly table only 3 or 4 devices are inserted and not 3000. (also in trigger I have already tried AFTER INSERT OR UPDATE but even that gives the same result) What I am doing wrong here? Please suggest any better way to write the trigger if you feel I have written it wrongly. Thanks!


问:
Point to localhost\sqlexpress using only localhost
Working on a common codebase, one developer is running SQL Server Express 2005 and the other 2 are running SQL Server 2005. Everything is working fine, but the connection strings differ. To maintain common configuration and build scripts we're looking to mask "localhost\sqlexpress" to just "localhost" like the other 2 developers.

Can this be done? Or, maybe there's a better way for all 3 to run on the same connection string... The solution sought is for all 3 to be able to run on the same file versions in the code repository.

I might not be 100% clear: basically I want this:

```<code>Data Source=localhost;Initial Catalog=Sample;Integrated Security=True
</code>```

to connect the exact same as this:

```<code>Data Source=localhost\sqlexpress;Initial Catalog=Sample;Integrated Security=True
</code>```

If at all possible.

答:
You can name SQL Server instances to anything you want. I'm pretty sure you can do it in SQL Express as well, so just name the instance, on each machine, to the same name, then you can just use localhost\<name>.

Or even better, don't hardcode the database name. Load it from some machine or user-specific setting (registry, config file, whatever suits your fancy :) ).

OwnerDisplayName: Chris Missal

Body:
Working on a common codebase, one developer is running SQL Server Express 2005 and the other 2 are running SQL Server 2005. Everything is working fine, but the connection strings differ. To maintain common configuration and build scripts we're looking to mask "localhost\sqlexpress" to just "localhost" like the other 2 developers.

Can this be done? Or, maybe there's a better way for all 3 to run on the same connection string... The solution sought is for all 3 to be able to run on the same file versions in the code repository.

I might not be 100% clear: basically I want this:

Data Source=localhost;Initial Catalog=Sample;Integrated Security=True

to connect the exact same as this:

Data Source=localhost\sqlexpress;Initial Catalog=Sample;Integrated Security=True

If at all possible.

LastEditorDisplayName: Chris Missal

OwnerDisplayName: Danut Enachioiu

ContentLicense: CC BY-SA 2.5


问:
Object reference not set to an instance of an object. ListViewItem VB.NET
```<code>Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
    Dim myList As ListViewItem

    Dim JmlList As Integer
    Dim i As Integer

    JmlList = lst_detail.Items.Count - 1
    i = 0

    myList = lst_detail.Items.Add(str(lst_detail.Items.Count + 1)) // error at this
    myList.SubItems.Add(txtKodeObat.Text.Trim)
    myList.SubItems.Add(txtNamaObat.Text.Trim)
    myList.SubItems.Add(txtHarga.Text.Trim)
    myList.SubItems.Add(txtQty.Text.Trim)
    myList.SubItems.Add(txtJumlah.Text.Trim)

    Dim subtotal As Double = 0

    JmlList = lst_detail.Items.Count - 1
    For i = 0 To JmlList
        subtotal = subtotal + Val(lst_detail.Items(i).SubItems(5).Text)
    Next
    txtSubTotal.Text = Format(subtotal, "##########")
    txtPPn.Text = Format(subtotal * 0.1, "##########")
    txtTotal.Text = Val(txtSubTotal.Text) + Val(txtPPn.Text)
    txtKodeObat.Text = ""
    txtNamaObat.Text = ""
    txtHarga.Text = "0"
    txtQty.Text = ""
    txtJumlah.Text = "0"
    txtKodeObat.Focus()

End Sub
</code>```

I got error at         myList = lst_detail.Items.Add(str(lst_detail.Items.Count + 1))

i want to add from text to listitem but got null error
i have fill that textbox

答:
It looks like you're trying to pull data from a specific index within the lst_detail. I didn't test the following code, but something like the following might do what you're trying to do.  </p>

<p>myList = lst_detail.Items.Add(lst_detail.Items[lst_detail.Items.Count + 1].ToString()) </p>

Body:
Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
    Dim myList As ListViewItem

    Dim JmlList As Integer
    Dim i As Integer

    JmlList = lst_detail.Items.Count - 1
    i = 0

    myList = lst_detail.Items.Add(str(lst_detail.Items.Count + 1)) // error at this
    myList.SubItems.Add(txtKodeObat.Text.Trim)
    myList.SubItems.Add(txtNamaObat.Text.Trim)
    myList.SubItems.Add(txtHarga.Text.Trim)
    myList.SubItems.Add(txtQty.Text.Trim)
    myList.SubItems.Add(txtJumlah.Text.Trim)

    Dim subtotal As Double = 0

    JmlList = lst_detail.Items.Count - 1
    For i = 0 To JmlList
        subtotal = subtotal + Val(lst_detail.Items(i).SubItems(5).Text)
    Next
    txtSubTotal.Text = Format(subtotal, "##########")
    txtPPn.Text = Format(subtotal * 0.1, "##########")
    txtTotal.Text = Val(txtSubTotal.Text) + Val(txtPPn.Text)
    txtKodeObat.Text = ""
    txtNamaObat.Text = ""
    txtHarga.Text = "0"
    txtQty.Text = ""
    txtJumlah.Text = "0"
    txtKodeObat.Focus()

End Sub

I got error at         myList = lst_detail.Items.Add(str(lst_detail.Items.Count + 1))

i want to add from text to listitem but got null error
i have fill that textbox

Body:
It looks like you're trying to pull data from a specific index within the lst_detail. I didn't test the following code, but something like the following might do what you're trying to do.

myList = lst_detail.Items.Add(lst_detail.Items[lst_detail.Items.Count + 1].ToString())


问:
Make a activity screen which shows up only once
I want to make a activity in an app which shows up only when the user installs the app and never again. How can I do that?</p>

答:
1.store value in sharedPrefernces.

```<code>SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("screen_show", false);
editor.commit();
</code>```

2. get value from sharedPreferences

```<code>SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
preferences.getBoolean("screen_show", false);
</code>```

3.It is false first time always

```<code>if( ! preferences.getBoolean("screen_show", false)){
    // if show screen
    Intent showscreenIntent=new(this,ShowScreen_Intent.class);
    startActivity(showscreenIntent);
} else {
    //
}
</code>```

4.after showing screen first time set true in shared prefernece like this.

```<code> SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("screen_show", true);
editor.commit();
</code>```

Now whenever step 3 execute else condition run and Activity will never show again.

hope it helps !!!

Body:
1.store value in sharedPrefernces.

SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("screen_show", false);
editor.commit();

2. get value from sharedPreferences

SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
preferences.getBoolean("screen_show", false);

3.It is false first time always

if( ! preferences.getBoolean("screen_show", false)){
    // if show screen
    Intent showscreenIntent=new(this,ShowScreen_Intent.class);
    startActivity(showscreenIntent);
} else {
    //
}

4.after showing screen first time set true in shared prefernece like this.

 SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("screen_show", true);
editor.commit();

Now whenever step 3 execute else condition run and Activity will never show again.

hope it helps !!!


问:
Filling a one2many inside a one2many in onchange
Using an on_change method I am trying to send default values to a one2many field using the concept of (0,0, {list values}; even there it works fine but inside that one2many there is also a one2many field to which I must also send values to implement In my code the same concept of (0,0, {list values}, but I did not get success.

Could you help me?.

Attached fragment of my code

class hc(models.Model):
    _name = 'hc'
    laboratorios_ids = fields.One2many(
        string='Laboratorios', comodel_name='resullab',
        inverse_name='hc_id')

    def cargar_pool_labs(self):
        labs = []
        pool = self.env['mymodel'].sudo().search([])
        for laboratorio in pool:
            analitos = [(0, 0, {'analito': line.analito,
                                'resultado': line.resultado ,
                                'resultado2': line.resultado2 ,
                                'unidades': line.unidades })
                            for line in laboratorio.analitos_ids]
            labs.append((0,0,{
            'nombre_examen' : laboratorio.nombre_examen,
            'cups' : laboratorio.cups,
            'laboratorio_id': laboratorio.laboratorio_id,
            'analitos_ids' : analitos
            }))
        self.laboratorios_ids = labs
```

<p><em>Note: the analitos_ids field is the one2many field that is inside the laboratorios_ids field which is also one2many.</em></p>

<p>The others models extructure</p>

<pre class="lang-py prettyprint-override"><code>class resullab(models.Model):
    _name = 'resullab'
    analitos_ids = fields.One2many('analito','laboratorio_id',
                                   'Analitos Lab', ondelete='cascade')

class labs_analito(models.Model):
    _name = 'analito'
    laboratorio_id = fields.Many2one('laboratorios', 'Lab Parent')
</code>```

Thanks for help!

答:
The only reason I can see here is the missing many2one reference in analitos. This 'analitos_ids' : analitos refers to which many2one model that record id must be specified.

```<code>def cargar_pool_labs(self):
  labs = []
  pool = self.env['mymodel'].sudo().search([])
  for laboratorio in pool:
      analitos = [(0, 0, {'analito': line.analito, 'resultado': line.resultado , 'resultado2': line.resultado2 , 'unidades':            line.unidades, }) for line in laboratorio.analitos_ids]
      labs.append((0,0,{'nombre_examen' : laboratorio.nombre_examen,
     'cups' : laboratorio.cups, 'laboratorio_id': laboratorio.laboratorio_id.id, 'analitos_ids' : analitos}))
  self.laboratorios_ids = labs
</code>```

And one more thing many2one reference must be id not an object. In your code it's an object not ID.

```<code>'laboratorio_id': laboratorio.laboratorio_id.id
</code>```

Solution:

The many2one field 'hc_id' in resullab model is missing.

```<code>'hc_id' : self.id #(here the id of 'hc' model required).
</code>```

analitos = [(0, 0, {'hc_id': id of resullab_object.id})]

This might helps you.

Filling default value for one2many model

Body:
Using an on_change method I am trying to send default values to a one2many field using the concept of (0,0, {list values}; even there it works fine but inside that one2many there is also a one2many field to which I must also send values to implement In my code the same concept of (0,0, {list values}, but I did not get success.

Could you help me?.

Attached fragment of my code

class hc(models.Model):
    _name = 'hc'
    laboratorios_ids = fields.One2many(
        string='Laboratorios', comodel_name='resullab',
        inverse_name='hc_id')

    def cargar_pool_labs(self):
        labs = []
        pool = self.env['mymodel'].sudo().search([])
        for laboratorio in pool:
            analitos = [(0, 0, {'analito': line.analito,
                                'resultado': line.resultado ,
                                'resultado2': line.resultado2 ,
                                'unidades': line.unidades })
                            for line in laboratorio.analitos_ids]
            labs.append((0,0,{
            'nombre_examen' : laboratorio.nombre_examen,
            'cups' : laboratorio.cups,
            'laboratorio_id': laboratorio.laboratorio_id,
            'analitos_ids' : analitos
            }))
        self.laboratorios_ids = labs

Note: the analitos_ids field is the one2many field that is inside the laboratorios_ids field which is also one2many.

The others models extructure

class resullab(models.Model):
    _name = 'resullab'
    analitos_ids = fields.One2many('analito','laboratorio_id',
                                   'Analitos Lab', ondelete='cascade')

class labs_analito(models.Model):
    _name = 'analito'
    laboratorio_id = fields.Many2one('laboratorios', 'Lab Parent')

Thanks for help!

Body:
The only reason I can see here is the missing many2one reference in analitos. This 'analitos_ids' : analitos refers to which many2one model that record id must be specified.

def cargar_pool_labs(self):
  labs = []
  pool = self.env['mymodel'].sudo().search([])
  for laboratorio in pool:
      analitos = [(0, 0, {'analito': line.analito, 'resultado': line.resultado , 'resultado2': line.resultado2 , 'unidades':            line.unidades, }) for line in laboratorio.analitos_ids]
      labs.append((0,0,{'nombre_examen' : laboratorio.nombre_examen,
     'cups' : laboratorio.cups, 'laboratorio_id': laboratorio.laboratorio_id.id, 'analitos_ids' : analitos}))
  self.laboratorios_ids = labs

And one more thing many2one reference must be id not an object. In your code it's an object not ID.

'laboratorio_id': laboratorio.laboratorio_id.id

Solution:

The many2one field 'hc_id' in resullab model is missing.

'hc_id' : self.id #(here the id of 'hc' model required).

analitos = [(0, 0, {'hc_id': id of resullab_object.id})]

This might helps you.

Filling default value for one2many model


问:
Mongoose custom validator: check if value exists in database
I am currently trying to add a custom validator to my schema. For some reason I cannot query the database. Does anyone know a solution for my problem?

This is the schema:

```<code>var Portfolio = new Schema({
    title: {
        type: String,
        required: [true, 'Title is required']
    },
    thumbnail: {
        type: String,
        required: [true, 'Thumbnail is required'],
    },
    description: String,
    date: Date,
    images: [String],
    categories: [Schema.Types.ObjectId],
    order: Number,
    slug: {
        type: String,
        validate: {
            validator: slugExists,
            message: 'Slug already exists, choose a different title',
        }
    }
}, options);
</code>```

This is the method that checks whether the data exists:

```<code>function slugExists(value) {
    this.model.count({slug: value}, function(err, count) {
        if (error) {
            return err;
        }
        return count > 0;
    });
}
</code>```

When I run the application I get the following error message:

```<code>TypeError: this.model.count is not a function
</code>```

I have also tried to use the following:

```<code>mongoose.model['portfolio'].count(...)
</code>```

but the result is the same.

I have been trying to fix the problem for two hours now, even tried different approaches (for example the pre hook). But adding the custom validation directly to the Schema feels like the cleanest entry.

Hope you have a solution for me. Many thanks in advance!

Jeffrey

答:
Can use the pre-save method
Consider the example below where trying to validate username in user model  :

```<code>   UserSchema.pre('save', function (next) {
   var self = this;
   mongoose.models["User"].findOne({username: self.username}, function (err, user) {
      if (!user) {
          next();
      } else {
          next(new Error("Username already exists!"));
      }
  });
</code>```

Body:
I am currently trying to add a custom validator to my schema. For some reason I cannot query the database. Does anyone know a solution for my problem?

This is the schema:

var Portfolio = new Schema({
    title: {
        type: String,
        required: [true, 'Title is required']
    },
    thumbnail: {
        type: String,
        required: [true, 'Thumbnail is required'],
    },
    description: String,
    date: Date,
    images: [String],
    categories: [Schema.Types.ObjectId],
    order: Number,
    slug: {
        type: String,
        validate: {
            validator: slugExists,
            message: 'Slug already exists, choose a different title',
        }
    }
}, options);

This is the method that checks whether the data exists:

function slugExists(value) {
    this.model.count({slug: value}, function(err, count) {
        if (error) {
            return err;
        }
        return count > 0;
    });
}

When I run the application I get the following error message:

TypeError: this.model.count is not a function

I have also tried to use the following:

mongoose.model['portfolio'].count(...)

but the result is the same.

I have been trying to fix the problem for two hours now, even tried different approaches (for example the pre hook). But adding the custom validation directly to the Schema feels like the cleanest entry.

Hope you have a solution for me. Many thanks in advance!

Jeffrey

Body:
Can use the pre-save method
Consider the example below where trying to validate username in user model  :

   UserSchema.pre('save', function (next) {
   var self = this;
   mongoose.models["User"].findOne({username: self.username}, function (err, user) {
      if (!user) {
          next();
      } else {
          next(new Error("Username already exists!"));
      }
  });


问:
setMinValue on NumberPicker doesn't select the correct min value
I want to create a NumberPicker with an array of displayed values. The values are not supposed to change when the NumberPicker is displayed, but the min and max values change dynamically depending on user action.

Here is the code:

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

    <NumberPicker
        android:id="@+id/picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
</RelativeLayout>
</code>```

In Main Activity

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final String[] values = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};

        NumberPicker picker = (NumberPicker) findViewById(R.id.picker);
        picker.setDisplayedValues(values);
        picker.setMaxValue(7);
        picker.setMinValue(3);

        picker.setWrapSelectorWheel(false);
    }
}
</code>```

When I set the maximum without setting the minimum, I end with displayed values between "0" and "7" (included). If I set the minValue to 0 I have the same behaviour.
But if I set the minValue to 3 I end with displayed values between "0" and "4". When it's supposed to be between "3" and "7".

I don't understand why. Have I done something wrong or is there an issue with the component?

答:
for brevity to @Bmuig answer, just a helper function:</p>

```<code>private void configurePicker(NumberPicker picker, ArrayList<String> values, int minValue, int maxValue, int currentValue) {
    picker.setDisplayedValues(values) //to avoid out of bounds
    picker.setMinValue(minValue);
    picker.setMaxValue(maxValue);
    picker.setValue(currentValue);
    picker.setDisplayedValues((String[]) values.subList(minValue, maxValue + 1).toArray());
}
</code>```

Body:
I want to create a NumberPicker with an array of displayed values. The values are not supposed to change when the NumberPicker is displayed, but the min and max values change dynamically depending on user action.

Here is the code:

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

    <NumberPicker
        android:id="@+id/picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
</RelativeLayout>

In Main Activity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final String[] values = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};

        NumberPicker picker = (NumberPicker) findViewById(R.id.picker);
        picker.setDisplayedValues(values);
        picker.setMaxValue(7);
        picker.setMinValue(3);

        picker.setWrapSelectorWheel(false);
    }
}

When I set the maximum without setting the minimum, I end with displayed values between "0" and "7" (included). If I set the minValue to 0 I have the same behaviour.
But if I set the minValue to 3 I end with displayed values between "0" and "4". When it's supposed to be between "3" and "7".

I don't understand why. Have I done something wrong or is there an issue with the component?

Body:
for brevity to @Bmuig answer, just a helper function:

private void configurePicker(NumberPicker picker, ArrayList<String> values, int minValue, int maxValue, int currentValue) {
    picker.setDisplayedValues(values) //to avoid out of bounds
    picker.setMinValue(minValue);
    picker.setMaxValue(maxValue);
    picker.setValue(currentValue);
    picker.setDisplayedValues((String[]) values.subList(minValue, maxValue + 1).toArray());
}


问:
Stop setInterval() without global variables
I am looking to start then later stop a setInterval, all examples that I've come across do this with a global variable, but I'd rather not use one if I can.

I have a button to start the setInterval and another to stop it. I can start it just fine, but I am unable to stop it without using a global variable.

This is what I have:

```<code>function counter() {
  function stop() {
    clearInterval(timer);
  }
  var timer = setInterval(function() {
    console.log(new Date());
  }, 1000);
  return stop;
}
$('#start').click(function() {
  counter();
});
$('#stop').click(function() {
  stop(); // this of course doesn't work
});
</code>```

答:
I think you require a static variable. But Unfortunately, javascript doesn't support static variables. However, we can create one. Because as in javascript functions are interpreted as objects so they could have static scope variable.

function counter() {
    if (typeof counter.timer == 'undefined') {
        counter.timer = 0;
    }
    counter.timer = setInterval(function() {
        $("#output").text(new Date());
    }, 1000);
}

function stop() {
    clearInterval(counter.timer);
}
$("#start").on('click', function() {
    counter();
});
$("#stop").on('click', function() {
    stop();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="start">start</button>
 <button type="button" id="stop">stop</button>
  <p id="output"></p></code>```

Body:
I am looking to start then later stop a setInterval, all examples that I've come across do this with a global variable, but I'd rather not use one if I can.

I have a button to start the setInterval and another to stop it. I can start it just fine, but I am unable to stop it without using a global variable.

This is what I have:

function counter() {
  function stop() {
    clearInterval(timer);
  }
  var timer = setInterval(function() {
    console.log(new Date());
  }, 1000);
  return stop;
}
$('#start').click(function() {
  counter();
});
$('#stop').click(function() {
  stop(); // this of course doesn't work
});

Body:
I think you require a static variable. But Unfortunately, javascript doesn't support static variables. However, we can create one. Because as in javascript functions are interpreted as objects so they could have static scope variable.

function counter() {
    if (typeof counter.timer == 'undefined') {
        counter.timer = 0;
    }
    counter.timer = setInterval(function() {
        $("#output").text(new Date());
    }, 1000);
}

function stop() {
    clearInterval(counter.timer);
}
$("#start").on('click', function() {
    counter();
});
$("#stop").on('click', function() {
    stop();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="start">start</button>
 <button type="button" id="stop">stop</button>
  <p id="output"></p>


问:
Async load multiple images to single cell
I have a problem with loading of 5 images to each cell of TableView. I use AFNetworking for download and setImageWithUrl method for imageView:

```<code>for (int i = 0; i < urls.count; i++) {
    [self.photoImageView[i] setImageWithURL:urls[i]];
}
</code>```

TableView very brakes when I scroll it. But when i try to load 1 or 2  no brakes when scrolling.

How to correct download images without brakes?

答:
I think's it's helpful for you below the code work for me.

First fall you use this library SDWebImage
then implement below code.

```<code>#import <SDWebImage/UIImageView+WebCache.h>
...
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"URL"]
             placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
</code>```

Body:
I have a problem with loading of 5 images to each cell of TableView. I use AFNetworking for download and setImageWithUrl method for imageView:

for (int i = 0; i < urls.count; i++) {
    [self.photoImageView[i] setImageWithURL:urls[i]];
}

TableView very brakes when I scroll it. But when i try to load 1 or 2  no brakes when scrolling.

How to correct download images without brakes?

Body:
I think's it's helpful for you below the code work for me.

First fall you use this library SDWebImage
then implement below code.

#import <SDWebImage/UIImageView+WebCache.h>
...
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"URL"]
             placeholderImage:[UIImage imageNamed:@"placeholder.png"]];


问:
How to change line color in EditText
I am creating an EditText in my layout xml file

But I want to change color line in EditText from Holo to (for example) red.
How that can be done?

答:
Programmatically, you can try:</p>

```<code>editText.getBackground().mutate().setColorFilter(getResources().getColor(android.R.color.holo_red_light), PorterDuff.Mode.SRC_ATOP);
</code>```

Title: How to change line color in EditText

Body:
Programmatically, you can try:

editText.getBackground().mutate().setColorFilter(getResources().getColor(android.R.color.holo_red_light), PorterDuff.Mode.SRC_ATOP);


问:
how to get parent div data-attribute javascript
I have a HTML structure like this :

```<code><div class="page" data-page-number="29" data-page-label="18" data-loaded="true" style="width: 816px; height: 1056px;">
   <div class="canvasWrapper" style="width: 816px; height: 1056px;">
      <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>
   </div>
   <div class="textLayer" style="width: 816px; height: 1056px;">
        some content
   </div>
</div>

    <div class="page" data-page-number="29" data-page-label="18" data-loaded="true" style="width: 816px; height: 1056px;">
       <div class="canvasWrapper" style="width: 816px; height: 1056px;">
          <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>
       </div>
       <div class="textLayer" style="width: 816px; height: 1056px;">
            some content
       </div>
    </div>
</code>```

I want to know that when I click on any textLayer class, I will get data-page-number="x" attribute from its parent .page div.

Only javascript solution required here.

This is basically PDF.js structure.

答:
You could use parentNode.dataset to retrieve data attribute of parent node.

var textLayer = document.querySelector('.textLayer');
textLayer.addEventListener('click', function(e) {
  console.log('page number: ' + e.target.parentNode.dataset.pageNumber);
  console.log('label: ' + e.target.parentNode.dataset.pageLabel);
  console.log('loaded: ' + e.target.parentNode.dataset.loaded);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page" data-page-number="29" data-page-label="18" data-loaded="true" style="width: 816px; height: 1056px;">
  <div class="canvasWrapper" style="width: 816px; height: 1056px;">
    <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>
  </div>
  <div class="textLayer" style="width: 816px; height: 1056px;">
    some content
  </div>
</div></code>```

Body:
I have a HTML structure like this :

      <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>

        some content

          <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>

            some content

I want to know that when I click on any textLayer class, I will get data-page-number="x" attribute from its parent .page div.

Only javascript solution required here.

This is basically PDF.js structure.

Body:
You could use parentNode.dataset to retrieve data attribute of parent node.

var textLayer = document.querySelector('.textLayer');
textLayer.addEventListener('click', function(e) {
  console.log('page number: ' + e.target.parentNode.dataset.pageNumber);
  console.log('label: ' + e.target.parentNode.dataset.pageLabel);
  console.log('loaded: ' + e.target.parentNode.dataset.loaded);
});

<div class="page" data-page-number="29" data-page-label="18" data-loaded="true" style="width: 816px; height: 1056px;">
  <div class="canvasWrapper" style="width: 816px; height: 1056px;">
    <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>
  </div>
  <div class="textLayer" style="width: 816px; height: 1056px;">
    some content
  </div>
</div>


问:
CRON Job using Curl.
I have a PHP Code, which reloads itself with another GET value. Like: example.com?number=453 and it keeps doing this for days. I was doing this in the browser. But i found cron job is way better.

So, I need to use CURL to reload the page with a new GET value like ?number=550. So this is the code, which i use (found it on stackoverflow)

```<code>function curl_download($Url){

    // is cURL installed yet?
    if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }

    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();

    // Now set some options (most are optional)

    // Set URL to download
    curl_setopt($ch, CURLOPT_URL, $Url);

    // Set a referer
    curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");

    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");

    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    // Download the given URL, and return output
    $output = curl_exec($ch);

    // Close the cURL resource, and free system resources
    curl_close($ch);

    return $output;
}

$output = curl_download("http://www.example.com/yourscript.php?number='$requestsDone'");
</code>```

And at the end of the page, i use this, to call the function

```<code>curl_download($Url);
</code>```

But i am getting this error:

Notice: Undefined variable: Url

in the last line, i.e curl_download($Url);

This is how we call the function right? What's wrong? Also is there any mistake or improvement, I can make in the code?

答:
You not assign values to variables $Url.
Before you can assign values to variables $Url. That like ```<code>$Url = "http://domaintest.com/?number=550";
curl_download($Url);
</code>```</p>

Title: CRON Job using Curl.

Body:
I have a PHP Code, which reloads itself with another GET value. Like: example.com?number=453 and it keeps doing this for days. I was doing this in the browser. But i found cron job is way better.

So, I need to use CURL to reload the page with a new GET value like ?number=550. So this is the code, which i use (found it on stackoverflow)

function curl_download($Url){

    // is cURL installed yet?
    if (!function_exists('curl_init')){
        die('Sorry cURL is not installed!');
    }

    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();

    // Now set some options (most are optional)

    // Set URL to download
    curl_setopt($ch, CURLOPT_URL, $Url);

    // Set a referer
    curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");

    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");

    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    // Download the given URL, and return output
    $output = curl_exec($ch);

    // Close the cURL resource, and free system resources
    curl_close($ch);

    return $output;
}

$output = curl_download("http://www.example.com/yourscript.php?number='$requestsDone'");

And at the end of the page, i use this, to call the function

curl_download($Url);

But i am getting this error:

Notice: Undefined variable: Url

in the last line, i.e curl_download($Url);

This is how we call the function right? What's wrong? Also is there any mistake or improvement, I can make in the code?

Body:
You not assign values to variables $Url.
Before you can assign values to variables $Url. That like
$Url = "http://domaintest.com/?number=550";
curl_download($Url);


问:
Sequelize Associate not found
I have a project I'm trying to use sequelize on. It creates the database and tables fine, but it never finds the associate class method, so it never calls the associate method.

This code works fine to create the tables (using the import method) but the Object.keys(db) iterates over each model, but it never finds the associate method.

```<code>fs.readdirSync('./models')
    .filter(function (file) {
        return (file.indexOf('.') !== 0) && (file !== 'index.js') && (file.indexOf('.js') > 0) && (file.indexOf('relations.js') !== 0 );
    })

    .forEach(function (file) {
        var model = sequelize.import('../models/' + file);
        db[model.name] = model;
    });

Object.keys(db).forEach(function (modelName) {
        if (db[modelName].associate) {
            db[modelName].associate(db);
            console.log('true');
        }
        else {
            console.log('false');

        }
    }
);
</code>```

Class Code Example:

module.exports = function (sequelize, DataTypes) {

```<code>let userModel = sequelize.define('user', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    email: {
        type: DataTypes.STRING,
        validate: {
            isEmail: true
        },
        allowNull: false
    }
}, {
    classMethods: {
        associate: function (models) {
            let createdByoptions = {
                foreignKey: 'createdByUserID'
            };
            let emailOptions = {
                foreignKey: 'emailAddressID'
            };

            userModel.hasOne(models.user, createdByoptions);
            userModel.hasOne(models.email, emailOptions)

            //userModel.hasMany(models.tenant, {foreignKey: 'id'});

        },
        addUser: function (identityID) {
            userModel.create({identityUserID: identityID});
        }
    }
});

return userModel;
</code>```

};

答:
Sequelize has changed how associations and instance methods are defined, post version >4.

So Associations earlier defined as (for version <4)

```<code>const Model = sequelize.define('Model', {
...
}, {
classMethods: {
    associate: function (model) {...}
},
instanceMethods: {
    someMethod: function () { ...}
}
});
</code>```

Should now be defined as

```<code>const Model = sequelize.define('Model', {
...
});

// Class Method
Model.belongsTo(SomeOtherModel);
</code>```

Check the upgrade guide and docs

Title: Sequelize Associate not found

Body:
I have a project I'm trying to use sequelize on. It creates the database and tables fine, but it never finds the associate class method, so it never calls the associate method.

This code works fine to create the tables (using the import method) but the Object.keys(db) iterates over each model, but it never finds the associate method.

fs.readdirSync('./models')
    .filter(function (file) {
        return (file.indexOf('.') !== 0) && (file !== 'index.js') && (file.indexOf('.js') > 0) && (file.indexOf('relations.js') !== 0 );
    })

    .forEach(function (file) {
        var model = sequelize.import('../models/' + file);
        db[model.name] = model;
    });

Object.keys(db).forEach(function (modelName) {
        if (db[modelName].associate) {
            db[modelName].associate(db);
            console.log('true');
        }
        else {
            console.log('false');

        }
    }
);

Class Code Example:

module.exports = function (sequelize, DataTypes) {

let userModel = sequelize.define('user', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    email: {
        type: DataTypes.STRING,
        validate: {
            isEmail: true
        },
        allowNull: false
    }
}, {
    classMethods: {
        associate: function (models) {
            let createdByoptions = {
                foreignKey: 'createdByUserID'
            };
            let emailOptions = {
                foreignKey: 'emailAddressID'
            };

            userModel.hasOne(models.user, createdByoptions);
            userModel.hasOne(models.email, emailOptions)

            //userModel.hasMany(models.tenant, {foreignKey: 'id'});

        },
        addUser: function (identityID) {
            userModel.create({identityUserID: identityID});
        }
    }
});

return userModel;

};

Body:
Sequelize has changed how associations and instance methods are defined, post version >4.

So Associations earlier defined as (for version <4)

const Model = sequelize.define('Model', {
...
}, {
classMethods: {
    associate: function (model) {...}
},
instanceMethods: {
    someMethod: function () { ...}
}
});

Should now be defined as

const Model = sequelize.define('Model', {
...
});

// Class Method
Model.belongsTo(SomeOtherModel);

Check the upgrade guide and docs


答:
You can use the java-script Closures for this, change your codes to this :

```<code>function counter (action, tId) {
   var timer =setInterval(function() {
    console.log(new Date());
 }, 1000);
 if(typeof tId!="undefined")
    window.clearInterval(tId);
   return function () {
    if(action=='stop'){
    counter('stop', timer)
   }
  }
 }

 $('#start').click(function() {
  counter('start');
 });
 $('#stop').click(function() {
   counter('stop');
 });
</code>```

Actually what we do is to re-call the function with interval-id if action is stop.

Title: Stop setInterval() without global variables

Body:
You can use the java-script Closures for this, change your codes to this :

function counter (action, tId) {
   var timer =setInterval(function() {
    console.log(new Date());
 }, 1000);
 if(typeof tId!="undefined")
    window.clearInterval(tId);
   return function () {
    if(action=='stop'){
    counter('stop', timer)
   }
  }
 }

 $('#start').click(function() {
  counter('start');
 });
 $('#stop').click(function() {
   counter('stop');
 });

Actually what we do is to re-call the function with interval-id if action is stop.


问:
Asp.Net Core v1.1 Get Inherited Class Names From another project in same solution
I m working with different inherited classes i want get this class names inherited from same interface

```<code>public class CollectorA : ICollector
{
    public string CollectSomething()
    {
        //DO Something
    }
}
public class CollectorB : ICollector
{
    public string CollectSomething()
    {
        //DO Something
    }
}
</code>```

I want to do like :

```<code>public void Init(IServiceCollection serviceCollection)
{

    var types  = AppDomain.CurrentDomain.GetAssemblies()
                          .SelectMany(assembly => assembly.GetTypes())
                          .Where(type => type.IsInstanceOfType(typeof(ICollector)));
</code>```

Getting types returns null I tried AppContext but still not works.

```<code>foreach(var item in types)
{
    serviceCollection.AddTransient<ICollector,item.Name>();
}
</code>```

答:
There is no AppDomain in .NET Core so this
  AppDomain.CurrentDomain.GetAssemblies() is not there as well(None of
  .NET Standard 1.x has it.) Here's the GitHub issue detailing
  this.

If you would like to go with the approach of PolyFill (AppDomain) in the blog,here's the code

```<code>public class AppDomain
 {
    public static AppDomain CurrentDomain { get; private set; }

    static AppDomain()
    {
        CurrentDomain = new AppDomain();
    }

    public Assembly[] GetAssemblies()
    {
        var assemblies = new List<Assembly>();
        var dependencies = DependencyContext.Default.RuntimeLibraries;
        foreach (var library in dependencies)
        {
            if (IsCandidateCompilationLibrary(library))
            {
                var assembly = Assembly.Load(new AssemblyName(library.Name));
                assemblies.Add(assembly);
            }
        }
        return assemblies.ToArray();
    }

    private static bool IsCandidateCompilationLibrary(RuntimeLibrary compilationLibrary)
    {
        return compilationLibrary.Name == ("Specify")
            || compilationLibrary.Dependencies.Any(d => d.Name.StartsWith("Specify"));
    }
}
</code>```

And then You can use like this

```<code>var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(ass => ass.ExportedTypes)
                          .Where(type => type.IsInstanceOfType(typeof(ICollector)));
            foreach (var item in types)
            {
                services.AddTransient(typeof(ICollector), item);
            }
</code>```

For an alternate approach, Please refer this SO post to get an alternative for GetAssemblies() or Types .

Body:
I m working with different inherited classes i want get this class names inherited from same interface

public class CollectorA : ICollector
{
    public string CollectSomething()
    {
        //DO Something
    }
}
public class CollectorB : ICollector
{
    public string CollectSomething()
    {
        //DO Something
    }
}

I want to do like :

public void Init(IServiceCollection serviceCollection)
{

    var types  = AppDomain.CurrentDomain.GetAssemblies()
                          .SelectMany(assembly => assembly.GetTypes())
                          .Where(type => type.IsInstanceOfType(typeof(ICollector)));

Getting types returns null I tried AppContext but still not works.

foreach(var item in types)
{
    serviceCollection.AddTransient<ICollector,item.Name>();
}

Body:
There is no AppDomain in .NET Core so this
  AppDomain.CurrentDomain.GetAssemblies() is not there as well(None of
  .NET Standard 1.x has it.) Here's the GitHub issue detailing
  this.

If you would like to go with the approach of PolyFill (AppDomain) in the blog,here's the code

public class AppDomain
 {
    public static AppDomain CurrentDomain { get; private set; }

    static AppDomain()
    {
        CurrentDomain = new AppDomain();
    }

    public Assembly[] GetAssemblies()
    {
        var assemblies = new List<Assembly>();
        var dependencies = DependencyContext.Default.RuntimeLibraries;
        foreach (var library in dependencies)
        {
            if (IsCandidateCompilationLibrary(library))
            {
                var assembly = Assembly.Load(new AssemblyName(library.Name));
                assemblies.Add(assembly);
            }
        }
        return assemblies.ToArray();
    }

    private static bool IsCandidateCompilationLibrary(RuntimeLibrary compilationLibrary)
    {
        return compilationLibrary.Name == ("Specify")
            || compilationLibrary.Dependencies.Any(d => d.Name.StartsWith("Specify"));
    }
}

And then You can use like this

var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(ass => ass.ExportedTypes)
                          .Where(type => type.IsInstanceOfType(typeof(ICollector)));
            foreach (var item in types)
            {
                services.AddTransient(typeof(ICollector), item);
            }

For an alternate approach, Please refer this SO post to get an alternative for GetAssemblies() or Types .


问:
Can Google robots see my S3 contents?
I have an S3 bucket with confidential files for many users. I am sending emails to specific users containing a pre-signed URL to access their specific confidential file.

Are there security issues I am risking with Google robots being able to view these contents in these S3 pre-signed URLs? Can I do anything to prevent this?

答:
Private objects in Amazon S3 are not accessible by default.

You are using a pre-signed URL, which permits access to a specific object until a specific date/time.

Yes, if Google (or somebody else) got hold of the pre-signed URL, they would also be able to read the object. Therefore, do not publicly reveal a pre-signed URL. Think of it like a time-limited password -- if somebody had your password, they could act as if they were you. Therefore, keep your pre-signed URLs as safe as you would keep a password.

Title: Can Google robots see my S3 contents?


问:
How to loop through array and ignore selected value
```<code>String response = "[\n" +
        "  {\n" +
        "    \"id\": 1,\n" +
        "    \"name\": \"What is your your father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 2,\n" +
        "    \"name\": \"What is your mother's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 3,\n" +
        "    \"name\": \"What is your brother's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 4,\n" +
        "    \"name\": \"What is your father's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 5,\n" +
        "    \"name\": \"What is your sister's father name\"\n" +
        "  }\n" +
        "]";
</code>```

I have this set of questions and I wanted to loop through it to show in Dialog list. There are going to be 2 AlertDialog and if user select the value from one of the AlertDialog. The questions wont show in the other AlerDialog. For the loops, this is my code:

```<code>public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.q1:
                try {
                    JSONArray jsonArray = new JSONArray(response);
                    if (selected2>-1)
                        q1 = new String[jsonArray.length()-1];
                    else
                        q1 = new String[jsonArray.length()];
                    int index = 0;

                    for (int x = 0; x<jsonArray.length(); x++){
                        idQuestion[index] = jsonArray.getJSONObject(x).getInt("id");
                        if (selected2==x)
                            continue;
                        q1[index]= jsonArray.getJSONObject(x).getString("name");
                        index++;
                    }

                    AlertDialog alertDialog =new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.select_security_question)
                            .setItems(q1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    question1.setText(q1[which]);
                                    if(selected == -1) {
                                        selected = which;
                                    } else {
                                        selected = which+1;
                                    }
                                }
                            }).create();
                    alertDialog.show();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;

            case R.id.q2:
                try {
                    JSONArray ja = new JSONArray(response);
                    if (selected>-1)
                        q2 = new String[ja.length()-1];
                    else
                        q2 = new String[ja.length()];
                    int index = 0;
                    for (int x = 0; x<ja.length(); x++){
                        if (selected==x)
                            continue;
                        q2[index] = ja.getJSONObject(x).getString("name");
                        index++;
                    }
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.select_security_question)
                            .setItems(q2, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    question2.setText(q2[which]);
                                    selected2 = which;
                                    if(selected2 == -1) {
                                        selected2 = which;
                                    } else {
                                        selected2 = which+1;
                                    }
                                }
                            }).create();
                    alertDialog.show();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
</code>```

But I found that this logic is wrong.Questions are form server, that's why its is JSON format. If possible I want to use the id of the questions., since I'll have to return the value of id, not the question.

答: To ignore values inside a loop use if(id==id_ignored) continue;

Body:
String response = "[\n" +
        "  {\n" +
        "    \"id\": 1,\n" +
        "    \"name\": \"What is your your father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 2,\n" +
        "    \"name\": \"What is your mother's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 3,\n" +
        "    \"name\": \"What is your brother's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 4,\n" +
        "    \"name\": \"What is your father's father name\"\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 5,\n" +
        "    \"name\": \"What is your sister's father name\"\n" +
        "  }\n" +
        "]";

I have this set of questions and I wanted to loop through it to show in Dialog list. There are going to be 2 AlertDialog and if user select the value from one of the AlertDialog. The questions wont show in the other AlerDialog. For the loops, this is my code:

public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.q1:
                try {
                    JSONArray jsonArray = new JSONArray(response);
                    if (selected2>-1)
                        q1 = new String[jsonArray.length()-1];
                    else
                        q1 = new String[jsonArray.length()];
                    int index = 0;

                    for (int x = 0; x<jsonArray.length(); x++){
                        idQuestion[index] = jsonArray.getJSONObject(x).getInt("id");
                        if (selected2==x)
                            continue;
                        q1[index]= jsonArray.getJSONObject(x).getString("name");
                        index++;
                    }

                    AlertDialog alertDialog =new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.select_security_question)
                            .setItems(q1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    question1.setText(q1[which]);
                                    if(selected == -1) {
                                        selected = which;
                                    } else {
                                        selected = which+1;
                                    }
                                }
                            }).create();
                    alertDialog.show();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;

            case R.id.q2:
                try {
                    JSONArray ja = new JSONArray(response);
                    if (selected>-1)
                        q2 = new String[ja.length()-1];
                    else
                        q2 = new String[ja.length()];
                    int index = 0;
                    for (int x = 0; x<ja.length(); x++){
                        if (selected==x)
                            continue;
                        q2[index] = ja.getJSONObject(x).getString("name");
                        index++;
                    }
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.select_security_question)
                            .setItems(q2, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    question2.setText(q2[which]);
                                    selected2 = which;
                                    if(selected2 == -1) {
                                        selected2 = which;
                                    } else {
                                        selected2 = which+1;
                                    }
                                }
                            }).create();
                    alertDialog.show();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }

But I found that this logic is wrong.Questions are form server, that's why its is JSON format. If possible I want to use the id of the questions., since I'll have to return the value of id, not the question.