问:
How to make Zoom on whole content in RecyclerView?
I need zoom in/out on whole content in RecyclerView.
In fact I need to resize all child views by width, and text inside each item.

```<code>public class ViewHolder {

    Button btn;

    ...
}
</code>```

When User make zoom in, the text of Button should be decrease down to 8sp and disappear if user continue zoom in.

So, now I have dilemma : what I need to do? Resize items in Adapter, or resize them in LayoutManager, and update whole adapter.

Both of scenarios seems affect an performance of visual effect, so I need help. Maybe you give me a better solution.

For state of 21/11/2016 I can't found any box-solution for this case.

So I decide write my own view and do remeasurement of visible views in each zoom scale factor change.

答:
user this code. it's working fine for zooming all content of recyclerview.

```<code>import android.content.Context;
import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;

/**
@author yogesh
* */
public class PinchRecyclerView extends RecyclerView {
    private static final int INVALID_POINTER_ID = -1;
    private int mActivePointerId = INVALID_POINTER_ID;
    private ScaleGestureDetector mScaleDetector;
    private float mScaleFactor = 1.f;
    private float maxWidth = 0.0f;
    private float maxHeight = 0.0f;
    private float mLastTouchX;
    private float mLastTouchY;
    private float mPosX;
    private float mPosY;
    private float width;
    private float height;

    public PinchRecyclerView(Context context) {
        super(context);
        if (!isInEditMode())
            mScaleDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
    }

    public PinchRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (!isInEditMode())
            mScaleDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
    }

    public PinchRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (!isInEditMode())
            mScaleDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        try {
            return super.onInterceptTouchEvent(ev);
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent ev) {
        super.onTouchEvent(ev);
        final int action = ev.getAction();
        mScaleDetector.onTouchEvent(ev);
        switch (action & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN: {
                final float x = ev.getX();
                final float y = ev.getY();
                mLastTouchX = x;
                mLastTouchY = y;
                mActivePointerId = ev.getPointerId(0);
                break;
            }

            case MotionEvent.ACTION_MOVE: {
                /* this line is replaced because here came below isssue
                java.lang.IllegalArgumentException: pointerIndex out of range
                 ref http://stackoverflow.com/questions/6919292/pointerindex-out-of-range-android-multitouch
                */
                //final int pointerIndex = ev.findPointerIndex(mActivePointerId);

                final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK)
                        >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
                final float x = ev.getX(pointerIndex);
                final float y = ev.getY(pointerIndex);
                final float dx = x - mLastTouchX;
                final float dy = y - mLastTouchY;

                mPosX += dx;
                mPosY += dy;

                if (mPosX > 0.0f)
                    mPosX = 0.0f;
                else if (mPosX < maxWidth)
                    mPosX = maxWidth;

                if (mPosY > 0.0f)
                    mPosY = 0.0f;
                else if (mPosY < maxHeight)
                    mPosY = maxHeight;

                mLastTouchX = x;
                mLastTouchY = y;

                invalidate();
                break;
            }

            case MotionEvent.ACTION_UP: {
                mActivePointerId = INVALID_POINTER_ID;
                break;
            }

            case MotionEvent.ACTION_CANCEL: {
                mActivePointerId = INVALID_POINTER_ID;
                break;
            }

            case MotionEvent.ACTION_POINTER_UP: {
                final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
                final int pointerId = ev.getPointerId(pointerIndex);
                if (pointerId == mActivePointerId) {
                    final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                    mLastTouchX = ev.getX(newPointerIndex);
                    mLastTouchY = ev.getY(newPointerIndex);
                    mActivePointerId = ev.getPointerId(newPointerIndex);
                }
                break;
            }
        }

        return true;
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        canvas.translate(mPosX, mPosY);
        canvas.scale(mScaleFactor, mScaleFactor);
        canvas.restore();
    }

    @Override
    protected void dispatchDraw(@NonNull Canvas canvas) {
        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        if (mScaleFactor == 1.0f) {
            mPosX = 0.0f;
            mPosY = 0.0f;
        }
        canvas.translate(mPosX, mPosY);
        canvas.scale(mScaleFactor, mScaleFactor);
        super.dispatchDraw(canvas);
        canvas.restore();
        invalidate();
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();
            mScaleFactor = Math.max(1.0f, Math.min(mScaleFactor, 3.0f));
            maxWidth = width - (width * mScaleFactor);
            maxHeight = height - (height * mScaleFactor);
            invalidate();
            return true;
        }
    }
}
</code>```

Code taken from this StackOverflow answer: Android change recycler view column no. on pinch zoom

Body:
I need zoom in/out on whole content in RecyclerView.
In fact I need to resize all child views by width, and text inside each item.

public class ViewHolder {

    Button btn;

    ...
}

When User make zoom in, the text of Button should be decrease down to 8sp and disappear if user continue zoom in.

So, now I have dilemma : what I need to do? Resize items in Adapter, or resize them in LayoutManager, and update whole adapter.

Both of scenarios seems affect an performance of visual effect, so I need help. Maybe you give me a better solution.

For state of 21/11/2016 I can't found any box-solution for this case.

So I decide write my own view and do remeasurement of visible views in each zoom scale factor change.

Body:
user this code. it's working fine for zooming all content of recyclerview.

import android.content.Context;
import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;

/**
@author yogesh
* */
public class PinchRecyclerView extends RecyclerView {
    private static final int INVALID_POINTER_ID = -1;
    private int mActivePointerId = INVALID_POINTER_ID;
    private ScaleGestureDetector mScaleDetector;
    private float mScaleFactor = 1.f;
    private float maxWidth = 0.0f;
    private float maxHeight = 0.0f;
    private float mLastTouchX;
    private float mLastTouchY;
    private float mPosX;
    private float mPosY;
    private float width;
    private float height;

    public PinchRecyclerView(Context context) {
        super(context);
        if (!isInEditMode())
            mScaleDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
    }

    public PinchRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (!isInEditMode())
            mScaleDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
    }

    public PinchRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (!isInEditMode())
            mScaleDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        try {
            return super.onInterceptTouchEvent(ev);
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent ev) {
        super.onTouchEvent(ev);
        final int action = ev.getAction();
        mScaleDetector.onTouchEvent(ev);
        switch (action & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN: {
                final float x = ev.getX();
                final float y = ev.getY();
                mLastTouchX = x;
                mLastTouchY = y;
                mActivePointerId = ev.getPointerId(0);
                break;
            }

            case MotionEvent.ACTION_MOVE: {
                /* this line is replaced because here came below isssue
                java.lang.IllegalArgumentException: pointerIndex out of range
                 ref http://stackoverflow.com/questions/6919292/pointerindex-out-of-range-android-multitouch
                */
                //final int pointerIndex = ev.findPointerIndex(mActivePointerId);

                final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK)
                        >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
                final float x = ev.getX(pointerIndex);
                final float y = ev.getY(pointerIndex);
                final float dx = x - mLastTouchX;
                final float dy = y - mLastTouchY;

                mPosX += dx;
                mPosY += dy;

                if (mPosX > 0.0f)
                    mPosX = 0.0f;
                else if (mPosX < maxWidth)
                    mPosX = maxWidth;

                if (mPosY > 0.0f)
                    mPosY = 0.0f;
                else if (mPosY < maxHeight)
                    mPosY = maxHeight;

                mLastTouchX = x;
                mLastTouchY = y;

                invalidate();
                break;
            }

            case MotionEvent.ACTION_UP: {
                mActivePointerId = INVALID_POINTER_ID;
                break;
            }

            case MotionEvent.ACTION_CANCEL: {
                mActivePointerId = INVALID_POINTER_ID;
                break;
            }

            case MotionEvent.ACTION_POINTER_UP: {
                final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
                final int pointerId = ev.getPointerId(pointerIndex);
                if (pointerId == mActivePointerId) {
                    final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                    mLastTouchX = ev.getX(newPointerIndex);
                    mLastTouchY = ev.getY(newPointerIndex);
                    mActivePointerId = ev.getPointerId(newPointerIndex);
                }
                break;
            }
        }

        return true;
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        canvas.translate(mPosX, mPosY);
        canvas.scale(mScaleFactor, mScaleFactor);
        canvas.restore();
    }

    @Override
    protected void dispatchDraw(@NonNull Canvas canvas) {
        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        if (mScaleFactor == 1.0f) {
            mPosX = 0.0f;
            mPosY = 0.0f;
        }
        canvas.translate(mPosX, mPosY);
        canvas.scale(mScaleFactor, mScaleFactor);
        super.dispatchDraw(canvas);
        canvas.restore();
        invalidate();
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();
            mScaleFactor = Math.max(1.0f, Math.min(mScaleFactor, 3.0f));
            maxWidth = width - (width * mScaleFactor);
            maxHeight = height - (height * mScaleFactor);
            invalidate();
            return true;
        }
    }
}

Code taken from this StackOverflow answer: Android change recycler view column no. on pinch zoom


来源: stackexchange

问:
What's the purpose of having both db level and code level uniqueness validations in Rails?
I see a table that has both db-level and code-level validations in Rails.

```<code>CREATE UNIQUE INDEX some_index_name ON joined_table_name USING btree (user_id, restriction_id);
</code>```

and code level:

```<code>class SomeJoinTable
validates_uniqueness_of :restriction_id, :scope => :user_id
end
</code>```

What's the benefit of having both?

答:
What's the benefit of having both?

The db-level guard is the ultimate protection. It is what keeps your data consistent.

The app-level guard, while also doing some checks, can't be relied on to keep your data consistent. Its purpose is to power ActiveRecord validations (populate errors array so you can show pretty form errors, etc.)

So, if you have only the db guard, you have to do extra work to intercept db errors and show user-friendly form errors.

And if you have only app-level check, you might as well delete it. It is vulnerable to race conditions and violations will happen, sooner or later.

ContentLicense: CC BY-SA 3.0

Body:
I see a table that has both db-level and code-level validations in Rails.

CREATE UNIQUE INDEX some_index_name ON joined_table_name USING btree (user_id, restriction_id);

and code level:

class SomeJoinTable
validates_uniqueness_of :restriction_id, :scope => :user_id
end

What's the benefit of having both?


问:
Optimized mysql queries in mysql database
I want to fetch 3 rows data from class table who is belongs to class 5,6 and 7 last row only.

Right now I'm using 3 sql queries to fetch data:

```<code> 1. SELECT * from class where class_name = '5';

 2. SELECT * from class where class_name = '6';

 3. SELECT * from class where class_name = '7';
</code>```

How can I use single sql query to retrieve 3 row data instead of 3 sql queries ?

```<code>**class table structure:**

|id | class_name | student  |
|---| -----------| ---------|
|1  |      5     | Student A|
|2  |      6     | Student B|
|3  |      4     | Student C|
|4  |      6     | Student D|
|5  |      7     | Student E|
|6  |      5     | Student F|
|7  |      4     | Student G|
|8  |      6     | Student H|
|9  |      5     | Student I|
|10 |      6     | Student J|
|11 |      7     | Student K|
|12 |      6     | Student L|
|13 |      8     | Student M|
|14 |      6     | Student N|
|15 |      8     | Student O|
</code>```

Result required:
Student I,Student N and Student K

答:
try this

```<code>SELECT * FROM class WHERE id IN (SELECT MAX(id) FROM class WHERE class_name in (5,6,7) GROUP BY class_name );
</code>```

sqlfiddle

Body:
I want to fetch 3 rows data from class table who is belongs to class 5,6 and 7 last row only.

Right now I'm using 3 sql queries to fetch data:

 1. SELECT * from class where class_name = '5';

 2. SELECT * from class where class_name = '6';

 3. SELECT * from class where class_name = '7';

How can I use single sql query to retrieve 3 row data instead of 3 sql queries ?

**class table structure:**

|id | class_name | student  |
|---| -----------| ---------|
|1  |      5     | Student A|
|2  |      6     | Student B|
|3  |      4     | Student C|
|4  |      6     | Student D|
|5  |      7     | Student E|
|6  |      5     | Student F|
|7  |      4     | Student G|
|8  |      6     | Student H|
|9  |      5     | Student I|
|10 |      6     | Student J|
|11 |      7     | Student K|
|12 |      6     | Student L|
|13 |      8     | Student M|
|14 |      6     | Student N|
|15 |      8     | Student O|

Result required:
Student I,Student N and Student K

Body:
try this

SELECT * FROM class WHERE id IN (SELECT MAX(id) FROM class WHERE class_name in (5,6,7) GROUP BY class_name );

sqlfiddle


问:
android custom layout doesn't align correctly in gridView
I am having an layout issue where i have a custom layout I use in a gridView in which a checkbox is suppose to align at the bottom right corner of an imageView. The preview of the layout shows it looks correct but when it loads into the gridView it moves the check box to the top left of the imageView. I have tried making the image smaller in the gridView and also removing the spacing in in between objects in the gridview, but to no avail.

here is my custom layout for each item of the gridView

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

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imgThumb"
    android:layout_alignRight="@+id/imgThumb"
    android:layout_alignBottom="@+id/imgThumb"/>

</RelativeLayout>
</code>```

and here is the gridView layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<GridView
    android:id="@+id/grdImages"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:numColumns="3"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

<Button
    android:id="@+id/btnSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select"
    android:layout_marginTop="5dp"/>

</LinearLayout>
</code>```

here is an image of what i would like the item in the gridview to look like, and this is also what the preview shows it will look like Preview

and this is what happens in the actual gridView GridView

答:
This works fine for me.</p>

```<code><ImageView
 android:id="@+id/imgThumb"
 android:layout_width="100dp"
 android:layout_height="100dp"/>
<CheckBox
 android:marginTop="80dp"
 android:id="@+id/chkImage"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignRight="@+id/imgThumb"/>
</code>```

Body:
I am having an layout issue where i have a custom layout I use in a gridView in which a checkbox is suppose to align at the bottom right corner of an imageView. The preview of the layout shows it looks correct but when it loads into the gridView it moves the check box to the top left of the imageView. I have tried making the image smaller in the gridView and also removing the spacing in in between objects in the gridview, but to no avail.

here is my custom layout for each item of the gridView

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

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imgThumb"
    android:layout_alignRight="@+id/imgThumb"
    android:layout_alignBottom="@+id/imgThumb"/>

</RelativeLayout>

and here is the gridView layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<GridView
    android:id="@+id/grdImages"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:numColumns="3"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

<Button
    android:id="@+id/btnSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select"
    android:layout_marginTop="5dp"/>

</LinearLayout>

here is an image of what i would like the item in the gridview to look like, and this is also what the preview shows it will look like Preview

and this is what happens in the actual gridView GridView

Body:
This works fine for me.

<ImageView
 android:id="@+id/imgThumb"
 android:layout_width="100dp"
 android:layout_height="100dp"/>
<CheckBox
 android:marginTop="80dp"
 android:id="@+id/chkImage"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignRight="@+id/imgThumb"/>


问:
Joining database values and add to an array using Java
This is part of my web service java project in netbeans.
I do not know how i can retrieve the two value from my database(the description + the culture - these are the columns), add them both to an array, and then retrieve them both later.
I know how to do this when retrieving just one value.

```<code>   public String countries(@WebParam(name = "name") String name) {
            //TODO write your implementation code here
            try {
                String url = "jdbc:odbc:" + "worldcup";
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

                Connection con = DriverManager.getConnection(url,"","");

                // Gets a statement
                Statement state1 = con.createStatement();
                //Statement state2 = con.createStatement();

                String query1 = "SELECT description,culture FROM Countries WHERE name = '" + name + "'";
                // selects the description for the selected group ( group will be referenced to the chosen group)
                ResultSet results = state1.executeQuery(query1);
                int i = 0;

                Arrays.fill(names, "");
                while (results.next()) {
                    String nam = results.getString("description"); // <---- this is the part i need help from
                    names[i++] = nam;
                }

                return Arrays.toString(names);

            } catch (SQLException e){

                e.printStackTrace();
            } catch (ClassNotFoundException e) {

            }
            return null;
</code>```

答:
You can access the value either through column name or column index.

Access by Column Name.

```<code>names[i++] = results.getString("description");

names[i++] = results.getString("culture");
</code>```

Access by column index.

```<code>names[i++] = results.getString(1);

names[i++] = results.getString(2);
</code>```

Body:
This is part of my web service java project in netbeans.
I do not know how i can retrieve the two value from my database(the description + the culture - these are the columns), add them both to an array, and then retrieve them both later.
I know how to do this when retrieving just one value.

   public String countries(@WebParam(name = "name") String name) {
            //TODO write your implementation code here
            try {
                String url = "jdbc:odbc:" + "worldcup";
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

                Connection con = DriverManager.getConnection(url,"","");

                // Gets a statement
                Statement state1 = con.createStatement();
                //Statement state2 = con.createStatement();

                String query1 = "SELECT description,culture FROM Countries WHERE name = '" + name + "'";
                // selects the description for the selected group ( group will be referenced to the chosen group)
                ResultSet results = state1.executeQuery(query1);
                int i = 0;

                Arrays.fill(names, "");
                while (results.next()) {
                    String nam = results.getString("description"); // <---- this is the part i need help from
                    names[i++] = nam;
                }

                return Arrays.toString(names);

            } catch (SQLException e){

                e.printStackTrace();
            } catch (ClassNotFoundException e) {

            }
            return null;

Body:
You can access the value either through column name or column index.

Access by Column Name.

names[i++] = results.getString("description");

names[i++] = results.getString("culture");

Access by column index.

names[i++] = results.getString(1);

names[i++] = results.getString(2);


问:
How to color System.out.println output?
How can I color Java output?

For example in C and other languages I can use ANSI-escape like \033[0m to do this. But in Java it doesn't work.

```<code>public static void main(String[] x) {
    System.out.println("\033[0m BLABLA \033[0m\n");
}
</code>```

答:
Check This Out: i used ANSI values with escape code and it probably not work in windows command prompt but in IDEs and Unix shell.
you can also check 'Jansi' library here  for windows support.</p>

```<code>System.out.println("\u001B[35m" + "This text is PURPLE!" + "\u001B[0m");
</code>```

Title: How to color System.out.println output?

Body:
How can I color Java output?

For example in C and other languages I can use ANSI-escape like \033[0m to do this. But in Java it doesn't work.

public static void main(String[] x) {
    System.out.println("\033[0m BLABLA \033[0m\n");
}

Body:
Check This Out: i used ANSI values with escape code and it probably not work in windows command prompt but in IDEs and Unix shell.
you can also check 'Jansi' library here  for windows support.

System.out.println("\u001B[35m" + "This text is PURPLE!" + "\u001B[0m");


问:
Accessing shared variables from two threads in Java
I'm building an application in Java which requires a Hashtable to be accessed from instances of two classes and both extend threads. I have declared the Hashtable in one of the two classes. I always get null when i try to access the Hashtable contents from one of the classes. The other class is able to access the contents without any problem. I thought this was a problem of concurrency control. Since these are threads of different classes we cannot use synchronized methods. Is there a way to make the Hashtable accessible from threads of both the classes?

Here are the some parts of the code of my application
This is the class which stores the HashMap:

```<code>public class DataStore {
public Map ChatWindows ;
public DataStore()
{
    ChatWindows = new ConcurrentHashMap();
}
public synchronized void putWindow(String with,ChatWindow t)
{
    ChatWindows.put(with,t);
    notifyAll();
}
public synchronized ChatWindow getWindow(String with)
{
    notifyAll();
    return (ChatWindow)ChatWindows.get(with);
}
public synchronized void ChatWindowOpen(chatClient cc,String with,String msg)
    {
       //    chatWith = with;
        ChatWindow t;
        System.out.println(with);
            t = getWindow(with);
           if(t == null)
           {
               t = new ChatWindow(cc,with,msg);
         //      th = new Thread(t);
               putWindow(with, t);
         //      th.start();
           }
           else
           {
              t.setVisible(true);

            }
}
}
</code>```

Two classes which access 'ChatWindows' HashMap

```<code>public class chatClient extends javax.swing.JFrame implements

Runnable,ListSelectionListener,MouseListener,WindowListener{

  static String LoginName,chatWith,msgToChatWindow;
    Thread listThread=null,th,chatListen;
static  Socket soc;
static  DataOutputStream dout,dout1;
static  DataInputStream din,din1;
        DefaultListModel listModel;

        ChatWindow t;

    public DataStore ds;
/** Creates new form chatClient */
public chatClient(Login l,DataStore ds) {
    listModel = new DefaultListModel();
    initComponents();
    clientList.addListSelectionListener(this);

     clientList.addMouseListener(this);
     addWindowListener(this);
      this.LoginName=l.loginName;

        soc = l.soc2;
        din = l.din2;
        dout = l.dout2;
        dout1 = l.dout1;
        din1 = l.din1;
        super.setTitle(LoginName);

        listThread = new Thread(this);
        listThread.start();
        this.ds = ds;

}
.
.
.
.
public void mouseClicked(MouseEvent e)
{
    chatWith = (String)clientList.getSelectedValue();
    ds.ChatWindowOpen(this,chatWith,"");
}
</code>```

This class has run() method too, but that doesn't use the HashMap. This class is able to access the 'ChatWindows' properly.'ChatListenThread' class is not able to access the contents of HashMap properly.

```<code>public class ChatListenThread implements Runnable{

DataOutputStream dout1;
DataInputStream din1;
public static chatClient cc;
public static ChatWindow t;
public DataStore ds;
    public ChatListenThread(Login l,DataStore ds)
    {
        din1 = l.din1;
        dout1= l.dout1;
        this.ds = ds;
    }
.
.
.
.
public void run(){
   while(true)
   {
       try{
                    String msgFromServer=new String();
                    msgFromServer = din1.readUTF();
                    StringTokenizer st=new StringTokenizer(msgFromServer);
        String msgFrom=st.nextToken();
        String MsgType=st.nextToken();
                    String msg = "";
                   while(st.hasMoreTokens())
        {
            msg=msg+" " +st.nextToken();
        }

                    ds.ChatWindowOpen(cc,msgFrom,msg);

       }
       catch(IOException e)
       {
            System.out.println("Read failed");

       }
   }
</code>```

}
}

答: It's possible. Take a look at Sharing data safely between two threads.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm building an application in Java which requires a Hashtable to be accessed from instances of two classes and both extend threads. I have declared the Hashtable in one of the two classes. I always get null when i try to access the Hashtable contents from one of the classes. The other class is able to access the contents without any problem. I thought this was a problem of concurrency control. Since these are threads of different classes we cannot use synchronized methods. Is there a way to make the Hashtable accessible from threads of both the classes?

Here are the some parts of the code of my application
This is the class which stores the HashMap:

public class DataStore {
public Map ChatWindows ;
public DataStore()
{
    ChatWindows = new ConcurrentHashMap();
}
public synchronized void putWindow(String with,ChatWindow t)
{
    ChatWindows.put(with,t);
    notifyAll();
}
public synchronized ChatWindow getWindow(String with)
{
    notifyAll();
    return (ChatWindow)ChatWindows.get(with);
}
public synchronized void ChatWindowOpen(chatClient cc,String with,String msg)
    {
       //    chatWith = with;
        ChatWindow t;
        System.out.println(with);
            t = getWindow(with);
           if(t == null)
           {
               t = new ChatWindow(cc,with,msg);
         //      th = new Thread(t);
               putWindow(with, t);
         //      th.start();
           }
           else
           {
              t.setVisible(true);

            }
}
}

Two classes which access 'ChatWindows' HashMap

public class chatClient extends javax.swing.JFrame implements

Runnable,ListSelectionListener,MouseListener,WindowListener{

  static String LoginName,chatWith,msgToChatWindow;
    Thread listThread=null,th,chatListen;
static  Socket soc;
static  DataOutputStream dout,dout1;
static  DataInputStream din,din1;
        DefaultListModel listModel;

        ChatWindow t;

    public DataStore ds;
/** Creates new form chatClient */
public chatClient(Login l,DataStore ds) {
    listModel = new DefaultListModel();
    initComponents();
    clientList.addListSelectionListener(this);

     clientList.addMouseListener(this);
     addWindowListener(this);
      this.LoginName=l.loginName;

        soc = l.soc2;
        din = l.din2;
        dout = l.dout2;
        dout1 = l.dout1;
        din1 = l.din1;
        super.setTitle(LoginName);

        listThread = new Thread(this);
        listThread.start();
        this.ds = ds;

}
.
.
.
.
public void mouseClicked(MouseEvent e)
{
    chatWith = (String)clientList.getSelectedValue();
    ds.ChatWindowOpen(this,chatWith,"");
}

This class has run() method too, but that doesn't use the HashMap. This class is able to access the 'ChatWindows' properly.'ChatListenThread' class is not able to access the contents of HashMap properly.

public class ChatListenThread implements Runnable{

DataOutputStream dout1;
DataInputStream din1;
public static chatClient cc;
public static ChatWindow t;
public DataStore ds;
    public ChatListenThread(Login l,DataStore ds)
    {
        din1 = l.din1;
        dout1= l.dout1;
        this.ds = ds;
    }
.
.
.
.
public void run(){
   while(true)
   {
       try{
                    String msgFromServer=new String();
                    msgFromServer = din1.readUTF();
                    StringTokenizer st=new StringTokenizer(msgFromServer);
        String msgFrom=st.nextToken();
        String MsgType=st.nextToken();
                    String msg = "";
                   while(st.hasMoreTokens())
        {
            msg=msg+" " +st.nextToken();
        }

                    ds.ChatWindowOpen(cc,msgFrom,msg);

       }
       catch(IOException e)
       {
            System.out.println("Read failed");

       }
   }

}
}


答:
Try this Code:

```<code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
    android:layout_width="100dp"
    android:layout_height="100dp">

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"/>
</RelativeLayout>
</code>```

Title: android custom layout doesn't align correctly in gridView

Body:
Try this Code:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
    android:layout_width="100dp"
    android:layout_height="100dp">

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"/>
</RelativeLayout>


问:
How to create SQL multiple count count query by date?
I have a query that selects counts group by department.

```<code>select department, count(*) group by department
</code>```

This returns two columns data result. I wonder if select cout, count by today and count by this month same query.

```<code>Department  Total  Today  ThisMonth
AAA         40     8      23
BBB         20     6      11
</code>```

答:
Try This</p>

```<code>select department,count(*),
sum(case when datecolumn= GETDATE() then 1 else 0 end) as Today,
sum(case when month(datecolumn) =month(GETDATE() and year(datecolumn) =year(GETDATE()) then 1 else 0 end) as ThisMonth
from YourTable
group by department
</code>```

Body:
I have a query that selects counts group by department.

select department, count(*) group by department

This returns two columns data result. I wonder if select cout, count by today and count by this month same query.

Department  Total  Today  ThisMonth
AAA         40     8      23
BBB         20     6      11

Body:
Try This

select department,count(*),
sum(case when datecolumn= GETDATE() then 1 else 0 end) as Today,
sum(case when month(datecolumn) =month(GETDATE() and year(datecolumn) =year(GETDATE()) then 1 else 0 end) as ThisMonth
from YourTable
group by department


问:
Spring MVC custom event which extends ApplicationEvent called twice
I've done a user registration email confirmation in my Spring app, based on this tutorial http://www.baeldung.com/registration-verify-user-by-email

Having a strange problem. for unknown reason, my custom event always fired 2 times.

Here is the code:
event:

```<code>public class OnRegistrationCompleteEvent extends ApplicationEvent {
    private final String appUrl;
    private final Locale locale;
    private final User user;

    public OnRegistrationCompleteEvent(User user, Locale locale, String appUrl) {
        super(user);

        this.user = user;
        this.locale = locale;
        this.appUrl = appUrl;
    }

    public String getAppUrl() {
        return appUrl;
    }
    public Locale getLocale() {
        return locale;
    }
    public User getUser() {
        return user;
    }
}
</code>```

listener:

```<code>@Component
public class RegistrationListener implements ApplicationListener<OnRegistrationCompleteEvent> {

    private final static Logger logger = LogManager.getLogger(RegistrationListener.class.getName());

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void onApplicationEvent(OnRegistrationCompleteEvent event) {
        this.confirmRegistration(event);
    }

    private void confirmRegistration(OnRegistrationCompleteEvent event) {
        logger.info("OnRegistrationCompleteEvent confirmSocialPosting fired");
        final User user = event.getUser();

        String recipientAddress = user.getEmail();
        String subject = "Registration Confirmation";
        String from = "contactblablabla@gmail.com";

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage, false, "utf-8");
            String htmlMsg = "Your account was successfully registered! <br><br>" +
                    "username: "+user.getUsername()+"<br>"+
                    "password: "+user.getPassword()+"<br>";

            mimeMessage.setContent(htmlMsg, "text/html");
            helper.setTo(new InternetAddress(recipientAddress));
            helper.setSubject(subject);
            helper.setFrom(new InternetAddress(from));
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            logger.error("Message creation exception: "+e.getMessage());
        }
    }
}
</code>```

controller:

```<code>@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public JsonResponse AddUser(@RequestBody @Valid User user, WebRequest request) throws SQLException {
        String result = userService.RegisterUser(user);
        if(result.equals("done")) {
            try {
                String appUrl = request.getContextPath();
                eventPublisher.publishEvent(new OnRegistrationCompleteEvent(user, request.getLocale(), appUrl));
            } catch (Exception me) {
                return new JsonResponse("FAIL", "Unknown on event publishing: "+ me.getMessage());
            }
            return new JsonResponse("OK", "");

        } else if(result.equals("duplicate")) {
            return new JsonResponse("FAIL", "duplicate");
        }
        return new JsonResponse("FAIL", "Unknown");
}
</code>```

So, in my log, i have OnRegistrationCompleteEvent confirmSocialPosting fired 2 times. And 2 emails send. What is the problem can be?

答:
This is cause because it to register twice. You are using anotation in your application i.e base-package="com.example"
thats why it registering twise

Remove anotation @component from your listener class and define bean defination in .xml file

this wokrs!!

Body:
I've done a user registration email confirmation in my Spring app, based on this tutorial http://www.baeldung.com/registration-verify-user-by-email

Having a strange problem. for unknown reason, my custom event always fired 2 times.

Here is the code:
event:

public class OnRegistrationCompleteEvent extends ApplicationEvent {
    private final String appUrl;
    private final Locale locale;
    private final User user;

    public OnRegistrationCompleteEvent(User user, Locale locale, String appUrl) {
        super(user);

        this.user = user;
        this.locale = locale;
        this.appUrl = appUrl;
    }

    public String getAppUrl() {
        return appUrl;
    }
    public Locale getLocale() {
        return locale;
    }
    public User getUser() {
        return user;
    }
}

listener:

@Component
public class RegistrationListener implements ApplicationListener<OnRegistrationCompleteEvent> {

    private final static Logger logger = LogManager.getLogger(RegistrationListener.class.getName());

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void onApplicationEvent(OnRegistrationCompleteEvent event) {
        this.confirmRegistration(event);
    }

    private void confirmRegistration(OnRegistrationCompleteEvent event) {
        logger.info("OnRegistrationCompleteEvent confirmSocialPosting fired");
        final User user = event.getUser();

        String recipientAddress = user.getEmail();
        String subject = "Registration Confirmation";
        String from = "contactblablabla@gmail.com";

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage, false, "utf-8");
            String htmlMsg = "Your account was successfully registered!

" +
                    "username: "+user.getUsername()+"
"+
                    "password: "+user.getPassword()+"
";

            mimeMessage.setContent(htmlMsg, "text/html");
            helper.setTo(new InternetAddress(recipientAddress));
            helper.setSubject(subject);
            helper.setFrom(new InternetAddress(from));
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            logger.error("Message creation exception: "+e.getMessage());
        }
    }
}

controller:

@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public JsonResponse AddUser(@RequestBody @Valid User user, WebRequest request) throws SQLException {
        String result = userService.RegisterUser(user);
        if(result.equals("done")) {
            try {
                String appUrl = request.getContextPath();
                eventPublisher.publishEvent(new OnRegistrationCompleteEvent(user, request.getLocale(), appUrl));
            } catch (Exception me) {
                return new JsonResponse("FAIL", "Unknown on event publishing: "+ me.getMessage());
            }
            return new JsonResponse("OK", "");

        } else if(result.equals("duplicate")) {
            return new JsonResponse("FAIL", "duplicate");
        }
        return new JsonResponse("FAIL", "Unknown");
}

So, in my log, i have OnRegistrationCompleteEvent confirmSocialPosting fired 2 times. And 2 emails send. What is the problem can be?


问:
Jersey Grizzly Containers w/ @WebListener ServletContextListeners
I've got my JAX-RS web services running with grizzly-server, but I cannot configure my @WebListener to work. I am building a framework so I cannot switch to Grizzly listeners.

I've got the latest libraries.

```<code><dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-http</artifactId>
</dependency>
<dependency>
    <groupId>org.glassfish.grizzly</groupId>
    <artifactId>grizzly-http-servlet</artifactId>
    <version>2.3.30</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
</dependency>
</code>```

Here is some code:

```<code>@ApplicationPath("/SampleAdmin")
public class SampleAdminApplication extends ResourceConfig {
    public SampleAdminApplication() {
        packages("com.companyname.sample.sampleadmin.server.services");
    }
}

    @WebListener
    public class SampleAdminListener implements ServletContextListener {
        private static final Logger log = Logger.getLogger(SampleAdminListener.class);

        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent) {
            log.info("SampleAdminListener Initializing context.");
        }

        @Override
        public void contextDestroyed(ServletContextEvent servletContextEvent) {
            log.info("SampleAdminListener Destroying context.");
        }
    }
    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     */
    public static HttpServer startServer() {
        // create a resource config that scans for JAX-RS resources and providers
        // in com.example.rest package
        final ResourceConfig rc = new SampleAdminApplication();

        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);

        WebappContext context = new WebappContext("WebappContext", "/" + webapp);
        context.addListener("com.vilabs.sample.sampleadmin.server.servlet.SampleAdminListener");
        context.addFilter("SampleAdminFilter", SampleAdminFilter.class);
        context.addFilter("SampleAdminCsrfFilter", SampleAdminCsrfFilter.class);
//        ServletRegistration registration = context.addServlet("ServletContainer", new ServletContainer(rc));
        ServletRegistration registration = context.addServlet("ServletContainer", new ServletContainer(rc));
        registration.addMapping("/*");

        context.deploy(httpServer);
        return httpServer;
    }
</code>```

The call to context.deploy(httpServer) throws IllegalStateException.

```<code>Jun 06, 2017 7:14:14 PM org.glassfish.grizzly.servlet.WebappContext deploy
SEVERE: [WebappContext] Exception deploying application.  See stack trace for details.
java.lang.RuntimeException: java.lang.IllegalStateException: The resource configuration is not modifiable in this context.
    at org.glassfish.grizzly.servlet.WebappContext.initServlets(WebappContext.java:1833)
    at org.glassfish.grizzly.servlet.WebappContext.deploy(WebappContext.java:318)
    at com.vilabs.sample.sampleadmin.server.SampleServer.startServer(SampleServer.java:60)
    at com.vilabs.sample.sampleadmin.server.SampleServer.main(SampleServer.java:70)
Caused by: java.lang.IllegalStateException: The resource configuration is not modifiable in this context.
    at org.glassfish.jersey.server.ResourceConfig$ImmutableState.register(ResourceConfig.java:274)
    at org.glassfish.jersey.server.ResourceConfig$ImmutableState.register(ResourceConfig.java:221)
    at org.glassfish.jersey.server.ResourceConfig.register(ResourceConfig.java:453)
    at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:387)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at org.glassfish.grizzly.servlet.WebappContext.initServlets(WebappContext.java:1831)
</code>```

答:
IllegalStateException: The resource configuration is not modifiable in this context

It's because createHttpServer(uri, resourceConfig) automatically starts the server unless the boolean flag is passed to the overloaded method, telling it not to auto-start.

Another thing is that you are are trying to create two applications. Once when you call createHttpServer passing the ResourceConfig, and another time when you create the ServletContainer with the same ResourceConfig.

What you should do is just the overloaded createHttpServer(uri). This won't create an application, and won't start the server. And you create the Jersey application when you create the ServletContainer with the ResourceConfig, and pass it to the WebAppContext.

Body:
I've got my JAX-RS web services running with grizzly-server, but I cannot configure my @WebListener to work. I am building a framework so I cannot switch to Grizzly listeners.

I've got the latest libraries.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-http</artifactId>
</dependency>
<dependency>
    <groupId>org.glassfish.grizzly</groupId>
    <artifactId>grizzly-http-servlet</artifactId>
    <version>2.3.30</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
</dependency>

Here is some code:

@ApplicationPath("/SampleAdmin")
public class SampleAdminApplication extends ResourceConfig {
    public SampleAdminApplication() {
        packages("com.companyname.sample.sampleadmin.server.services");
    }
}

    @WebListener
    public class SampleAdminListener implements ServletContextListener {
        private static final Logger log = Logger.getLogger(SampleAdminListener.class);

        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent) {
            log.info("SampleAdminListener Initializing context.");
        }

        @Override
        public void contextDestroyed(ServletContextEvent servletContextEvent) {
            log.info("SampleAdminListener Destroying context.");
        }
    }
    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     */
    public static HttpServer startServer() {
        // create a resource config that scans for JAX-RS resources and providers
        // in com.example.rest package
        final ResourceConfig rc = new SampleAdminApplication();

        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);

        WebappContext context = new WebappContext("WebappContext", "/" + webapp);
        context.addListener("com.vilabs.sample.sampleadmin.server.servlet.SampleAdminListener");
        context.addFilter("SampleAdminFilter", SampleAdminFilter.class);
        context.addFilter("SampleAdminCsrfFilter", SampleAdminCsrfFilter.class);
//        ServletRegistration registration = context.addServlet("ServletContainer", new ServletContainer(rc));
        ServletRegistration registration = context.addServlet("ServletContainer", new ServletContainer(rc));
        registration.addMapping("/*");

        context.deploy(httpServer);
        return httpServer;
    }

The call to context.deploy(httpServer) throws IllegalStateException.

Jun 06, 2017 7:14:14 PM org.glassfish.grizzly.servlet.WebappContext deploy
SEVERE: [WebappContext] Exception deploying application.  See stack trace for details.
java.lang.RuntimeException: java.lang.IllegalStateException: The resource configuration is not modifiable in this context.
    at org.glassfish.grizzly.servlet.WebappContext.initServlets(WebappContext.java:1833)
    at org.glassfish.grizzly.servlet.WebappContext.deploy(WebappContext.java:318)
    at com.vilabs.sample.sampleadmin.server.SampleServer.startServer(SampleServer.java:60)
    at com.vilabs.sample.sampleadmin.server.SampleServer.main(SampleServer.java:70)
Caused by: java.lang.IllegalStateException: The resource configuration is not modifiable in this context.
    at org.glassfish.jersey.server.ResourceConfig$ImmutableState.register(ResourceConfig.java:274)
    at org.glassfish.jersey.server.ResourceConfig$ImmutableState.register(ResourceConfig.java:221)
    at org.glassfish.jersey.server.ResourceConfig.register(ResourceConfig.java:453)
    at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:387)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at org.glassfish.grizzly.servlet.WebappContext.initServlets(WebappContext.java:1831)


问:
How to change the HSV values of an image in python?
I am able to convert an image from the RGB to HSV colorspace, but how can I then manipulate those values using the HSV scale as outlined in the PIL documentation?</p>

```<code>img = Image.open("assets/image.png")
img = img.convert('HSV')
img.show()
</code>```

答:
You can convert the image to a NumPy array and manipulate it from there.

For example, to shift the hue:

```<code>import numpy as np
from PIL import image

def hue_shift(img, amount):
    hsv_img = img.convert('HSV')
    hsv = np.array(hsv_img)
    hsv[..., 0] = (hsv[..., 0]+amount) % 360
    new_img = Image.fromarray(hsv, 'HSV')
    return new_img.convert('RGB')
</code>```

Body:
I am able to convert an image from the RGB to HSV colorspace, but how can I then manipulate those values using the HSV scale as outlined in the PIL documentation?

img = Image.open("assets/image.png")
img = img.convert('HSV')
img.show()

Body:
You can convert the image to a NumPy array and manipulate it from there.

For example, to shift the hue:

import numpy as np
from PIL import image

def hue_shift(img, amount):
    hsv_img = img.convert('HSV')
    hsv = np.array(hsv_img)
    hsv[..., 0] = (hsv[..., 0]+amount) % 360
    new_img = Image.fromarray(hsv, 'HSV')
    return new_img.convert('RGB')


问:
How to make actionscript run once?
When I add actionscript to a Flash movie, it runs every time the movie enters a new loop. How do I make it run only once, when the movie has finished loading?</p>

答:
Just set a flag telling you if the script has already executed. Like this;</p>

```<code>var done:Boolean;
if (!done) {

    // any code here will run only once.

    done=true;
}
</code>```

Title: How to make actionscript run once?

Body:
Just set a flag telling you if the script has already executed. Like this;

var done:Boolean;
if (!done) {

    // any code here will run only once.

    done=true;
}


问:
SQL: How to make a query which takes a possible null value into respect according to my specific task?
```<code>Table1

Col1|Col2
----|----
AAAA|1111
BBBB|2222
CCCC|3333
CCCC|4444
</code>```

Following query is given:

```<code>SELECT Col1,Col2 from Table1 where Col1+Col2 like 'CCCC%'
</code>```

This works. It returns row 3 and row 4 as expected.

Now there is another table which holds data like following:

```<code>Table2

Col1|Col2
----|----
AAAA|1111
CCCC|
</code>```

Now I want to get AAAA|1111 and BOTH of CCCC rows from Table 1.

Therefore I made the columns of Table2 like following:

```<code>Col1 varchar(50) DEFAULT ('%')
Col2 varchar(50) DEFAULT ('%')
</code>```

And finally, if I use both tables "together", following query is used:

```<code>SELECT Col1,Col2 where Col1+Col2 in (SELECT Col1+Col2 FROM Table2)
</code>```

=> It does only return the AAAA|1111, but NOT CCCC-rows.
Conclusion: The DEFAULT value '%' is either

a) not set at all or

b) not taken into respect

How can I resolve this?

Thank you very much!

Edit:

No, I can not change the whole "idea behind this"

Yes, I am fully aware of the possibility that the "empty" field in Table2.Col2 could be a space-character or something else, but it is 100% sure NULL

答:
NB: in performs an = against values in a list; not a like.  I think that's the root of your issue.  Try instead:

```<code>SELECT Col1, Col2
from Table1 t1
where exists (
    SELECT top 1 1
    from Table2 t2
    where t1.Col1 + t1.Col2 like t2.Col1 + t2.Col2
)
</code>```

NB: Rather than defaulting values to '%' you can replace nulls at runtime using the isnull or coalesce functions.  i.e.

```<code>SELECT Col1, Col2
from Table1 t1
where exists (
    SELECT top 1 1
    from Table2 t2
    where t1.Col1 + t1.Col2 like coalesce(t2.Col1, '%') + coalesce(t2.Col2, '%')
)
</code>```

Whilst the above is slower than using the default values approach (i.e. because we're using functions at runtime rather than a one off when the row's inserted), it likely makes more sense to leave the value as null rather than using a default value to hold something code specific.

Full Runnable Example

```<code>create table Table1 (
    Col1 varchar(10) not null
    ,Col2 varchar(10) not null
)

create table Table2 (
    Col1 varchar(10) default '%'
    ,Col2 varchar(10) default '%'
)
go
insert Table1 (Col1, Col2)
values
 ('AAAA', '1111')
,('BBBB', '2222')
,('CCCC', '3333')
,('CCCC', '4444')

insert Table2 (Col1, Col2)
values
 ('AAAA', '1111')
,('CCCC', default)

select Col1, Col2
from Table1 t1
where exists (
    select top 1 1
    from Table2 t2
    where t1.Col1 + t1.Col2 like t2.Col1 + t2.Col2
)
</code>```

Body:
Table1

Col1|Col2
----|----
AAAA|1111
BBBB|2222
CCCC|3333
CCCC|4444

Following query is given:

SELECT Col1,Col2 from Table1 where Col1+Col2 like 'CCCC%'

This works. It returns row 3 and row 4 as expected.

Now there is another table which holds data like following:

Table2

Col1|Col2
----|----
AAAA|1111
CCCC|

Now I want to get AAAA|1111 and BOTH of CCCC rows from Table 1.

Therefore I made the columns of Table2 like following:

Col1 varchar(50) DEFAULT ('%')
Col2 varchar(50) DEFAULT ('%')

And finally, if I use both tables "together", following query is used:

SELECT Col1,Col2 where Col1+Col2 in (SELECT Col1+Col2 FROM Table2)

=> It does only return the AAAA|1111, but NOT CCCC-rows.
Conclusion: The DEFAULT value '%' is either

a) not set at all or

b) not taken into respect

How can I resolve this?

Thank you very much!

Edit:

No, I can not change the whole "idea behind this"

Yes, I am fully aware of the possibility that the "empty" field in Table2.Col2 could be a space-character or something else, but it is 100% sure NULL

Body:
NB: in performs an = against values in a list; not a like.  I think that's the root of your issue.  Try instead:

SELECT Col1, Col2
from Table1 t1
where exists (
    SELECT top 1 1
    from Table2 t2
    where t1.Col1 + t1.Col2 like t2.Col1 + t2.Col2
)

NB: Rather than defaulting values to '%' you can replace nulls at runtime using the isnull or coalesce functions.  i.e.

SELECT Col1, Col2
from Table1 t1
where exists (
    SELECT top 1 1
    from Table2 t2
    where t1.Col1 + t1.Col2 like coalesce(t2.Col1, '%') + coalesce(t2.Col2, '%')
)

Whilst the above is slower than using the default values approach (i.e. because we're using functions at runtime rather than a one off when the row's inserted), it likely makes more sense to leave the value as null rather than using a default value to hold something code specific.

Full Runnable Example

create table Table1 (
    Col1 varchar(10) not null
    ,Col2 varchar(10) not null
)

create table Table2 (
    Col1 varchar(10) default '%'
    ,Col2 varchar(10) default '%'
)
go
insert Table1 (Col1, Col2)
values
 ('AAAA', '1111')
,('BBBB', '2222')
,('CCCC', '3333')
,('CCCC', '4444')

insert Table2 (Col1, Col2)
values
 ('AAAA', '1111')
,('CCCC', default)

select Col1, Col2
from Table1 t1
where exists (
    select top 1 1
    from Table2 t2
    where t1.Col1 + t1.Col2 like t2.Col1 + t2.Col2
)


问:
Trying to pass SqlCommand in SqlDataAdapter as parameters
I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();

I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.

Running code (aspx page code)

```<code>if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
        // username & password logic
        DataTable dt = new DataTable();
        string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = @USERNAME AND PASSWORD = @PASSWORD";

        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
        cmd.Parameters.Add("@PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();

        DBConnection conn_ = new DBConnection();

        dt = conn_.SelectData(cmd);

        if (conn_.SQL_dt.Rows.Count > 0)
        {
            Response.Redirect("Home.aspx", false);
        }
    }
</code>```

Successful connection class code

```<code>public DataTable SelectData(SqlCommand command)
{
    try
    {
       conn.Open();

       SqlDataAdapter DA = new SqlDataAdapter();

       command.CommandType = CommandType.Text;
       command.Connection = conn;

       DA.SelectCommand = command;
       DA.Fill(SQL_dt);

       return SQL_dt;
   }
   catch (Exception ex)
   {
       return null;
   }
   finally
   {
       conn.Close();
   }
}
</code>```

How can I pass CommandType.Text as parameters for SqlDataAdapter?

Error code

```<code>public DataTable SelectData(SqlCommand command)
{
    try
    {
        conn.Open();

        SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);

        // command.CommandType = CommandType.Text;
        // command.Connection = conn;
        DA.SelectCommand = command;
        DA.Fill(SQL_dt);

        return SQL_dt;
    }
    catch (Exception ex)
    {
        return null;
    }
    finally
    {
        conn.Close();
    }
}
</code>```

I am getting this error:

System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.

  at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...

答:
Reds has the answer.  Just to clean the code up a little bit...</p>

```<code>    public DataTable SelectData(string query)
    {
        using (var connection = new SqlConnection("myConnectionString"))
        using (var command = new SqlCommand(query, connection))
        using (var adapter = new SqlDataAdapter(command))
        {
            var dt = new DataTable();

            connection.Open();
            adapter.Fill(dt);

            return dt;
        }
    }
</code>```

Body:
I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();

I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.

Running code (aspx page code)

if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
        // username & password logic
        DataTable dt = new DataTable();
        string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = @USERNAME AND PASSWORD = @PASSWORD";

        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
        cmd.Parameters.Add("@PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();

        DBConnection conn_ = new DBConnection();

        dt = conn_.SelectData(cmd);

        if (conn_.SQL_dt.Rows.Count > 0)
        {
            Response.Redirect("Home.aspx", false);
        }
    }

Successful connection class code

public DataTable SelectData(SqlCommand command)
{
    try
    {
       conn.Open();

       SqlDataAdapter DA = new SqlDataAdapter();

       command.CommandType = CommandType.Text;
       command.Connection = conn;

       DA.SelectCommand = command;
       DA.Fill(SQL_dt);

       return SQL_dt;
   }
   catch (Exception ex)
   {
       return null;
   }
   finally
   {
       conn.Close();
   }
}

How can I pass CommandType.Text as parameters for SqlDataAdapter?

Error code

public DataTable SelectData(SqlCommand command)
{
    try
    {
        conn.Open();

        SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);

        // command.CommandType = CommandType.Text;
        // command.Connection = conn;
        DA.SelectCommand = command;
        DA.Fill(SQL_dt);

        return SQL_dt;
    }
    catch (Exception ex)
    {
        return null;
    }
    finally
    {
        conn.Close();
    }
}

I am getting this error:

System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.

  at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...

Body:
Reds has the answer.  Just to clean the code up a little bit...

    public DataTable SelectData(string query)
    {
        using (var connection = new SqlConnection("myConnectionString"))
        using (var command = new SqlCommand(query, connection))
        using (var adapter = new SqlDataAdapter(command))
        {
            var dt = new DataTable();

            connection.Open();
            adapter.Fill(dt);

            return dt;
        }
    }


问:
Unable to gather error info from halting Powershell script
I'm writing a script that will watch a directory for any new mp4 files, then convert the file using HandBrake's CLI tool.  The logic that watches the directory for changes works by itself, but if I drop a large video into the "watched" directory the conversion fails since it kicks off as soon as it sees a new file, before the file has time to finish copying.

I'm using a do until loop to check if the file is locked/downloading and then continues once the file is unlocked/writable.  The loop works as a stand-alone script, but when used inside the filesystem watcher the script it will halt without any errors on this line:

[System.IO.FileStream] $fs = $convertingFile.OpenWrite();

This occurs regardless if $ErrorActionPreference = "SilentlyContinue" is commented out.  I've been unable to gather any log output to see why the script is halting using Start-Transcript or Out-File.

How should I best gather error info about why the script halts once it hits this line?

Bonus:  Why might this script not provide error information?

```<code>    $ErrorActionPreference = "SilentlyContinue"

    function Start-FileSystemWatcher {

      [CmdletBinding()]
      param(
        [Parameter()]
        [string]$Path,
        [Parameter()]
        [ValidateSet('Changed','Created','Deleted','Renamed')]
        [string[]]$EventName,
        [Parameter()]
        [string]$Filter,
        [Parameter()]
        [System.IO.NotifyFilters]$NotifyFilter,
        [Parameter()]
        [switch]$Recurse,
        [Parameter()]
        [scriptblock]$Action
      )

      #region Build  FileSystemWatcher

      $FileSystemWatcher = New-Object System.IO.FileSystemWatcher
      if (-not $PSBoundParameters.ContainsKey('Path')) {
        $Path = $PWD
      }
      $FileSystemWatcher.Path = $Path
      if ($PSBoundParameters.ContainsKey('Filter')) {
        $FileSystemWatcher.Filter = $Filter
      }

      if ($PSBoundParameters.ContainsKey('NotifyFilter')) {
        $FileSystemWatcher.NotifyFilter = $NotifyFilter
      }

      if ($PSBoundParameters.ContainsKey('Recurse')) {
        $FileSystemWatcher.IncludeSubdirectories = $True
      }

      if (-not $PSBoundParameters.ContainsKey('EventName')) {
        $EventName = 'Changed','Created','Deleted','Renamed'
      }

      if (-not $PSBoundParameters.ContainsKey('Action')) {
        $Action = {
          switch ($Event.SourceEventArgs.ChangeType) {
            'Renamed' {
              $Object = "{0} was  {1} to {2} at {3}" -f $Event.SourceArgs[-1].OldFullPath,
              $Event.SourceEventArgs.ChangeType,
              $Event.SourceArgs[-1].FullPath,
              $Event.TimeGenerated
            }

            Default {
              $Object = "{0} was  {1} at {2}" -f $Event.SourceEventArgs.FullPath,
              $Event.SourceEventArgs.ChangeType,
              $Event.TimeGenerated
            }
          }

          $WriteHostParams = @{
            ForegroundColor = 'Green'
            BackgroundColor = 'Black'
            Object = $Object
          }

          Write-Host @WriteHostParams
        }

      }

      $ObjectEventParams = @{
        InputObject = $FileSystemWatcher
        Action = $Action

      }

      foreach ($Item in $EventName) {
        $ObjectEventParams.EventName = $Item
        $ObjectEventParams.SourceIdentifier = "File.$($Item)"
        Write-Verbose "Starting watcher for Event: $($Item)"
        $Null = Register-ObjectEvent @ObjectEventParams
      }

    }

    $FileSystemWatcherParams = @{
      Path = 'X:\share\scripts\ps\converter\input'
      Recurse = $True
      NotifyFilter = 'FileName'
      Verbose = $True
      Action = {
        $Item = Get-Item $Event.SourceEventArgs.FullPath
        $WriteHostParams = @{
          ForegroundColor = 'Green'
          BackgroundColor = 'Black'
        }

        $inputFile = "${PWD}\input\$($Item.Name)".trim()
        $outputFile = "${PWD}\output\$($Item.Name)".trim()
        $logFile = "${PWD}\log\$($Item.Name).txt"
        $testLogFile = "${PWD}\log\$($Item.Name)(t).txt"

        function mp4-Func {
          Start-Transcript -path $logFile
          Write-Host "New mp4 file detected..."
          $convertingFile = New-Object -TypeName System.IO.FileInfo -ArgumentList $inputFile
          $locked = 1
          do {
            [System.IO.FileStream] $fs = $convertingFile.OpenWrite();
            if (!$?) {
                Write-Host "Can't convert yet, file appears to be loading..."
                sleep 2
            }
            else {
                $fs.Dispose()
                $locked = 0
            }
          } until ($locked -eq 0)

          Write-Host "File unlocked and ready for conversion."
          HandBrake
          Stop-Transcript
          $WriteHostParams.Object = "Finished converting: $($Item.Name)"
        }

        function HandBrake {
          .\HandBrakeCLI.exe --input "$inputFile" `
                             --output "$outputFile" `
                             --format av_mp4 `
                             --encoder x264 `
                             --vb 1700 `
                             --two-pass `
                             --aencoder copy:aac `
                             --ab 320 `
                             --arate 48 `
                             --mixdown stereo
        }

        switch -regex ($Item.Extension) {
          '\.mp4' { mp4-Func }
        }

        Write-Host @WriteHostParams
      }

    }
    @( 'Created') | ForEach-Object {
      $FileSystemWatcherParams.EventName = $_
      Start-FileSystemWatcher @FileSystemWatcherParams
    }
</code>```

答:
Based on Burt_Harris' answer (please upvote his answer over this one), I changed the "do while" loop so that it would use try/catch rather than an if/else statement.  By using $.Exception.Message and $.Exception.ItemName I was able to better understand why the script was halting at that particular line.

Working code:

```<code>Do {
    Try {
      [System.IO.FileStream] $fs = $convertingFile.OpenWrite()
      $fs.Dispose()
      $locked = 0
    }
    Catch {
      $ErrorMessage = $_.Exception.Message
      $FailedItem = $_.Exception.ItemName
      Write-Host $ErrorMessage
      Write-Host $FailedItem
      Write-Host "Can't convert yet, file appears to be loading..."
      sleep 5
      continue
    }
  } until ($locked -eq 0)
</code>```

Body:
I'm writing a script that will watch a directory for any new mp4 files, then convert the file using HandBrake's CLI tool.  The logic that watches the directory for changes works by itself, but if I drop a large video into the "watched" directory the conversion fails since it kicks off as soon as it sees a new file, before the file has time to finish copying.

I'm using a do until loop to check if the file is locked/downloading and then continues once the file is unlocked/writable.  The loop works as a stand-alone script, but when used inside the filesystem watcher the script it will halt without any errors on this line:

[System.IO.FileStream] $fs = $convertingFile.OpenWrite();

This occurs regardless if $ErrorActionPreference = "SilentlyContinue" is commented out.  I've been unable to gather any log output to see why the script is halting using Start-Transcript or Out-File.

How should I best gather error info about why the script halts once it hits this line?

Bonus:  Why might this script not provide error information?

    $ErrorActionPreference = "SilentlyContinue"

    function Start-FileSystemWatcher {

      [CmdletBinding()]
      param(
        [Parameter()]
        [string]$Path,
        [Parameter()]
        [ValidateSet('Changed','Created','Deleted','Renamed')]
        [string[]]$EventName,
        [Parameter()]
        [string]$Filter,
        [Parameter()]
        [System.IO.NotifyFilters]$NotifyFilter,
        [Parameter()]
        [switch]$Recurse,
        [Parameter()]
        [scriptblock]$Action
      )

      #region Build  FileSystemWatcher

      $FileSystemWatcher = New-Object System.IO.FileSystemWatcher
      if (-not $PSBoundParameters.ContainsKey('Path')) {
        $Path = $PWD
      }
      $FileSystemWatcher.Path = $Path
      if ($PSBoundParameters.ContainsKey('Filter')) {
        $FileSystemWatcher.Filter = $Filter
      }

      if ($PSBoundParameters.ContainsKey('NotifyFilter')) {
        $FileSystemWatcher.NotifyFilter = $NotifyFilter
      }

      if ($PSBoundParameters.ContainsKey('Recurse')) {
        $FileSystemWatcher.IncludeSubdirectories = $True
      }

      if (-not $PSBoundParameters.ContainsKey('EventName')) {
        $EventName = 'Changed','Created','Deleted','Renamed'
      }

      if (-not $PSBoundParameters.ContainsKey('Action')) {
        $Action = {
          switch ($Event.SourceEventArgs.ChangeType) {
            'Renamed' {
              $Object = "{0} was  {1} to {2} at {3}" -f $Event.SourceArgs[-1].OldFullPath,
              $Event.SourceEventArgs.ChangeType,
              $Event.SourceArgs[-1].FullPath,
              $Event.TimeGenerated
            }

            Default {
              $Object = "{0} was  {1} at {2}" -f $Event.SourceEventArgs.FullPath,
              $Event.SourceEventArgs.ChangeType,
              $Event.TimeGenerated
            }
          }

          $WriteHostParams = @{
            ForegroundColor = 'Green'
            BackgroundColor = 'Black'
            Object = $Object
          }

          Write-Host @WriteHostParams
        }

      }

      $ObjectEventParams = @{
        InputObject = $FileSystemWatcher
        Action = $Action

      }

      foreach ($Item in $EventName) {
        $ObjectEventParams.EventName = $Item
        $ObjectEventParams.SourceIdentifier = "File.$($Item)"
        Write-Verbose "Starting watcher for Event: $($Item)"
        $Null = Register-ObjectEvent @ObjectEventParams
      }

    }

    $FileSystemWatcherParams = @{
      Path = 'X:\share\scripts\ps\converter\input'
      Recurse = $True
      NotifyFilter = 'FileName'
      Verbose = $True
      Action = {
        $Item = Get-Item $Event.SourceEventArgs.FullPath
        $WriteHostParams = @{
          ForegroundColor = 'Green'
          BackgroundColor = 'Black'
        }

        $inputFile = "${PWD}\input\$($Item.Name)".trim()
        $outputFile = "${PWD}\output\$($Item.Name)".trim()
        $logFile = "${PWD}\log\$($Item.Name).txt"
        $testLogFile = "${PWD}\log\$($Item.Name)(t).txt"

        function mp4-Func {
          Start-Transcript -path $logFile
          Write-Host "New mp4 file detected..."
          $convertingFile = New-Object -TypeName System.IO.FileInfo -ArgumentList $inputFile
          $locked = 1
          do {
            [System.IO.FileStream] $fs = $convertingFile.OpenWrite();
            if (!$?) {
                Write-Host "Can't convert yet, file appears to be loading..."
                sleep 2
            }
            else {
                $fs.Dispose()
                $locked = 0
            }
          } until ($locked -eq 0)

          Write-Host "File unlocked and ready for conversion."
          HandBrake
          Stop-Transcript
          $WriteHostParams.Object = "Finished converting: $($Item.Name)"
        }

        function HandBrake {
          .\HandBrakeCLI.exe --input "$inputFile" `
                             --output "$outputFile" `
                             --format av_mp4 `
                             --encoder x264 `
                             --vb 1700 `
                             --two-pass `
                             --aencoder copy:aac `
                             --ab 320 `
                             --arate 48 `
                             --mixdown stereo
        }

        switch -regex ($Item.Extension) {
          '\.mp4' { mp4-Func }
        }

        Write-Host @WriteHostParams
      }

    }
    @( 'Created') | ForEach-Object {
      $FileSystemWatcherParams.EventName = $_
      Start-FileSystemWatcher @FileSystemWatcherParams
    }

Body:
Based on Burt_Harris' answer (please upvote his answer over this one), I changed the "do while" loop so that it would use try/catch rather than an if/else statement.  By using $.Exception.Message and $.Exception.ItemName I was able to better understand why the script was halting at that particular line.

Working code:

Do {
    Try {
      [System.IO.FileStream] $fs = $convertingFile.OpenWrite()
      $fs.Dispose()
      $locked = 0
    }
    Catch {
      $ErrorMessage = $_.Exception.Message
      $FailedItem = $_.Exception.ItemName
      Write-Host $ErrorMessage
      Write-Host $FailedItem
      Write-Host "Can't convert yet, file appears to be loading..."
      sleep 5
      continue
    }
  } until ($locked -eq 0)


问:
Redirection based on URL?
How to do 301 Htaccess  redirect ?

Just Moved Site A Whole content to Site B . This site has 3000 plus url so cann't redirect by specifying each and every link . change is only domain name . if some clicks on sitea.com/whateverispage then he/she should redirect  to siteb.com/whateverispage

```<code>www.sitea.com/productinfo -->www.siteb.info/productinfo
</code>```

any idea to how yo get this result , this is somehow similar to wildcard in SQl and PHP

答:
please try this

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^sitea.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.sitea.com [NC]
RewriteRule ^(.*)$ http://siteb.com/$1 [L,R=301,NC]
</code>```

hope it will work for you

Title: Redirection based on URL?

Body:
How to do 301 Htaccess  redirect ?

Just Moved Site A Whole content to Site B . This site has 3000 plus url so cann't redirect by specifying each and every link . change is only domain name . if some clicks on sitea.com/whateverispage then he/she should redirect  to siteb.com/whateverispage

www.sitea.com/productinfo -->www.siteb.info/productinfo

any idea to how yo get this result , this is somehow similar to wildcard in SQl and PHP

Body:
please try this

RewriteEngine on
RewriteCond %{HTTP_HOST} ^sitea.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.sitea.com [NC]
RewriteRule ^(.*)$ http://siteb.com/$1 [L,R=301,NC]

hope it will work for you


问:
Issue in getting Current Location with GPS_PROVIDER and NETWORK_PROVIDER
I trying to get current location in my android application. But, every time I am getting my Location as null. I have done as below :

```<code>private void getLocation() {
    try {
        if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Constant.displayLogE(">> PErmission >> ", ">> not granted");
            return;
        } else {
            mLocationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            boolean isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            boolean isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    if (mLocationManager != null) {

                        mLocation = mLocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (mLocation != null) {
                            mCurrentLatitude = mLocation.getLatitude();
                            mCurrentLongitude = mLocation.getLongitude();
                            loadFilterListData();
                        }
                    }
                } else if (isGPSEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                0,
                                0, this);
                        if (mLocationManager != null) {
                            mLocation = mLocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mCurrentLatitude = mLocation.getLatitude();
                                mCurrentLongitude = mLocation.getLongitude();
                                loadFilterListData();
                            }
                        }
                    }
                }
                if (mLocation == null) {
                    Constant.displayToast(mContext, "Location not fetched. Please, try again.");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
</code>```

I don't know the solution for this as i am checking for both NETWORK_PROVIDER as well as GPS_PROVIDER. But, getting mLocation as null every time.

I have given necessary permissions in my Manifest file also.

What might be the issue ?

Thanks.

答:
Try GoogleApiClient to get user Current Location

Sample Code:

First you need to build a connection to googleApiclient

```<code>private synchronized void buildGoogleApiClient(){
    mGoogleApiClient = new GoogleApiClient.Builder(YourApplication.getContext())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}
</code>```

Ask for Permission for Android 6.0 and above version

```<code>public void checkLocationPermission(){
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
        // You don't have the permission you need to request it
        ActivityCompat.requestPermissions(this, Manifest.permission.ACCESS_FINE_LOCATION), REQ_CODE);
    }else{
        // You have the permission.
        requestLocationAccess();
    }
}
</code>```

Then implement onRequestPermissionResult to check that user granted permission or not

```<code> @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {

            case REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.

                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    requestLocationAccess();
                } else {

                        Snackbar.make(findViewById(android.R.id.content), "Please Allow to access to your Location",
                                Snackbar.LENGTH_LONG).setAction("Allow",
                                new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent();
                                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                                        intent.setData(Uri.parse("package:" + getPackageName()));

                                        startActivity(intent);

                                    }
                                }).show();

                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
</code>```

Create method requestLocationAccess where you will access location

```<code>  public void requestLocationAccess(){
        LocationRequest mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval((long) (LocationHelper.UPDATE_INTERVAL_IN_MILLISECONDS*1.1));
        mLocationRequest.setFastestInterval(LocationHelper.UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        final LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true); //this is the key ingredient
        com.google.android.gms.common.api.PendingResult<LocationSettingsResult> result =
                    LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>(){
            @Override
            public void onResult(@NonNull LocationSettingsResult result){
                if(requester != null){
                    final Status resultStatus = result.getStatus();
                    switch(resultStatus.getStatusCode()){
                        case LocationSettingsStatusCodes.SUCCESS:
                            PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                                        googleApiClient, locationRequest, YourActivity.this);

                            break;
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            // Location settings are not satisfied. But could be fixed by showing the user a dialog.
ActivityCompat.requestPermissions(YourActivity.this, new String[]{ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
                            try{
                                resultStatus.startResolutionForResult(this, REQUEST_LOCATION);
                                break;
                            }catch(IntentSender.SendIntentException ignored){}
                        }
                    }
                }
            }
        });
    }
</code>```

Then implement GoogleApliClient callback onConnected where you can get user location simply

```<code> @Override
    public void onConnected(@Nullable Bundle bundle) {

        if (ContextCompat
                .checkSelfPermission(this,
                        ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
            location = LocationServices.FusedLocationApi.getLastLocation(
                    googleApiClient);

        }
    }
</code>```

Body:
I trying to get current location in my android application. But, every time I am getting my Location as null. I have done as below :

private void getLocation() {
    try {
        if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Constant.displayLogE(">> PErmission >> ", ">> not granted");
            return;
        } else {
            mLocationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            boolean isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            boolean isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    if (mLocationManager != null) {

                        mLocation = mLocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (mLocation != null) {
                            mCurrentLatitude = mLocation.getLatitude();
                            mCurrentLongitude = mLocation.getLongitude();
                            loadFilterListData();
                        }
                    }
                } else if (isGPSEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                0,
                                0, this);
                        if (mLocationManager != null) {
                            mLocation = mLocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mCurrentLatitude = mLocation.getLatitude();
                                mCurrentLongitude = mLocation.getLongitude();
                                loadFilterListData();
                            }
                        }
                    }
                }
                if (mLocation == null) {
                    Constant.displayToast(mContext, "Location not fetched. Please, try again.");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

I don't know the solution for this as i am checking for both NETWORK_PROVIDER as well as GPS_PROVIDER. But, getting mLocation as null every time.

I have given necessary permissions in my Manifest file also.

What might be the issue ?

Thanks.

Body:
Try GoogleApiClient to get user Current Location

Sample Code:

First you need to build a connection to googleApiclient

private synchronized void buildGoogleApiClient(){
    mGoogleApiClient = new GoogleApiClient.Builder(YourApplication.getContext())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

Ask for Permission for Android 6.0 and above version

public void checkLocationPermission(){
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
        // You don't have the permission you need to request it
        ActivityCompat.requestPermissions(this, Manifest.permission.ACCESS_FINE_LOCATION), REQ_CODE);
    }else{
        // You have the permission.
        requestLocationAccess();
    }
}

Then implement onRequestPermissionResult to check that user granted permission or not

 @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {

            case REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.

                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    requestLocationAccess();
                } else {

                        Snackbar.make(findViewById(android.R.id.content), "Please Allow to access to your Location",
                                Snackbar.LENGTH_LONG).setAction("Allow",
                                new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent();
                                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                                        intent.setData(Uri.parse("package:" + getPackageName()));

                                        startActivity(intent);

                                    }
                                }).show();

                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

Create method requestLocationAccess where you will access location

  public void requestLocationAccess(){
        LocationRequest mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval((long) (LocationHelper.UPDATE_INTERVAL_IN_MILLISECONDS*1.1));
        mLocationRequest.setFastestInterval(LocationHelper.UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        final LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true); //this is the key ingredient
        com.google.android.gms.common.api.PendingResult<LocationSettingsResult> result =
                    LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>(){
            @Override
            public void onResult(@NonNull LocationSettingsResult result){
                if(requester != null){
                    final Status resultStatus = result.getStatus();
                    switch(resultStatus.getStatusCode()){
                        case LocationSettingsStatusCodes.SUCCESS:
                            PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                                        googleApiClient, locationRequest, YourActivity.this);

                            break;
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            // Location settings are not satisfied. But could be fixed by showing the user a dialog.
ActivityCompat.requestPermissions(YourActivity.this, new String[]{ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
                            try{
                                resultStatus.startResolutionForResult(this, REQUEST_LOCATION);
                                break;
                            }catch(IntentSender.SendIntentException ignored){}
                        }
                    }
                }
            }
        });
    }

Then implement GoogleApliClient callback onConnected where you can get user location simply

 @Override
    public void onConnected(@Nullable Bundle bundle) {

        if (ContextCompat
                .checkSelfPermission(this,
                        ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
            location = LocationServices.FusedLocationApi.getLastLocation(
                    googleApiClient);

        }
    }


问:
How to select textbox values in windows form
I've set textbox as multiline, and now whenever I mouse click on muliple items of that textbox, it is shown selected. May I know how can I do this?</p>

答: Since I'm seeing the words select and item, I think maybe you are wanting to use a listview (set to detail view) instead of a textbox.  It would allow you to have items on separate lines and be able to select them by clicking on them.</p>