问:
Image is not showing in imageview when set image dynamic
Here my layout where I am set a static image and it show successfully but when I set dynamic it don't update that previous image. This is my imageview edit_profile_civ_profile_image

```<code>    <include layout="@layout/content_edit_profile" />

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:contentInsetStart="0dp">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            app:contentInsetStart="0dp"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:titleEnabled="false">

            <RelativeLayout
                android:id="@+id/header"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/orange_1">

                <TextView
                    android:id="@+id/profile_tv_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_margin="@dimen/_15sdp"
                    android:gravity="center"
                    android:text="@string/profile"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/_16sdp" />

                <android.support.design.widget.CoordinatorLayout
                    android:id="@+id/profile_iv_image"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/profile_tv_title"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="@dimen/_30sdp">

                    <de.hdodenhof.circleimageview.CircleImageView
                        android:id="@+id/edit_profile_civ_profile_image"
                        android:layout_width="@dimen/_80sdp"
                        android:layout_height="@dimen/_80sdp"
                        android:src="@mipmap/selected"
                        app:civ_border_color="@color/orange_1"
                        app:civ_border_width="@dimen/_2sdp" />

                    <android.support.design.widget.FloatingActionButton
                        android:id="@+id/edtProfile"
                        android:layout_width="@dimen/_25sdp"
                        android:layout_height="@dimen/_25sdp"
                        android:src="@mipmap/ic_camera_orange"
                        app:backgroundTint="@android:color/white"
                        app:fabSize="mini"
                        app:layout_anchor="@id/edit_profile_civ_profile_image"
                        app:layout_anchorGravity="bottom|right|end" />

                </android.support.design.widget.CoordinatorLayout>

                <de.hdodenhof.circleimageview.CircleImageView
                    android:layout_width="@dimen/_110sdp"
                    android:layout_height="@dimen/_110sdp"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:src="@mipmap/ic_welcome_1"
                    android:visibility="gone"
                    app:civ_border_color="@color/green_1"
                    app:civ_border_width="@dimen/_6sdp" />

                <TextView
                    android:id="@+id/profile_tv_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/profile_iv_image"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="@dimen/_15sdp"
                    android:gravity="center_horizontal"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/_20sdp"
                    tools:text="Abd al Hakim" />

                <TextView
                    android:id="@+id/profile_tv_gender"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/profile_tv_name"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="@dimen/_2sdp"
                    android:gravity="center_horizontal"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/_12sdp"
                    android:visibility="gone"
                    tools:text="Male" />

                <TextView
                    android:id="@+id/profile_tv_mobile_number"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/profile_tv_gender"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="@dimen/_8sdp"
                    android:drawablePadding="@dimen/_10sdp"
                    android:drawableStart="@mipmap/ic_call_white"
                    android:gravity="center_vertical"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/_10sdp"
                    tools:text="+1244-45785621" />

                <TextView
                    android:id="@+id/profile_tv_email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/profile_tv_mobile_number"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginBottom="@dimen/_15sdp"
                    android:layout_marginTop="@dimen/_8sdp"
                    android:drawablePadding="@dimen/_10sdp"
                    android:drawableStart="@mipmap/ic_email"
                    android:gravity="center_vertical"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/_10sdp"
                    tools:text="alhakim0055@gmail.com" />

                <TextView
                    android:id="@+id/profile_tv_edit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/profile_tv_email"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="@dimen/_15sdp"
                    android:background="@drawable/rectangle_rounded_corner_white"
                    android:paddingBottom="@dimen/_5sdp"
                    android:paddingEnd="@dimen/_25sdp"
                    android:paddingStart="@dimen/_25sdp"
                    android:paddingTop="@dimen/_5sdp"
                    android:text="@string/edit_profile"
                    android:textColor="@color/orange_1"
                    android:textSize="@dimen/_12sdp"
                    android:visibility="gone" />

            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:contentInsetStart="0dp"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay">

                <TextView
                    android:id="@+id/profile_tv_activity_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="@string/profile"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/_16sdp"
                    android:visibility="gone" />

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

Here I am set Image in imageview:-

```<code>    public class ProfileActivity extends BaseActivity  {

        private AppBarLayout appBarLayout;

        private ImageView editProfileCivProfileImage;

        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_profile);
    editProfileCivProfileImage = findViewById(R.id.edit_profile_civ_profile_image);

            editProfileCivProfileImage.setImageResource(R.mipmap.ic_launcher);

        }
    }
</code>```

Here BaseActivity:-

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

    protected CompositeDisposable compositeDisposable;

    private ProgressDialog progressDialog;
    private SahelPreferences sahelPreferences;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i("compositeDisposable", ">>" + "new");
        sahelPreferences = new SahelPreferences(this, AppConstant.PREFERENCE_DEFAULT);

        compositeDisposable = new CompositeDisposable();
        progressDialog = new ProgressDialog(this);

        progressDialog.setMessage("Please Wait...");
        progressDialog.setCancelable(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        Log.i("compositeDisposable", ">>" + "clear");
        compositeDisposable.clear();
        hideLoading();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.i("compositeDisposable", ">>" + "dispose");
        compositeDisposable.dispose();
        super.onDestroy();
    }

    public void showLoading() {
        hideLoading();
        progressDialog = CommonUtil.showLoadingDialog(this);
    }

    public void hideLoading() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog.cancel();
        }
    }

    public SahelPreferences getPreferences() {
        return sahelPreferences;
    }
}
</code>```

Anyone can solve this. I am new in Android. Thanks in Advance.

答:
Try this</p>

```<code>editProfileCivProfileImage.setImageDrawable(getResource().getDrawable(R.mipmap.ic_launcher));
</code>```

Body:
Here my layout where I am set a static image and it show successfully but when I set dynamic it don't update that previous image. This is my imageview edit_profile_civ_profile_image

    <include layout="@layout/content_edit_profile" />

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:contentInsetStart="0dp">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            app:contentInsetStart="0dp"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:titleEnabled="false">

            <RelativeLayout
                android:id="@+id/header"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/orange_1">

                <TextView
                    android:id="@+id/profile_tv_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_margin="@dimen/_15sdp"
                    android:gravity="center"
                    android:text="@string/profile"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/_16sdp" />

                <android.support.design.widget.CoordinatorLayout
                    android:id="@+id/profile_iv_image"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/profile_tv_title"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="@dimen/_30sdp">

                    <de.hdodenhof.circleimageview.CircleImageView
                        android:id="@+id/edit_profile_civ_profile_image"
                        android:layout_width="@dimen/_80sdp"
                        android:layout_height="@dimen/_80sdp"
                        android:src="@mipmap/selected"
                        app:civ_border_color="@color/orange_1"
                        app:civ_border_width="@dimen/_2sdp" />

                    <android.support.design.widget.FloatingActionButton
                        android:id="@+id/edtProfile"
                        android:layout_width="@dimen/_25sdp"
                        android:layout_height="@dimen/_25sdp"
                        android:src="@mipmap/ic_camera_orange"
                        app:backgroundTint="@android:color/white"
                        app:fabSize="mini"
                        app:layout_anchor="@id/edit_profile_civ_profile_image"
                        app:layout_anchorGravity="bottom|right|end" />

                </android.support.design.widget.CoordinatorLayout>

                <de.hdodenhof.circleimageview.CircleImageView
                    android:layout_width="@dimen/_110sdp"
                    android:layout_height="@dimen/_110sdp"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:src="@mipmap/ic_welcome_1"
                    android:visibility="gone"
                    app:civ_border_color="@color/green_1"
                    app:civ_border_width="@dimen/_6sdp" />

                <TextView
                    android:id="@+id/profile_tv_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/profile_iv_image"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="@dimen/_15sdp"
                    android:gravity="center_horizontal"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/_20sdp"
                    tools:text="Abd al Hakim" />

                <TextView
                    android:id="@+id/profile_tv_gender"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/profile_tv_name"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="@dimen/_2sdp"
                    android:gravity="center_horizontal"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/_12sdp"
                    android:visibility="gone"
                    tools:text="Male" />

                <TextView
                    android:id="@+id/profile_tv_mobile_number"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/profile_tv_gender"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="@dimen/_8sdp"
                    android:drawablePadding="@dimen/_10sdp"
                    android:drawableStart="@mipmap/ic_call_white"
                    android:gravity="center_vertical"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/_10sdp"
                    tools:text="+1244-45785621" />

                <TextView
                    android:id="@+id/profile_tv_email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/profile_tv_mobile_number"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginBottom="@dimen/_15sdp"
                    android:layout_marginTop="@dimen/_8sdp"
                    android:drawablePadding="@dimen/_10sdp"
                    android:drawableStart="@mipmap/ic_email"
                    android:gravity="center_vertical"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/_10sdp"
                    tools:text="alhakim0055@gmail.com" />

                <TextView
                    android:id="@+id/profile_tv_edit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/profile_tv_email"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="@dimen/_15sdp"
                    android:background="@drawable/rectangle_rounded_corner_white"
                    android:paddingBottom="@dimen/_5sdp"
                    android:paddingEnd="@dimen/_25sdp"
                    android:paddingStart="@dimen/_25sdp"
                    android:paddingTop="@dimen/_5sdp"
                    android:text="@string/edit_profile"
                    android:textColor="@color/orange_1"
                    android:textSize="@dimen/_12sdp"
                    android:visibility="gone" />

            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:contentInsetStart="0dp"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay">

                <TextView
                    android:id="@+id/profile_tv_activity_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="@string/profile"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/_16sdp"
                    android:visibility="gone" />

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>

Here I am set Image in imageview:-

    public class ProfileActivity extends BaseActivity  {

        private AppBarLayout appBarLayout;

        private ImageView editProfileCivProfileImage;

        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_profile);
    editProfileCivProfileImage = findViewById(R.id.edit_profile_civ_profile_image);

            editProfileCivProfileImage.setImageResource(R.mipmap.ic_launcher);

        }
    }

Here BaseActivity:-

    public class BaseActivity extends AppCompatActivity {

    protected CompositeDisposable compositeDisposable;

    private ProgressDialog progressDialog;
    private SahelPreferences sahelPreferences;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i("compositeDisposable", ">>" + "new");
        sahelPreferences = new SahelPreferences(this, AppConstant.PREFERENCE_DEFAULT);

        compositeDisposable = new CompositeDisposable();
        progressDialog = new ProgressDialog(this);

        progressDialog.setMessage("Please Wait...");
        progressDialog.setCancelable(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        Log.i("compositeDisposable", ">>" + "clear");
        compositeDisposable.clear();
        hideLoading();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.i("compositeDisposable", ">>" + "dispose");
        compositeDisposable.dispose();
        super.onDestroy();
    }

    public void showLoading() {
        hideLoading();
        progressDialog = CommonUtil.showLoadingDialog(this);
    }

    public void hideLoading() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog.cancel();
        }
    }

    public SahelPreferences getPreferences() {
        return sahelPreferences;
    }
}

Anyone can solve this. I am new in Android. Thanks in Advance.

Body:
Try this

editProfileCivProfileImage.setImageDrawable(getResource().getDrawable(R.mipmap.ic_launcher));


来源: stackexchange

问:
How to join two HashMaps having same key and different values
I have two hashmaps and I want to join both the maps where the keys are same and the values are different or same.

```<code>HashMap<String, Integer> h1 = new HashMap<String, Integer>();
HashMap<String, Integer> h2 = new HashMap<String, Integer>();
h1.put("A",1);
h1.put("B", 2);
h1.put("C",32);

h2.put("A",321);
h2.put("B", 4562);
</code>```

I need to merge this map so that it looks like {A=[1,321],B=[32,4562],C=[32]}
If I am using Java 7 then how should I do it?

答:
Create a HashMap that takes in an array as the value.

```<code>Map<String, List<Integer>> combined = new HashMap<String, List<Integer>>();
</code>```

Then write a for loop for the keys of each map

```<code>for(String key: mapA.keys()){
    if(!combined.keys().contains(key))
        combined.put(key, new List<Integer>());
    combined.get(key).put(mapA.get(key))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two hashmaps and I want to join both the maps where the keys are same and the values are different or same.

HashMap<String, Integer> h1 = new HashMap<String, Integer>();
HashMap<String, Integer> h2 = new HashMap<String, Integer>();
h1.put("A",1);
h1.put("B", 2);
h1.put("C",32);

h2.put("A",321);
h2.put("B", 4562);

I need to merge this map so that it looks like {A=[1,321],B=[32,4562],C=[32]}
If I am using Java 7 then how should I do it?

Body:
Create a HashMap that takes in an array as the value.

Map<String, List<Integer>> combined = new HashMap<String, List<Integer>>();

Then write a for loop for the keys of each map

for(String key: mapA.keys()){
    if(!combined.keys().contains(key))
        combined.put(key, new List<Integer>());
    combined.get(key).put(mapA.get(key))


问:
How can I get Id of inserted entity without saveChanges in Entity framework?
I have a problem with Entity Framework in Asp.net. I want to get the Id value whenever I add an object to database without executing SaveChanges(). How can I do this?</p>

答:
If you use a Sequence to generate your key values instead of an IDENTITY column, you can fetch the key value before inserting into the database.

EF Core supports this natively Sequences, and you can do this in EF6 with a little custom SQL.


问:
Joining two tables when dates mismatch
I have Two tables Customer and Customer Address. Join criteria is on CustomerNo and Date. When date is not matching or not available on Customer Address table, I want to join with latest date available on the Customer Address

```<code>   Customer Table              Customer Address Table
    CustomerNo    Date        CustomerNo      Date       Addr
    123          1/1/2017     123            1/1/2017   sample1
    123          2/1/2017     123            2/1/2017   sample2
    123          2/11/2017
    123          3/1/2017
</code>```

Expected output

```<code>         Final Table

CustomerNo       Date      Addr
123             1/1/2017   sample1
123             2/1/2017   sample2
122             2/11/2017  sample2
123             3/1/2017   sample2
</code>```

When Dates are not available in Customer Address , match with last available date.

Thanks in advance.

答:
One method is a subquery:</p>

```<code>select c.*,
       (select top 1 address
        from customeraddress ca
        where ca.CustomerNo = c.CustomerNo and ca.date <= c.date
        order by ca.date desc
       ) as address
from customer c;
</code>```

Title: Joining two tables when dates mismatch

Body:
I have Two tables Customer and Customer Address. Join criteria is on CustomerNo and Date. When date is not matching or not available on Customer Address table, I want to join with latest date available on the Customer Address

   Customer Table              Customer Address Table
    CustomerNo    Date        CustomerNo      Date       Addr
    123          1/1/2017     123            1/1/2017   sample1
    123          2/1/2017     123            2/1/2017   sample2
    123          2/11/2017
    123          3/1/2017

Expected output

         Final Table

CustomerNo       Date      Addr
123             1/1/2017   sample1
123             2/1/2017   sample2
122             2/11/2017  sample2
123             3/1/2017   sample2

When Dates are not available in Customer Address , match with last available date.

Thanks in advance.

Body:
One method is a subquery:

select c.*,
       (select top 1 address
        from customeraddress ca
        where ca.CustomerNo = c.CustomerNo and ca.date <= c.date
        order by ca.date desc
       ) as address
from customer c;


问:
How Do I See The Final Text Of A Query Resulting From A Call To mysqli->prepare?
After code like this:

```<code>$stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
$stmt->execute();
$stmt->bind_result($district);
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
</code>```

How Do I See The Actual SQL Statement That Was Executed?

(It Should Look Something Like "SELECT District FROM City WHERE Name='Simi Valley';")

I already realize that in this simplistic case it would be very easy to simply reconstruct the query... but how can I access it in a general way that will work for very complicated prepared statements, and cases where I don't necessarily already understand the intended structure of the query, etc.  Isn't there some function or method that can be called on the statement object that will return the actual text of the SQL query, after binding?

答:
PDO simulates binding if you set it like that; in this topic you can read about the debugDumpParams statement, which is also in the PHP documentation. There is no way, however, to check if the value substitution happened properly when you leave it to the real sql engine; one workaround could be a SELECT with the field placeholders in it so that in the result you get the actual string values:

```<code>SELECT :field1 as field1, :field2 as field2
</code>```

If you bind and fetch this one, it will contain the values:

```<code>Array
(
    [field1] => Lorem ipsum
    [field2] => dolor sit amet
)
</code>```

With this, you can build your own debug function which stitches the original query string together using sql's CONCAT - but you won't learn a lot from this since SQL is quite reliable when it comes to parameter binding :)

ContentLicense: CC BY-SA 2.5

Body:
After code like this:

$stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
$stmt->execute();
$stmt->bind_result($district);
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);

How Do I See The Actual SQL Statement That Was Executed?

(It Should Look Something Like "SELECT District FROM City WHERE Name='Simi Valley';")

I already realize that in this simplistic case it would be very easy to simply reconstruct the query... but how can I access it in a general way that will work for very complicated prepared statements, and cases where I don't necessarily already understand the intended structure of the query, etc.  Isn't there some function or method that can be called on the statement object that will return the actual text of the SQL query, after binding?

Body:
PDO simulates binding if you set it like that; in this topic you can read about the debugDumpParams statement, which is also in the PHP documentation. There is no way, however, to check if the value substitution happened properly when you leave it to the real sql engine; one workaround could be a SELECT with the field placeholders in it so that in the result you get the actual string values:

SELECT :field1 as field1, :field2 as field2

If you bind and fetch this one, it will contain the values:

Array
(
    [field1] => Lorem ipsum
    [field2] => dolor sit amet
)

With this, you can build your own debug function which stitches the original query string together using sql's CONCAT - but you won't learn a lot from this since SQL is quite reliable when it comes to parameter binding :)


问:
What are the common defenses against XSS?
In other words, what are the most-used techniques to sanitize input and/or output nowadays? What do people in industrial (or even just personal-use) websites use to combat the problem?</p>

答:
There are two kinds of XSS attack. One is where your site allows HTML to be injected somehow. This is not that hard to defend against: either escape all user input data, or strip all <> tags and support something like UBB-code instead. Note: URLs may still open you up to rick-rolling type attacks.

The more insiduous one is where some third-party site contains an IFRAME, SCRIPT or IMG tag or the like that hits a URL on your site, and this URL will use whatever authentication the user currently has towards your site. Thus, you should never, ever take any direct action in response to a GET request. If you get a GET request that attempts to do anything (update a profile, check out a shopping cart, etc), then you should respond with a form that in turn requires a POST to be accepted. This form should also contain a cross-site request forgery token, so that nobody can put up a form on a third party site that's set up to submit to your site using hidden fields (again, to avoid a masquerading attack).


问:
Create one list of numbers by combining numbers from three lists of uneven length
I'm trying to create a list of id's, where the numbers are made up of three different lists: the first part of the number should be from the list pers:

```<code>pers = list(range(1,12))
</code>```

The second part should be a combination of the person id, and the number 1 or 2 (not necessarily a list, as it is just two numbers), like this:

```<code>ids = [11, 12, 21, 22, 31, 32, 41, 42, 51, 52, 61, 62, 71, 72, 81, 82, 91,
       92, 101, 102, 111, 112]
</code>```

The third part should be a combination of the above and the values in the list reps:

```<code>reps = list(range(1,13))
</code>```

like this:

```<code>ids = [111, 112, 113, 114, 115, 116, 117, 118, 119, 1110, 1111, 1112,
       121, 122, 123, 124, 125, 126, 127, 128, 129, 1210, 1211, 1212 ...]
</code>```

and so on, all the way up to 11212 (person 11, condition 2,  repetition 12). In total around 2250 items in the list.

I've tried various itertools functions, or nested for loops, lists of lists and tips in this post, but none seem to yield what I need.

答:
```<code>pers = list(range(1,12))
cond = [1,2]
rep = list(range(1,13))

ids = ['{}{}{}'.format(a,b,c) for a in pers for b in cond for c in rep]

ids2 =[]
for i in ids:
    ids2.append(list(i))
print(ids2)
</code>```

Body:
I'm trying to create a list of id's, where the numbers are made up of three different lists: the first part of the number should be from the list pers:

pers = list(range(1,12))

The second part should be a combination of the person id, and the number 1 or 2 (not necessarily a list, as it is just two numbers), like this:

ids = [11, 12, 21, 22, 31, 32, 41, 42, 51, 52, 61, 62, 71, 72, 81, 82, 91,
       92, 101, 102, 111, 112]

The third part should be a combination of the above and the values in the list reps:

reps = list(range(1,13))

like this:

ids = [111, 112, 113, 114, 115, 116, 117, 118, 119, 1110, 1111, 1112,
       121, 122, 123, 124, 125, 126, 127, 128, 129, 1210, 1211, 1212 ...]

and so on, all the way up to 11212 (person 11, condition 2,  repetition 12). In total around 2250 items in the list.

I've tried various itertools functions, or nested for loops, lists of lists and tips in this post, but none seem to yield what I need.


问:
How to add tooltip on each select option with bootstrap-select
I am trying to add tooltip to each select option with bootstrap-select. While I inspecting it seems the select-js converting the select tag to ul. I have no idea this is the reason for my code is not working.

html

```<code><div class="form-group">
    <label  for="email">Network : </label>
    <select  id="basic" class="selectpicker form-control" >
        <option value="0" data-toggle="tooltip" title="Finding your IMEI number">One</option>
        <option value="1" data-toggle="tooltip" title="Next title" >Two</option>
        <option value="2" >Three</option>
        <option  value="3">Four</option>
        <option value="4">Five</option>
        <option value="5">Six</option>
    </select>
</div>
</code>```

js

```<code><script>
$(document).ready(function () {
  var mySelect = $('#first-disabled2');

  $('#special').on('click', function () {
    mySelect.find('option:selected').attr('disabled', 'disabled');
    mySelect.selectpicker('refresh');
  });

  var $basic2 = $('#basic2').selectpicker({
    liveSearch: true,
    maxOptions: 1
  });
});
</script>

<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
</code>```

答:
Update 2021-06-25

It seems that for versions 1.13.x and higher, the solution is to use:

$('#select').data('selectpicker').selectpicker.main.elements - which returns an array of li elements that you can use.

as described on the Github issues page of this plugin:

https://github.com/snapappointments/bootstrap-select/issues/2561#issuecomment-787112874

Bootstrap-select creates new DOM elements (an
 with
s) in order to render the dropdown items.

The problem with your code is that the tooltips are attached to the original option elements.
But they have to be attached to the newly created elements.

However, we should attach them only after the Bootstrap-select plugin is initialized, so we can take advantage of the loaded.bs.select event (From the plugin docs: "This event fires after the select has been initialized." - https://silviomoreto.github.io/bootstrap-select/options/#events).

Also, the plugin is not copying all the attributes from the option elements, so the list items will not have set the title attribute. We have to copy this attribute manually.

In order to find the list items created by the plugin, we can take advantage of the .data('selectpicker') attribute, which is appended to our original select element, and contains all the data that we need.
The list items are found in .data('selectpicker').$lis object.

Please check the code below:

```<code>$(document).ready(function () {

    $('#basic').selectpicker({
     liveSearch: true
     // other options...
    }).on('loaded.bs.select', function(e){

      // save the element
      var $el = $(this);

      // the list items with the options
      var $lis = $el.data('selectpicker').$lis;

      $lis.each(function(i) {

          // get the title from the option
          var tooltip_title = $el.find('option').eq(i).attr('title');

          $(this).tooltip({
             'title': tooltip_title,
             'placement': 'top'
          });

       });

    });

});
</code>```

Fiddle: https://jsfiddle.net/61kbe55z/.

Body:
I am trying to add tooltip to each select option with bootstrap-select. While I inspecting it seems the select-js converting the select tag to ul. I have no idea this is the reason for my code is not working.

html

    Network :
    <select  id="basic" class="selectpicker form-control" >
        <option value="0" data-toggle="tooltip" title="Finding your IMEI number">One</option>
        <option value="1" data-toggle="tooltip" title="Next title" >Two</option>
        <option value="2" >Three</option>
        <option  value="3">Four</option>
        <option value="4">Five</option>
        <option value="5">Six</option>
    </select>

js

Body:
Update 2021-06-25

It seems that for versions 1.13.x and higher, the solution is to use:

$('#select').data('selectpicker').selectpicker.main.elements - which returns an array of li elements that you can use.

as described on the Github issues page of this plugin:

https://github.com/snapappointments/bootstrap-select/issues/2561#issuecomment-787112874

Bootstrap-select creates new DOM elements (an <ul> with <li>s) in order to render the dropdown items.

The problem with your code is that the tooltips are attached to the original option elements.
But they have to be attached to the newly created elements.

However, we should attach them only after the Bootstrap-select plugin is initialized, so we can take advantage of the loaded.bs.select event (From the plugin docs: "This event fires after the select has been initialized." - https://silviomoreto.github.io/bootstrap-select/options/#events).

Also, the plugin is not copying all the attributes from the option elements, so the list items will not have set the title attribute. We have to copy this attribute manually.

In order to find the list items created by the plugin, we can take advantage of the .data('selectpicker') attribute, which is appended to our original select element, and contains all the data that we need.
The list items are found in .data('selectpicker').$lis object.

Please check the code below:

$(document).ready(function () {

    $('#basic').selectpicker({
     liveSearch: true
     // other options...
    }).on('loaded.bs.select', function(e){

      // save the element
      var $el = $(this);

      // the list items with the options
      var $lis = $el.data('selectpicker').$lis;

      $lis.each(function(i) {

          // get the title from the option
          var tooltip_title = $el.find('option').eq(i).attr('title');

          $(this).tooltip({
             'title': tooltip_title,
             'placement': 'top'
          });

       });

    });

});

Fiddle: https://jsfiddle.net/61kbe55z/.

ContentLicense: CC BY-SA 4.0


问:
Misunderstanding of array_values
I've a problem to unerstand correctly array_values, when I do:

```<code>$array[] = 'data1'; // I want [0 => 'data1']
unset($array[0]); // I want []
$array = array_values($array); // I want [] but keys resetted
$array[] = 'data2'; // I want [0 => 'data2']
$array[] = 'data3'; // I want [0 => 'data2', 1 => 'data3']
dump($array);
</code>```

I've the result:

```<code>array:2 [▼
  1 => "data2"
  2 => "data3"
]
</code>```

But I'll want:

```<code>array:2 [▼
  0 => "data2"
  1 => "data3"
]
</code>```

Maybe someone can explain it to me ? Because I'm a little lost :-/

For exemple, if I've an array with 10 values in, remove the 3rd value, and do an array_values on, it works well.

But if I remove the last value from an array, then when I do a array_value, the next value I add, always have id 1 and not 0.

答: This behaviour has been already reported as a bug: https://bugs.php.net/bug.php?id=75433 and (apparently as the result of this post) also: https://bugs.php.net/bug.php?id=75653</p>

Title: Misunderstanding of array_values

Body:
I've a problem to unerstand correctly array_values, when I do:

$array[] = 'data1'; // I want [0 => 'data1']
unset($array[0]); // I want []
$array = array_values($array); // I want [] but keys resetted
$array[] = 'data2'; // I want [0 => 'data2']
$array[] = 'data3'; // I want [0 => 'data2', 1 => 'data3']
dump($array);

I've the result:

array:2 [▼
  1 => "data2"
  2 => "data3"
]

But I'll want:

array:2 [▼
  0 => "data2"
  1 => "data3"
]

Maybe someone can explain it to me ? Because I'm a little lost :-/

For exemple, if I've an array with 10 values in, remove the 3rd value, and do an array_values on, it works well.

But if I remove the last value from an array, then when I do a array_value, the next value I add, always have id 1 and not 0.


问:
Getting a random value from a JavaScript array
Consider:

```<code>var myArray = ['January', 'February', 'March'];
</code>```

How can I select a random value from this array using JavaScript?

答:
Recursive, standalone function which can return any number of items (identical to lodash.sampleSize):</p>

```<code>function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
    const elements = [];

    function getRandomElement(arr) {
        if (elements.length < numberOfRandomElementsToExtract) {
            const index = Math.floor(Math.random() * arr.length)
            const element = arr.splice(index, 1)[0];

            elements.push(element)

            return getRandomElement(arr)
        } else {
            return elements
        }
    }

    return getRandomElement([...array])
}
</code>```

Body:
Consider:

var myArray = ['January', 'February', 'March'];

How can I select a random value from this array using JavaScript?

Body:
Recursive, standalone function which can return any number of items (identical to lodash.sampleSize):

function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
    const elements = [];

    function getRandomElement(arr) {
        if (elements.length < numberOfRandomElementsToExtract) {
            const index = Math.floor(Math.random() * arr.length)
            const element = arr.splice(index, 1)[0];

            elements.push(element)

            return getRandomElement(arr)
        } else {
            return elements
        }
    }

    return getRandomElement([...array])
}


问:
Why is my image so high on the page?
I have two buttons on a webpage, I am trying to make the Clear button be a little lower, to align with the Search button.  Why is the Clear button so high?

Here is a live example: http://www.davidjpotter.com/temp/test.php

```<code><table border=1>
<tr>
<td>
  <button type="submit">Search</button>
  <img src="../images/button-clear.png">
</td>
</tr>
</table>
</code>```

答:
Replace this:

```<code><img src="../images/button-clear.png">
</code>```

with this:

```<code><img src="../images/button-clear.png" style="vertical-align: bottom; ">
</code>```

Title: Why is my image so high on the page?

Body:
I have two buttons on a webpage, I am trying to make the Clear button be a little lower, to align with the Search button.  Why is the Clear button so high?

Here is a live example: http://www.davidjpotter.com/temp/test.php

  <button type="submit">Search</button>

Body:
Replace this:

<img src="../images/button-clear.png">

with this:

<img src="../images/button-clear.png" style="vertical-align: bottom; ">


问:
jQuery Toggle function doesn't work on 1st click
I realized the solution to this problem while I was creating the documentation to ASK this question...so I am posting the answer if for no other reason than to keep me from wasting time on this in the future</p>

答:
I know this is a really old question, but just for people that are looking for a quick fix this worked for me:

a. in the PHP/HTML file:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/.../jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#pClick").click(function(){
            $("#pText").toggle();
            $("#pText").text("...");
        });
    });
    </script>
</code>```

b. in the CSS file:

```<code>#pText {display: none;}
</code>```

It now works even on the first click. It's a simple, quick answer that I hope will be useful.

Body:
I know this is a really old question, but just for people that are looking for a quick fix this worked for me:

a. in the PHP/HTML file:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/.../jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#pClick").click(function(){
            $("#pText").toggle();
            $("#pText").text("...");
        });
    });
    </script>

b. in the CSS file:

#pText {display: none;}

It now works even on the first click. It's a simple, quick answer that I hope will be useful.


答:
First of all you can use CASE expression in join condition, like this:

```<code>on c.date = case when ca.date = c.date then ca.date when [some logic] then [some result] end
</code>```

as you mentioned that your ELSE logic is "last available date", you need to prepare this field somehow, for example in subquery.

But best solution is to split this complex join into few queries and union them all. It will work faster in Teradata.

Title: Joining two tables when dates mismatch

Body:
First of all you can use CASE expression in join condition, like this:

on c.date = case when ca.date = c.date then ca.date when [some logic] then [some result] end

as you mentioned that your ELSE logic is "last available date", you need to prepare this field somehow, for example in subquery.

But best solution is to split this complex join into few queries and union them all. It will work faster in Teradata.


问:
Performance issue in Dynamic Dropdown Search list in excel
I have created dropdown list which gives suggestions from existing data (like google search). I have followed the steps mentioned in the link to get the expected result. I have changed the process to VBA Code since the column range that has data can increase in time (Formula will be inserted for a range dynamically when a new entry is added). Now the problem is since the column have more than 20 000 rows it takes more time to display the suggestions when a key is pressed.

I need to get data from users in a form and store it in an excel sheet. Form will mostly contain dropdown search lists with search list having almost 100k values. Search list is maintained in a different excel sheet and the size of the list will increase every week. Is it ok to use Excel VBA to achieve this? If so how to improve excel performance?

I am using Excel 2010 in Windows Server 2008 OS. I can load the data to SQL Server Table. If this is not possible in Excel is there any way that I can use SQL Server to achieve this?

答:
I did something similar to a google search in my excel app. My code waits 2 seconds after the last keystroke, then runs through another sheet to get close matches. This way it wasn't running through the DB whilst typing..

Wait until user has stopped typing in ComboBox to run macro (VBA)

Someone had suggested I actually look at this post but it was not helpful to my particular challenge.


问:
How to create Page counter with shuffled links
I  am wanting to create page count down for shuffled links so easily informed of where my script is actually progressing.

I try:

```<code>def page_counter():
  for x in range(1000):
      yield x

count = page_counter()
driver = webdriver.Chrome()
driver.get('https://www.betstar.com.au/sports/soccer/')
elements = [x.get_attribute("href") for x in
driver.find_elements_by_css_selector(".market-group a")]
 shuffle(elements)
print(len(elements))

import operator

links = dict((next(count) + 1, e) for e in elements)
desc_links = sorted(links.items(), key=operator.itemgetter(1))

for link in desc_links:
    driver.get(link[1])
    print(f'At Page: {link[0]}')
</code>```

Current Output (random numbers):

```<code>   64
    At Page: 44
    At Page: 24
    At Page: 34
    At Page: 46
    At Page: 42
    At Page: 10
</code>```

The above is not really useful to know how it is progressing.
Change to:

```<code>driver.get('https://stackoverflow.com/questions')
</code>```

Change to:

```<code> driver.find_elements_by_css_selector("#questions .question-hyperlink")]
</code>```

I get(which is also my DESIRED output as it counts down)

```<code>15
At Page: 15  #When at page 15
At Page: 14   #When at page 15
At Page: 13  #When at page 15
At Page: 12
At Page: 11
At Page: 10
At Page: 9
</code>```

How do I create a page counter with shuffled links?

I have also tried to get this working:

```<code>driver = webdriver.Chrome()

driver.get('https://www.betstar.com.au/sports/soccer/')
elements = driver.find_elements_by_css_selector(".market-group a")
elem_href1 = [element.get_attribute("href") for element in elements]
print(elem_href1)
print (len(elem_href1))
shuffle(elem_href1)
for link in elem_href1:#(2)
    driver.get(link)
    print(len(link))
    import numbers

    #number = number -= 1
    #print (len(elem_href1-(number)))

print (len(elem_href1)) gives total number of pages to navigate to.

print(len(link)) gives random number due to shuffle.
</code>```

Not supported, though the links are shuffled though no way of knowing how script is progressing

How to create page counter so that it displays desired output.

答:
try this

Replace

```<code>links = dict((next(count) + 1, e) for e in elements)
desc_links = sorted(links.items(), key=operator.itemgetter(1))

for link in desc_links:
    driver.get(link[1])
    print(f'At Page: {link[0]}')
</code>```

With

```<code>import collections
links = dict((next(count) + 1, e) for e in elements)

desc_links = collections.OrderedDict(sorted(links.items(), reverse=True))

for key, value in desc_links.items():
    driver.get(value)
    print('At Page: ' + str(key))
</code>```

Body:
I  am wanting to create page count down for shuffled links so easily informed of where my script is actually progressing.

I try:

def page_counter():
  for x in range(1000):
      yield x

count = page_counter()
driver = webdriver.Chrome()
driver.get('https://www.betstar.com.au/sports/soccer/')
elements = [x.get_attribute("href") for x in
driver.find_elements_by_css_selector(".market-group a")]
 shuffle(elements)
print(len(elements))

import operator

links = dict((next(count) + 1, e) for e in elements)
desc_links = sorted(links.items(), key=operator.itemgetter(1))

for link in desc_links:
    driver.get(link[1])
    print(f'At Page: {link[0]}')

Current Output (random numbers):

   64
    At Page: 44
    At Page: 24
    At Page: 34
    At Page: 46
    At Page: 42
    At Page: 10

The above is not really useful to know how it is progressing.
Change to:

driver.get('https://stackoverflow.com/questions')

Change to:

 driver.find_elements_by_css_selector("#questions .question-hyperlink")]

I get(which is also my DESIRED output as it counts down)

15
At Page: 15  #When at page 15
At Page: 14   #When at page 15
At Page: 13  #When at page 15
At Page: 12
At Page: 11
At Page: 10
At Page: 9

How do I create a page counter with shuffled links?

I have also tried to get this working:

driver = webdriver.Chrome()

driver.get('https://www.betstar.com.au/sports/soccer/')
elements = driver.find_elements_by_css_selector(".market-group a")
elem_href1 = [element.get_attribute("href") for element in elements]
print(elem_href1)
print (len(elem_href1))
shuffle(elem_href1)
for link in elem_href1:#(2)
    driver.get(link)
    print(len(link))
    import numbers

    #number = number -= 1
    #print (len(elem_href1-(number)))

print (len(elem_href1)) gives total number of pages to navigate to.

print(len(link)) gives random number due to shuffle.

Not supported, though the links are shuffled though no way of knowing how script is progressing

How to create page counter so that it displays desired output.

Body:
try this

Replace

links = dict((next(count) + 1, e) for e in elements)
desc_links = sorted(links.items(), key=operator.itemgetter(1))

for link in desc_links:
    driver.get(link[1])
    print(f'At Page: {link[0]}')

With

import collections
links = dict((next(count) + 1, e) for e in elements)

desc_links = collections.OrderedDict(sorted(links.items(), reverse=True))

for key, value in desc_links.items():
    driver.get(value)
    print('At Page: ' + str(key))


问:
NoSuchMethodError when running Junit @Test method
I have an application (Spring 4 MVC+Hibernate 4+MySQL+Maven integration example using annotations) , integrating Spring with Hibernate using annotation based configuration.

I have this Junit test:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class, BasicDataSourceHibernateConfig.class },
                      loader = AnnotationConfigContextLoader.class)
@Transactional(transactionManager = "transactionManager")
public class DeviceEventServiceImplTest {

    @Inject
    DeviceEventService deviceEventService;

    @Test
    public void testFindWithActiveAlarm() throws Exception {
        List<DeviceEvent> deviceEvents = getDeviceEventService().findWithActiveAlarm();
        System.out.println(deviceEvents);
    }

    public DeviceEventService getDeviceEventService() {
        return deviceEventService;
    }

    public void setDeviceEventService(DeviceEventService deviceEventService) {
        this.deviceEventService = deviceEventService;
    }
}
</code>```

But this error when I run it:

```<code>java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotationAttributes(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/String;ZZ)Lorg/springframework/core/annotation/AnnotationAttributes;
    at org.springframework.test.util.MetaAnnotationUtils$AnnotationDescriptor.<init>(MetaAnnotationUtils.java:290)
    at org.springframework.test.util.MetaAnnotationUtils$UntypedAnnotationDescriptor.<init>(MetaAnnotationUtils.java:365)
    at org.springframework.test.util.MetaAnnotationUtils$UntypedAnnotationDescriptor.<init>(MetaAnnotationUtils.java:360)
    at org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptorForTypes(MetaAnnotationUtils.java:191)
    at org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptorForTypes(MetaAnnotationUtils.java:166)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:274)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:110)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:120)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:105)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:154)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:145)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code>```

答: One of the main reasons for java.lang.NoSuchMethodError is multiple versions of incompatible jar files. Check Effective pom file and make sure you just have one which is compatible with your spring/spring boot version. In above case, it would be conflicts of spring-core dependency.</p>

Body:
I have an application (Spring 4 MVC+Hibernate 4+MySQL+Maven integration example using annotations) , integrating Spring with Hibernate using annotation based configuration.

I have this Junit test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class, BasicDataSourceHibernateConfig.class },
                      loader = AnnotationConfigContextLoader.class)
@Transactional(transactionManager = "transactionManager")
public class DeviceEventServiceImplTest {

    @Inject
    DeviceEventService deviceEventService;

    @Test
    public void testFindWithActiveAlarm() throws Exception {
        List<DeviceEvent> deviceEvents = getDeviceEventService().findWithActiveAlarm();
        System.out.println(deviceEvents);
    }

    public DeviceEventService getDeviceEventService() {
        return deviceEventService;
    }

    public void setDeviceEventService(DeviceEventService deviceEventService) {
        this.deviceEventService = deviceEventService;
    }
}

But this error when I run it:

java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotationAttributes(Ljava/lang/reflect/AnnotatedElement;Ljava/lang/String;ZZ)Lorg/springframework/core/annotation/AnnotationAttributes;
    at org.springframework.test.util.MetaAnnotationUtils$AnnotationDescriptor.<init>(MetaAnnotationUtils.java:290)
    at org.springframework.test.util.MetaAnnotationUtils$UntypedAnnotationDescriptor.<init>(MetaAnnotationUtils.java:365)
    at org.springframework.test.util.MetaAnnotationUtils$UntypedAnnotationDescriptor.<init>(MetaAnnotationUtils.java:360)
    at org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptorForTypes(MetaAnnotationUtils.java:191)
    at org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptorForTypes(MetaAnnotationUtils.java:166)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:274)
    at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:110)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:120)
    at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:105)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:154)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:145)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)


问:
Only update field if form value exists
I'm using Form Model Binding as such and updating my DB using the fill() and save() methods.

```<code>{{ Form::model($account) }}
  {{ Form::text('name', null, array('class'=>'class')) }}
  {{ Form::text('email', null, array('class'=>'class')) }}
  {{ Form::password('password', array('class'=>'class')) }}
  {{ Form::password('password_confirmation', array('class'=>'class')) }}
{{ Form::close() }}
</code>```

Which fires my editAccount controller method:

```<code>$rules = array(
  'name' => array('required'),
  'email' => array('required'),
  'password' => array('confirmed')
);

$validator = Validator::make(Input::all(), $rules);

if ($validator->fails())
{
 // Redirect
}

// Save to DB
$account->fill(Input::all());
$account->save();
</code>```

Which works fine, but if no password was supplied (because the user doesn't want to update/modify it) then the password field is set to null in the db. So, I only want the password field to update if a new password value is supplied via the form.

I know I can do the following:

```<code>// Set the fields manually
$account->name = Input::get('name');
$account->email = Input::get('email');

// Only update the password field if a value is supplied
if (Input::get('password')) {
    $account->password = Input::get('password');
}
$account->save();
</code>```

However I'm wondering if there is a more cleaner way to handle this? Like an UpdateOnlyIfValueExists() method within Laravel/Eloquent.

答:
A much cleaner approach would be to use Eloquent Mutators

Under no circumstances would you allow a null or an empty string as password so you can safely define the following mutator in your Account model.

```<code>// Only accept a valid password and
// hash a password before saving
public function setPasswordAttribute($password)
{
    if ( $password !== null & $password === '' )
    {
        $this->attributes['password'] = bcrypt($password);
    }
}
</code>```

The above mutator will only set a password attribute if it is not null and an empty string. It also hashes the password before saving so you do not need to do it in your controller action or application elsewhere.

Title: Only update field if form value exists

Body:
I'm using Form Model Binding as such and updating my DB using the fill() and save() methods.

{{ Form::model($account) }}
  {{ Form::text('name', null, array('class'=>'class')) }}
  {{ Form::text('email', null, array('class'=>'class')) }}
  {{ Form::password('password', array('class'=>'class')) }}
  {{ Form::password('password_confirmation', array('class'=>'class')) }}
{{ Form::close() }}

Which fires my editAccount controller method:

$rules = array(
  'name' => array('required'),
  'email' => array('required'),
  'password' => array('confirmed')
);

$validator = Validator::make(Input::all(), $rules);

if ($validator->fails())
{
 // Redirect
}

// Save to DB
$account->fill(Input::all());
$account->save();

Which works fine, but if no password was supplied (because the user doesn't want to update/modify it) then the password field is set to null in the db. So, I only want the password field to update if a new password value is supplied via the form.

I know I can do the following:

// Set the fields manually
$account->name = Input::get('name');
$account->email = Input::get('email');

// Only update the password field if a value is supplied
if (Input::get('password')) {
    $account->password = Input::get('password');
}
$account->save();

However I'm wondering if there is a more cleaner way to handle this? Like an UpdateOnlyIfValueExists() method within Laravel/Eloquent.

Body:
A much cleaner approach would be to use Eloquent Mutators

Under no circumstances would you allow a null or an empty string as password so you can safely define the following mutator in your Account model.

// Only accept a valid password and
// hash a password before saving
public function setPasswordAttribute($password)
{
    if ( $password !== null & $password === '' )
    {
        $this->attributes['password'] = bcrypt($password);
    }
}

The above mutator will only set a password attribute if it is not null and an empty string. It also hashes the password before saving so you do not need to do it in your controller action or application elsewhere.


问:
Python list | How to remove parenthesis,quotes and commas in my list?
From my database, I'm returning a list to be displayed into my HTML page but my list has this unwanted symbols. I tried using split() function but it wont work. How can I remove those parenthesis,commas and quotes. Thanks for you help

The output is :

```<code>[('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]
</code>```

I want:

```<code> [cenomar, cedula, Birth Certificate, Clearance]
</code>```

Here is my python function:

```<code> @app.route('/')
    def search():
        conn=psycopg2.connect("dbname='forms' user='postgres' password='everboy'
       host='localhost' port='5432'")
       cur=conn.cursor()
       cur.execute("SELECT name from form")
       rows=cur.fetchall()
       print(rows)
       return render_template("form.html",rows=rows)
</code>```

答:
An easy solution would be:

Input: ["('cenomar',)", "('cedula',)", "('Birth Certificate',)", "('Clearance',)"]

```<code>rows = ["('cenomar',)", "('cedula',)", "('Birth Certificate',)", "('Clearance',)"]
res = []
for r in rows:
    res.append(r[2:-3]) # this line ignores the beginning bracket and open quote and the closing bracket, comma, and close quote
print res
</code>```

Output: ["cenomar", "cedula", "Birth Certificate", "Clearance"]

What happens is, you iterate over your list, and for each item you just cut off the things you don't need with the use of string manipulation ([n:m], where n is the starting character and m is the end character, in your case 2 indicates to start the string from the 3 character (ignoring the ( and ') and -3 indicates cut the string to 3 characters before the end of it (ignoring the ), ', and ,)).

EDIT 1

I noticed that your input may not be a string as my above answer suggests, if you have a tuple ("smth",) you can just simply get the 1st element. So the answer would change to:

Input: [('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]

```<code>rows = [('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]
res = []
for r in rows:
    res.append(r[0])
print res
</code>```

Output: ["cenomar", "cedula", "Birth Certificate", "Clearance"]

The above implementation is written in long for ease of understanding, but as well can be translated into a shorter one liner like so:

```<code>rows = [i[0] for i in rows]
</code>```

Hope this helps!

Body:
From my database, I'm returning a list to be displayed into my HTML page but my list has this unwanted symbols. I tried using split() function but it wont work. How can I remove those parenthesis,commas and quotes. Thanks for you help

The output is :

[('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]

I want:

 [cenomar, cedula, Birth Certificate, Clearance]

Here is my python function:

 @app.route('/')
    def search():
        conn=psycopg2.connect("dbname='forms' user='postgres' password='everboy'
       host='localhost' port='5432'")
       cur=conn.cursor()
       cur.execute("SELECT name from form")
       rows=cur.fetchall()
       print(rows)
       return render_template("form.html",rows=rows)

Body:
An easy solution would be:

Input: ["('cenomar',)", "('cedula',)", "('Birth Certificate',)", "('Clearance',)"]

rows = ["('cenomar',)", "('cedula',)", "('Birth Certificate',)", "('Clearance',)"]
res = []
for r in rows:
    res.append(r[2:-3]) # this line ignores the beginning bracket and open quote and the closing bracket, comma, and close quote
print res

Output: ["cenomar", "cedula", "Birth Certificate", "Clearance"]

What happens is, you iterate over your list, and for each item you just cut off the things you don't need with the use of string manipulation ([n:m], where n is the starting character and m is the end character, in your case 2 indicates to start the string from the 3 character (ignoring the ( and ') and -3 indicates cut the string to 3 characters before the end of it (ignoring the ), ', and ,)).

EDIT 1

I noticed that your input may not be a string as my above answer suggests, if you have a tuple ("smth",) you can just simply get the 1st element. So the answer would change to:

Input: [('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]

rows = [('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]
res = []
for r in rows:
    res.append(r[0])
print res

Output: ["cenomar", "cedula", "Birth Certificate", "Clearance"]

The above implementation is written in long for ease of understanding, but as well can be translated into a shorter one liner like so:

rows = [i[0] for i in rows]

Hope this helps!


问:
tinymce 4.3.4 video_template_callback
The goal is to populate "Embed" field in "insert/edit video" dialog with data from my DOM.
As I understood from the docs there is "video_template_callback" for this purpose:

```<code>tinymce.init({
    selector: '#text',
    theme: 'modern',
    height: 300,
    menubar: false,
    plugins: ['media code'],
    toolbar: 'media code',
    video_template_callback: function (data) {
        console.log('data');
    },
});
</code>```

But the callback does not fire when calling "insert/edit video" dialog.
May be I mistaken trying to implement this way. Thanks for help.

答:
I had issues with video_template_callback in version 4.7.3.
I tried to add onclick and controlslist props to my video tag. Initially, it didn't appear, but after some time of research I figured out that TinyMCE has a whitelist of tag properties and I need to add it to the extended_valid_elements. It works with this configuration:

```<code>extended_valid_elements: 'video[onclick|controlslist|controls]',
video_template_callback: ({
  width, height, poster, source1, source1mime, source2, source2mime,
}) => [
   `<video onclick="playFunction" controls controlslist="nodownload"`
   `width="${width}" height="${height}" ${(poster ? `poster="${poster}` : '')}>`,
   `<source src="${source1}" ${(source1mime ? `type="${source1mime}"` : '')} />`,
   `<source src="${source2}" ${(source2mime ? `type="${source2mime}"` : '')} />`,
   '</video>',
].join(''),
</code>```

Also, please note that all properties should be lowercased.

Title: tinymce 4.3.4 video_template_callback

Body:
The goal is to populate "Embed" field in "insert/edit video" dialog with data from my DOM.
As I understood from the docs there is "video_template_callback" for this purpose:

tinymce.init({
    selector: '#text',
    theme: 'modern',
    height: 300,
    menubar: false,
    plugins: ['media code'],
    toolbar: 'media code',
    video_template_callback: function (data) {
        console.log('data');
    },
});

But the callback does not fire when calling "insert/edit video" dialog.
May be I mistaken trying to implement this way. Thanks for help.

Body:
I had issues with video_template_callback in version 4.7.3.
I tried to add onclick and controlslist props to my video tag. Initially, it didn't appear, but after some time of research I figured out that TinyMCE has a whitelist of tag properties and I need to add it to the extended_valid_elements. It works with this configuration:

extended_valid_elements: 'video[onclick|controlslist|controls]',
video_template_callback: ({
  width, height, poster, source1, source1mime, source2, source2mime,
}) => [
   `<video onclick="playFunction" controls controlslist="nodownload"`
   `width="${width}" height="${height}" ${(poster ? `poster="${poster}` : '')}>`,
   `<source src="${source1}" ${(source1mime ? `type="${source1mime}"` : '')} />`,
   `<source src="${source2}" ${(source2mime ? `type="${source2mime}"` : '')} />`,
   '</video>',
].join(''),

Also, please note that all properties should be lowercased.


问:
Add Array Item into console.log

Hi guys, I am trying to develop on a lesson regarding basic To Do lists. If, after deleting a ToDo item I wanted the console to print "Deleted To Do Item" how would I do that? This is what I have thus far for the delete portion of the To Do.

```<code>function deleteToDo() {
    var index = prompt("Enter index of todo to delete");
        todos.splice(index, 1);
        console.log("Deleted " + todos[index]);
}
</code>```

The error I receive is that "todos[index] is undefined" which I kind of guess would happen, at this point I'm just winging various options and seeing what happens. Do I need to define something before the splice?

答:
Save the value before deleting:</p>

```<code>function deleteToDo() {
   var index = prompt("Enter index of todo to delete");

   if (index >= 0 && index < todos.length) {
       var deletedItem = todos[index];
       todos.splice(index, 1);
       console.log(deletedItem);
   }
}
</code>```

Title: Add Array Item into console.log

Body:
Hi guys, I am trying to develop on a lesson regarding basic To Do lists. If, after deleting a ToDo item I wanted the console to print "Deleted To Do Item" how would I do that? This is what I have thus far for the delete portion of the To Do.

function deleteToDo() {
    var index = prompt("Enter index of todo to delete");
        todos.splice(index, 1);
        console.log("Deleted " + todos[index]);
}

The error I receive is that "todos[index] is undefined" which I kind of guess would happen, at this point I'm just winging various options and seeing what happens. Do I need to define something before the splice?

Body:
Save the value before deleting:

function deleteToDo() {
   var index = prompt("Enter index of todo to delete");

   if (index >= 0 && index < todos.length) {
       var deletedItem = todos[index];
       todos.splice(index, 1);
       console.log(deletedItem);
   }
}


问:
SEO Language information
I was wondering if defining your language in HTML is better for search enigines. For example, I've got a French site, then i've got three options:

1.) have faith that google can say my site is french

2.) define language in the HTML tag

```<code><html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="fr">
</code>```

3.) define language in a meta tag

```<code><meta http-equiv="content-language" content="FR-fr" />
</code>```

Which option you believe is best? Or which combination of options?

答: andrewk is right - use 2 or 3 , but take into account that in most cases the language will be detected by the robot it self automatically.</p>

Title: SEO Language information

Body:
I was wondering if defining your language in HTML is better for search enigines. For example, I've got a French site, then i've got three options:

1.) have faith that google can say my site is french

2.) define language in the HTML tag

3.) define language in a meta tag

<meta http-equiv="content-language" content="FR-fr" />

Which option you believe is best? Or which combination of options?


问:
Running gdb with a source file
I have a Linux executable file and I can run it on command line, but at first, I should use

```<code>source ./somefile
</code>```

If I don't source it, the executable crashed. I also, can run the file under dbg. But I need to source somefile in gdb also. I mean, I already make source ./somefile then run the gdb and run the executable in it, the executable crashed like without using source ./somefile.

By the way, somefile that I should source contains some EXPORT=bla bla definitions.

Executable is an embedded qt software, running on imx6 board. Sourcing somefile makes some definition about qt libraries. The crash message when I run the executable without sourcing somefile and when sourcing it and then run in gdb is exactly the same. So I think that after source somefile, if I run the executable in gdb, it seems gdb doesn't know libraries' path. May be a way to source a file for gdb.

答:
You might run your source command, and later, in the same shell (e.g. same terminal window), run gdb to debug your program. The environment variables setup by your source builtin command are valid for not only the gdb process, but also the debugged process.

Read more about Debugging with GDB.

Title: Running gdb with a source file

Body:
I have a Linux executable file and I can run it on command line, but at first, I should use

source ./somefile

If I don't source it, the executable crashed. I also, can run the file under dbg. But I need to source somefile in gdb also. I mean, I already make source ./somefile then run the gdb and run the executable in it, the executable crashed like without using source ./somefile.

By the way, somefile that I should source contains some EXPORT=bla bla definitions.

Executable is an embedded qt software, running on imx6 board. Sourcing somefile makes some definition about qt libraries. The crash message when I run the executable without sourcing somefile and when sourcing it and then run in gdb is exactly the same. So I think that after source somefile, if I run the executable in gdb, it seems gdb doesn't know libraries' path. May be a way to source a file for gdb.


问:
Wrote a code in python to edit an image's background and the output i am getting is totally off

I edited it to view the foreground image on a white background but now, none of the images are visible.

```<code>import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('91_photo.jpg')
mask = np.zeros(img.shape[:2],np.uint8)

bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

rect = (10,10,360,480)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)

mask2 = np.where((mask==2)|(mask==0),0,255).astype('uint8')
img = img*mask2[:,:,np.newaxis]

plt.imshow(img),plt.colorbar(),plt.show()
</code>```

 Expecting the result to be a visible image on a white background

This is what i'm getting

答:
There are a number of small issues with your code that are adding up to that weird result.

OpenCV uses BGR ordering of the channels of an image, where matplotlib uses RGB. That means if you read an image with OpenCV but want to display with matplotlib, you need to convert the image from BGR to RGB before displaying (that's the reason the colors are weird). Also, not that important, but color images are not displayed with a colormap, so showing the colormap does not do anything for you.

In numpy, it's best to keep masks boolean whenever you can, because you can use them to index your arrays. Your current code converts a boolean mask to a uint8 image with 0 and 255 values and then you multiply that with your image. That means your image will be set to zero wherever the mask is zero---and your image values will explode (or do weird stuff with overflow). Instead, keep the mask boolean and use it to index your array. That way anywhere the mask is True you can just set the value in your image to something specific (like 255 for white).

This should fix you up:

```<code>import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('91_photo.jpg')
mask = np.zeros(img.shape[:2], np.uint8)

bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)

rect = (10, 10, 360, 480)
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)

mask2 = (mask==2) | (mask==0)
img[mask2] = 255

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img)
plt.show()
</code>```

Body:
I edited it to view the foreground image on a white background but now, none of the images are visible.

import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('91_photo.jpg')
mask = np.zeros(img.shape[:2],np.uint8)

bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

rect = (10,10,360,480)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)

mask2 = np.where((mask==2)|(mask==0),0,255).astype('uint8')
img = img*mask2[:,:,np.newaxis]

plt.imshow(img),plt.colorbar(),plt.show()

 Expecting the result to be a visible image on a white background

This is what i'm getting

Body:
There are a number of small issues with your code that are adding up to that weird result.

OpenCV uses BGR ordering of the channels of an image, where matplotlib uses RGB. That means if you read an image with OpenCV but want to display with matplotlib, you need to convert the image from BGR to RGB before displaying (that's the reason the colors are weird). Also, not that important, but color images are not displayed with a colormap, so showing the colormap does not do anything for you.

In numpy, it's best to keep masks boolean whenever you can, because you can use them to index your arrays. Your current code converts a boolean mask to a uint8 image with 0 and 255 values and then you multiply that with your image. That means your image will be set to zero wherever the mask is zero---and your image values will explode (or do weird stuff with overflow). Instead, keep the mask boolean and use it to index your array. That way anywhere the mask is True you can just set the value in your image to something specific (like 255 for white).

This should fix you up:

import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('91_photo.jpg')
mask = np.zeros(img.shape[:2], np.uint8)

bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)

rect = (10, 10, 360, 480)
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)

mask2 = (mask==2) | (mask==0)
img[mask2] = 255

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img)
plt.show()


问:
export data from Source system and import to destination system in update mode
I have two systems source and destination. both system had same no of tables with same names. But destination system tables had more colums than in source system tables. I want to export source system dump into destination system without updating new colums in destination system.

ex: Source System,

T1->name='a',sex='F', id=1

Destination system

T1->name='a1',sex='F', id=1, email=a@b.com.

I want to import dump in to destination system, update t1 table without updating email field.
How can i do this?

答:
Please find below my code which i have run on my sample data. please run it in your environment and check if it solve your issue.

Few assumptions:

 1.) TARGET SCHEMA NAME IS @Target_Schema.( In the code replace @Target_schema with your target schema name)

 3.) EACH TABLE IN SOURCE SCHEMA SHOULD HAVE A PK TO UPDATE.

 4.) MAKE SURE NO TABLE IN SOURCE HAS COMPOSITE PK

 5.) YOU SHOULD HAVE DML PRIVILEGES IN TGT SCHEMA FOR PARTICULAR TABLES YOU ARE UPDATING or inserting.

Code:

```<code>    CREATE TABLE ANK1
            (
            ID NUMBER,
            NAME VARCHAR2(4000),
            );

            ALTER TABLE ank1
            ADD CONSTRAINT ANK_PK PRIMARY KEY (ID);

            insert into ANK1   values(1,'abc');
            commit;

           CREATE TABLE @Target_Schema.ANK1
            (
           ID NUMBER,
           NAME VARCHAR2(4000),
           EMAIL VARCHAR2(4000)
           );

    SET SERVEROUTPUT ON
declare
p_key_col varchar2(40);
l_merge_sql varchar2(4000);
begin
for cur_tab in ( SELECT * FROM (
SELECT UTC.TABLE_NAME,UTC.COLUMN_NAME,UCC.COLUMN_NAME AS PK_COL  FROM USER_TAB_COLS UTC,USER_CONSTRAINTS UC,USER_CONS_COLUMNS UCC WHERE UTC.TABLE_NAME IN ('ANK1')
AND UTC.TABLE_NAME = UC.TABLE_NAME AND UC.CONSTRAINT_TYPE = 'P' AND UC.CONSTRAINT_NAME = UCC.CONSTRAINT_NAME) WHERE PK_COL <> COLUMN_NAME ) loop

    l_merge_sql:= 'MERGE INTO @Target_Schema.'||cur_tab.table_name||' T_TABLE
     USING '||cur_tab.table_name||' SRC
        ON (T_TABLE.'||cur_tab.PK_COL||' = SRC.'||cur_tab.PK_COL||')

     WHEN MATCHED THEN
          UPDATE
             SET T_TABLE.'||cur_tab.COLUMN_NAME||' = SRC.'||cur_tab.COLUMN_NAME||'

     WHEN NOT MATCHED THEN
          INSERT (T_TABLE.'||cur_tab.PK_COL||', T_TABLE.'||cur_tab.COLUMN_NAME||')
          VALUES (SRC.'||cur_tab.PK_COL||', SRC.'||cur_tab.COLUMN_NAME||')';
    DBMS_OUTPUT.PUT_LINE(l_merge_sql);

 END LOOP;

 END;
</code>```

You will get a merge statement printed and you can run that separately to see the results.

Hope this will solve your issue.

Body:
Please find below my code which i have run on my sample data. please run it in your environment and check if it solve your issue.

Few assumptions:

 1.) TARGET SCHEMA NAME IS @Target_Schema.( In the code replace @Target_schema with your target schema name)

 3.) EACH TABLE IN SOURCE SCHEMA SHOULD HAVE A PK TO UPDATE.

 4.) MAKE SURE NO TABLE IN SOURCE HAS COMPOSITE PK

 5.) YOU SHOULD HAVE DML PRIVILEGES IN TGT SCHEMA FOR PARTICULAR TABLES YOU ARE UPDATING or inserting.

Code:

    CREATE TABLE ANK1
            (
            ID NUMBER,
            NAME VARCHAR2(4000),
            );

            ALTER TABLE ank1
            ADD CONSTRAINT ANK_PK PRIMARY KEY (ID);

            insert into ANK1   values(1,'abc');
            commit;

           CREATE TABLE @Target_Schema.ANK1
            (
           ID NUMBER,
           NAME VARCHAR2(4000),
           EMAIL VARCHAR2(4000)
           );

    SET SERVEROUTPUT ON
declare
p_key_col varchar2(40);
l_merge_sql varchar2(4000);
begin
for cur_tab in ( SELECT * FROM (
SELECT UTC.TABLE_NAME,UTC.COLUMN_NAME,UCC.COLUMN_NAME AS PK_COL  FROM USER_TAB_COLS UTC,USER_CONSTRAINTS UC,USER_CONS_COLUMNS UCC WHERE UTC.TABLE_NAME IN ('ANK1')
AND UTC.TABLE_NAME = UC.TABLE_NAME AND UC.CONSTRAINT_TYPE = 'P' AND UC.CONSTRAINT_NAME = UCC.CONSTRAINT_NAME) WHERE PK_COL <> COLUMN_NAME ) loop

    l_merge_sql:= 'MERGE INTO @Target_Schema.'||cur_tab.table_name||' T_TABLE
     USING '||cur_tab.table_name||' SRC
        ON (T_TABLE.'||cur_tab.PK_COL||' = SRC.'||cur_tab.PK_COL||')

     WHEN MATCHED THEN
          UPDATE
             SET T_TABLE.'||cur_tab.COLUMN_NAME||' = SRC.'||cur_tab.COLUMN_NAME||'

     WHEN NOT MATCHED THEN
          INSERT (T_TABLE.'||cur_tab.PK_COL||', T_TABLE.'||cur_tab.COLUMN_NAME||')
          VALUES (SRC.'||cur_tab.PK_COL||', SRC.'||cur_tab.COLUMN_NAME||')';
    DBMS_OUTPUT.PUT_LINE(l_merge_sql);

 END LOOP;

 END;

You will get a merge statement printed and you can run that separately to see the results.

Hope this will solve your issue.


问:
Setting a max-width for flex items?
I'm trying to create a filter section on my site, the content is all generated dynamically (so I can't add extra parents to it), and our styleguide creates them using flex items. I'd like to keep this functionality for the most part.

I want my 3 flex items to have a max-width and be floated left, leaving my non flex item floated right, in the overall container that is set to a max width of 1080px sort of like this:

```<code>Option 1    Option 2    Option 3                                    Non-flex Item
</code>```

I've tried setting the flex-align values and following this answer, but that doesn't seem to work for this.

As of right now, this is the code that I am working with:

One

Three

Three

       I'm not a flex item

```
<pre class="lang-css prettyprint-override"><code>.container {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    position: relative;
    max-width: 1080px;
    margin: 0 auto;
    padding: 0 20px;
    box-sizing: content-box;
}

.child {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    position: relative;
}
</code>```

I also made a Fiddle for you all to play around.

答:
You could use:

```<code>.non-flex{
  margin-left: 50%;
}
</code>```

to create more space in between the first 3 elements and the non-flex one

Title: Setting a max-width for flex items?

Body:
I'm trying to create a filter section on my site, the content is all generated dynamically (so I can't add extra parents to it), and our styleguide creates them using flex items. I'd like to keep this functionality for the most part.

I want my 3 flex items to have a max-width and be floated left, leaving my non flex item floated right, in the overall container that is set to a max width of 1080px sort of like this:

Option 1    Option 2    Option 3                                    Non-flex Item

I've tried setting the flex-align values and following this answer, but that doesn't seem to work for this.

As of right now, this is the code that I am working with:

One

Three

Three

       I'm not a flex item

.container {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    position: relative;
    max-width: 1080px;
    margin: 0 auto;
    padding: 0 20px;
    box-sizing: content-box;
}

.child {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    position: relative;
}

I also made a Fiddle for you all to play around.

Body:
You could use:

.non-flex{
  margin-left: 50%;
}

to create more space in between the first 3 elements and the non-flex one


问:
Hide and display nav bar depending on user in Angular
I am using rxjs BehaviorSubject to allow my login page to pass data to auth.service.ts and my app.component is able to retrieve data that is in auth.service.ts. But I want to app.component to be able to detect the changes to the data in auth.service.ts and change the nav according to the data in auth.service.ts

this is my app.component.html

```<code><h1 class="logo">Fast Pay</h1>
<nav class="navbar">
  <ul class="nav" *ngIf="isOwner">
  <li><a routerLink="/home" >Home</a></li>
  <li><a routerLink="/payment">Payment</a></li>
  <li><a routerLink="/transfer">Money Transfer</a></li>
  <li><a routerLink="/history">Transaction History</a></li>
  <li><a routerLink="/manage-sub-acc">Manage Sub Account</a></li>
  <li style="float:right"><a routerLink="/home">Logout</a></li>
  </ul>

  <ul class="nav" *ngIf="isCustomer">
    <li><a routerLink="/home" >Home</a></li>
    <li><a routerLink="/payment">Payment</a></li>
    <li><a routerLink="/transfer">Money Transfer</a></li>
    <li><a routerLink="/history">Transaction History</a></li>
    <li class="nav"><a class="nav" routerLink="/add-amount">Top-up</a></li>
    <li style="float:right"><a routerLink="/home">Logout</a></li>
  </ul>

      <li class="nav" style="float:right"><a class="nav" routerLink="/registration">Registration</a></li>
      <li class="nav" style="float:right"><a class="nav" routerLink="/login">Login</a></li>
    </ul>

  <ul class="nav" *ngIf="!isCustomer && !isOwner">
  <li class="nav"><a class="nav" routerLink="/home" >Home</a></li>
  <li class="nav"><a class="nav" routerLink="/login">Payment</a></li>
  <li class="nav"><a class="nav" routerLink="/login">Money Transfer</a></li>
  <li class="nav"><a class="nav" routerLink="/login">Transaction History</a></li>
  <li class="nav"><a class="nav" routerLink="/login">Top-up</a></li>
  <li class="nav" style="float:right"><a class="nav" routerLink="/registration">Registration</a></li>
  <li class="nav" style="float:right"><a class="nav" routerLink="/login">Login</a></li>

  </ul>
</nav>
<div class="container">
  <div class="row">
    <router-outlet></router-outlet>
  </div>
</div>
</code>```

this is my app.component.ts

```<code>import { Component } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  public email:string = "";
  public accType:string = "";
  isOwner = false;
  isCustomer = false;

  constructor(private auth: AuthService) {
    if(this.email=="default@email.com"){
      this.isOwner = false;
      this.isCustomer = false;

    }
    if(this.email!="default@email.com"){
      if(this.accType == "customer"){
        this.isCustomer = true;
      }
      else if(this.accType == "owner"){
        this.isOwner = true;
      }
    }

  }
  ngOnInit() {
    this.auth.currentEmail.subscribe(email => this.email = email);
    this.auth.currentaccTyoe.subscribe(type => this.accType = type);

  }
</code>```

答:
I would add a BehaviorSubject to your auth service, then have your app.component subscribe to the BehaviorSubject so app.component can be notified when a user logs in.

```<code>// auth.service.ts
userChange$ = new BehaviorSubject({email: null, accType: null});

// call this when a user logs in so all subscribers of userChange$ will be notified
loggedIn(email, accType){
    this.userChange$.next({
        email: email,
        accType: accType
    });
}
</code>```

Then subscribe to userChange$ in your app.component to listen for changes

```<code>// app.component.ts
ngOnInit(){
    this.authService.userChange$.subscribe(res => {
        if(res.email=="default@email.com") {
            res.isOwner = false;
            res.isCustomer = false;
        }
        if(res.email!="default@email.com") {
            if(res.accType == "customer") {
                this.isCustomer = true;
            } else if(res.accType == "owner") {
                this.isOwner = true;
            }
        }
    });
}
</code>```

Body:
I am using rxjs BehaviorSubject to allow my login page to pass data to auth.service.ts and my app.component is able to retrieve data that is in auth.service.ts. But I want to app.component to be able to detect the changes to the data in auth.service.ts and change the nav according to the data in auth.service.ts

this is my app.component.html

Fast Pay

Home

Payment

Money Transfer

Transaction History

Manage Sub Account

Logout

Home

Payment

Money Transfer

Transaction History

Top-up

Logout

Registration

Login

Home

Payment

Money Transfer

Transaction History

Top-up

Registration

Login

    <router-outlet></router-outlet>

this is my app.component.ts

import { Component } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  public email:string = "";
  public accType:string = "";
  isOwner = false;
  isCustomer = false;

  constructor(private auth: AuthService) {
    if(this.email=="default@email.com"){
      this.isOwner = false;
      this.isCustomer = false;

    }
    if(this.email!="default@email.com"){
      if(this.accType == "customer"){
        this.isCustomer = true;
      }
      else if(this.accType == "owner"){
        this.isOwner = true;
      }
    }

  }
  ngOnInit() {
    this.auth.currentEmail.subscribe(email => this.email = email);
    this.auth.currentaccTyoe.subscribe(type => this.accType = type);

  }

Body:
I would add a BehaviorSubject to your auth service, then have your app.component subscribe to the BehaviorSubject so app.component can be notified when a user logs in.

// auth.service.ts
userChange$ = new BehaviorSubject({email: null, accType: null});

// call this when a user logs in so all subscribers of userChange$ will be notified
loggedIn(email, accType){
    this.userChange$.next({
        email: email,
        accType: accType
    });
}

Then subscribe to userChange$ in your app.component to listen for changes

// app.component.ts
ngOnInit(){
    this.authService.userChange$.subscribe(res => {
        if(res.email=="default@email.com") {
            res.isOwner = false;
            res.isCustomer = false;
        }
        if(res.email!="default@email.com") {
            if(res.accType == "customer") {
                this.isCustomer = true;
            } else if(res.accType == "owner") {
                this.isOwner = true;
            }
        }
    });
}


答:
After This line: rows=cur.fetchall()
add this line

```<code>rows=[i[0] for i in rows]
</code>```

Title: Python list | How to remove parenthesis,quotes and commas in my list?

Body:
After This line: rows=cur.fetchall()
add this line

rows=[i[0] for i in rows]