问:
How to reduce sensitivity of android ScaleGestureDetector.SimpleOnScaleGestureListener
I have a custom SwipeRefreshLayout that has a custom GridView inside it. I want to change the column number of that GridView based on pinch/zoom gesture. I have successfully implemented it. The problem is, the scale is too sensitive.

For example, i have column number 3-5. It is easy to scale to 3 or 5, but to make it 4 is hard, since the scale itself is too sensitive.

Here is my custom SwipeRefreshLayout class

```<code>/**
 * This class contains fix from http://stackoverflow.com/questions/23989910/horizontalscrollview-inside-swiperefreshlayout
 */
public class CustomSwipeRefreshLayout extends SwipeRefreshLayout {

    private int mTouchSlop;
    private float mPrevX;
    private ScaleGestureDetector mScaleGestureDetector;
    private ScaleListener mScaleListener;

    public CustomSwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    public void setScaleListener(Context context, ScaleListener scaleListener) {
        this.mScaleListener = scaleListener;
        mScaleGestureDetector = new ScaleGestureDetector(context, new MyOnScaleGestureListener());
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (mScaleGestureDetector != null) {
            mScaleGestureDetector.onTouchEvent(event);
        }

        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_POINTER_DOWN:
                setEnabled(false);
                if (mScaleListener != null) {
                    mScaleListener.onTwoFingerStart();
                }
                break;
            case MotionEvent.ACTION_POINTER_UP:
                setEnabled(true);
                mPrevX = MotionEvent.obtain(event).getX();
                if (mScaleListener != null) {
                    mScaleListener.onTwoFingerEnd();
                }
                break;
            case MotionEvent.ACTION_DOWN:
                mPrevX = MotionEvent.obtain(event).getX();
                break;

            case MotionEvent.ACTION_MOVE:
                final float eventX = event.getX();
                float xDiff = Math.abs(eventX - mPrevX);

                if (xDiff > mTouchSlop) {
                    return false;
                }
        }

        return super.onInterceptTouchEvent(event);
    }

    class MyOnScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

        private static final String TAG = "MyOnScaleGestureListene";

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            if (mScaleListener != null) {
                // Too sensitive, must change to other approach
                float scaleFactor = detector.getScaleFactor();
                Log.d(TAG, "onScale: " + scaleFactor);
                if (scaleFactor > 1F) {
                    mScaleListener.onScaleUp(scaleFactor);
                } else if (scaleFactor < 1F) {
                    mScaleListener.onScaleDown(scaleFactor);
                } else {
                    // no scale
                }
            }
            return true;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
        }
    }

    public interface ScaleListener {
        void onTwoFingersStart();

        void onTwoFingersEnd();

        void onScaleUp(float scaleFactor);

        void onScaleDown(float scaleFactor);
    }
}
</code>```

Is there any way to reduce the sensitivity of ScaleGestureDetector.SimpleOnScaleGestureListener? If there is no way, is there any alternatives to solve it?

Here is a short video that showed the problem
https://www.youtube.com/watch?v=0MItDNZ_o4c

答:
I am able to solve the problem to meet my requirement. @azizbekian's answer was not really meet my requirement because spanDelta always resets if my fingers too slow and if my fingers too fast, it can scale, but still hard to get 4 columns. But from his code example, i am able to create a workaround.

I just need to save initial scale distance(span) using detector.getCurrentSpan()

```<code>@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
    mInitialDistance = detector.getCurrentSpan();
    return true;
}
</code>```

And then compare it directly with detector.getCurrentSpan() every time onScale() called. Then reset initial distance with mInitialDistance = detector.getCurrentSpan(); if scale occurred.

```<code>@Override
public boolean onScale(ScaleGestureDetector detector) {
    if (gestureTolerance(detector)) {
        if (mScaleListener != null) {
            float scaleFactor = detector.getScaleFactor();
            if (scaleFactor > 1F) {
                mScaleListener.onScaleUp(scaleFactor);
                mInitialDistance = detector.getCurrentSpan();
            } else if (scaleFactor < 1F) {
                mScaleListener.onScaleDown(scaleFactor);
                mInitialDistance = detector.getCurrentSpan();
            }
        }
    }
    return true;
}

private boolean gestureTolerance(@NonNull ScaleGestureDetector detector) {
    final float currentDistance = detector.getCurrentSpan();
    final float distanceDelta = Math.abs(mInitialDistance - currentDistance);
    return distanceDelta > mScaleTriggerDistance;
}
</code>```

Here is the complete code of my custom SwipeRefreshLayout

```<code>public class MyCustomSwipeRefreshLayout extends SwipeRefreshLayout {

    private static final String TAG = "OneTouchRefreshFreeSwip";
    private static final float DEFAULT_SCALE_TRIGGER_DISTANCE = 48;// in dp
    private int mTouchSlop;
    private float mPrevX;

    private ScaleGestureDetector mScaleGestureDetector;
    private ScaleListener mScaleListener;

    private float mScaleTriggerDistance;
    private float mInitialDistance;

    public MyCustomSwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    public void setScaleListener(Context context, ScaleListener scaleListener) {
        this.mScaleListener = scaleListener;
        mScaleGestureDetector = new ScaleGestureDetector(context, new MyOnScaleGestureListener());
        mScaleTriggerDistance = Util.dp2px(DEFAULT_SCALE_TRIGGER_DISTANCE, context);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (mScaleGestureDetector != null) {
            mScaleGestureDetector.onTouchEvent(event);
        }

        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_POINTER_DOWN:
                setEnabled(false);
                if (mScaleListener != null) {
                    mScaleListener.onTwoFingersStart();
                }
                break;
            case MotionEvent.ACTION_POINTER_UP:
                if (mScaleListener != null) {
                    mScaleListener.onTwoFingersEnd();
                }
                mPrevX = MotionEvent.obtain(event).getX();
                setEnabled(true);
                return true;
            case MotionEvent.ACTION_DOWN:
                mPrevX = MotionEvent.obtain(event).getX();
                break;

            case MotionEvent.ACTION_MOVE:
                final float eventX = event.getX();
                float xDiff = Math.abs(eventX - mPrevX);

                if (xDiff > mTouchSlop) {
                    return false;
                }
        }

        return super.onInterceptTouchEvent(event);
    }

    private boolean gestureTolerance(@NonNull ScaleGestureDetector detector) {
        final float currentDistance = detector.getCurrentSpan();
        final float distanceDelta = Math.abs(mInitialDistance - currentDistance);
        return distanceDelta > mScaleTriggerDistance;
    }

    class MyOnScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            if (gestureTolerance(detector)) {
                if (mScaleListener != null) {
                    float scaleFactor = detector.getScaleFactor();
                    if (scaleFactor > 1F) {
                        mScaleListener.onScaleUp(scaleFactor);
                        mInitialDistance = detector.getCurrentSpan();
                    } else if (scaleFactor < 1F) {
                        mScaleListener.onScaleDown(scaleFactor);
                        mInitialDistance = detector.getCurrentSpan();
                    }
                }
            }
            return true;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            mInitialDistance = detector.getCurrentSpan();
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
        }
    }

    public interface ScaleListener {
        void onTwoFingersStart();

        void onTwoFingersEnd();

        void onScaleUp(float scaleFactor);

        void onScaleDown(float scaleFactor);
    }
}
</code>```

Body:
I have a custom SwipeRefreshLayout that has a custom GridView inside it. I want to change the column number of that GridView based on pinch/zoom gesture. I have successfully implemented it. The problem is, the scale is too sensitive.

For example, i have column number 3-5. It is easy to scale to 3 or 5, but to make it 4 is hard, since the scale itself is too sensitive.

Here is my custom SwipeRefreshLayout class

/**
 * This class contains fix from http://stackoverflow.com/questions/23989910/horizontalscrollview-inside-swiperefreshlayout
 */
public class CustomSwipeRefreshLayout extends SwipeRefreshLayout {

    private int mTouchSlop;
    private float mPrevX;
    private ScaleGestureDetector mScaleGestureDetector;
    private ScaleListener mScaleListener;

    public CustomSwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    public void setScaleListener(Context context, ScaleListener scaleListener) {
        this.mScaleListener = scaleListener;
        mScaleGestureDetector = new ScaleGestureDetector(context, new MyOnScaleGestureListener());
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (mScaleGestureDetector != null) {
            mScaleGestureDetector.onTouchEvent(event);
        }

        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_POINTER_DOWN:
                setEnabled(false);
                if (mScaleListener != null) {
                    mScaleListener.onTwoFingerStart();
                }
                break;
            case MotionEvent.ACTION_POINTER_UP:
                setEnabled(true);
                mPrevX = MotionEvent.obtain(event).getX();
                if (mScaleListener != null) {
                    mScaleListener.onTwoFingerEnd();
                }
                break;
            case MotionEvent.ACTION_DOWN:
                mPrevX = MotionEvent.obtain(event).getX();
                break;

            case MotionEvent.ACTION_MOVE:
                final float eventX = event.getX();
                float xDiff = Math.abs(eventX - mPrevX);

                if (xDiff > mTouchSlop) {
                    return false;
                }
        }

        return super.onInterceptTouchEvent(event);
    }

    class MyOnScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

        private static final String TAG = "MyOnScaleGestureListene";

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            if (mScaleListener != null) {
                // Too sensitive, must change to other approach
                float scaleFactor = detector.getScaleFactor();
                Log.d(TAG, "onScale: " + scaleFactor);
                if (scaleFactor > 1F) {
                    mScaleListener.onScaleUp(scaleFactor);
                } else if (scaleFactor < 1F) {
                    mScaleListener.onScaleDown(scaleFactor);
                } else {
                    // no scale
                }
            }
            return true;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
        }
    }

    public interface ScaleListener {
        void onTwoFingersStart();

        void onTwoFingersEnd();

        void onScaleUp(float scaleFactor);

        void onScaleDown(float scaleFactor);
    }
}

Is there any way to reduce the sensitivity of ScaleGestureDetector.SimpleOnScaleGestureListener? If there is no way, is there any alternatives to solve it?

Here is a short video that showed the problem
https://www.youtube.com/watch?v=0MItDNZ_o4c

Body:
I am able to solve the problem to meet my requirement. @azizbekian's answer was not really meet my requirement because spanDelta always resets if my fingers too slow and if my fingers too fast, it can scale, but still hard to get 4 columns. But from his code example, i am able to create a workaround.

I just need to save initial scale distance(span) using detector.getCurrentSpan()

@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
    mInitialDistance = detector.getCurrentSpan();
    return true;
}

And then compare it directly with detector.getCurrentSpan() every time onScale() called. Then reset initial distance with mInitialDistance = detector.getCurrentSpan(); if scale occurred.

@Override
public boolean onScale(ScaleGestureDetector detector) {
    if (gestureTolerance(detector)) {
        if (mScaleListener != null) {
            float scaleFactor = detector.getScaleFactor();
            if (scaleFactor > 1F) {
                mScaleListener.onScaleUp(scaleFactor);
                mInitialDistance = detector.getCurrentSpan();
            } else if (scaleFactor < 1F) {
                mScaleListener.onScaleDown(scaleFactor);
                mInitialDistance = detector.getCurrentSpan();
            }
        }
    }
    return true;
}

private boolean gestureTolerance(@NonNull ScaleGestureDetector detector) {
    final float currentDistance = detector.getCurrentSpan();
    final float distanceDelta = Math.abs(mInitialDistance - currentDistance);
    return distanceDelta > mScaleTriggerDistance;
}

Here is the complete code of my custom SwipeRefreshLayout

public class MyCustomSwipeRefreshLayout extends SwipeRefreshLayout {

    private static final String TAG = "OneTouchRefreshFreeSwip";
    private static final float DEFAULT_SCALE_TRIGGER_DISTANCE = 48;// in dp
    private int mTouchSlop;
    private float mPrevX;

    private ScaleGestureDetector mScaleGestureDetector;
    private ScaleListener mScaleListener;

    private float mScaleTriggerDistance;
    private float mInitialDistance;

    public MyCustomSwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    public void setScaleListener(Context context, ScaleListener scaleListener) {
        this.mScaleListener = scaleListener;
        mScaleGestureDetector = new ScaleGestureDetector(context, new MyOnScaleGestureListener());
        mScaleTriggerDistance = Util.dp2px(DEFAULT_SCALE_TRIGGER_DISTANCE, context);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (mScaleGestureDetector != null) {
            mScaleGestureDetector.onTouchEvent(event);
        }

        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_POINTER_DOWN:
                setEnabled(false);
                if (mScaleListener != null) {
                    mScaleListener.onTwoFingersStart();
                }
                break;
            case MotionEvent.ACTION_POINTER_UP:
                if (mScaleListener != null) {
                    mScaleListener.onTwoFingersEnd();
                }
                mPrevX = MotionEvent.obtain(event).getX();
                setEnabled(true);
                return true;
            case MotionEvent.ACTION_DOWN:
                mPrevX = MotionEvent.obtain(event).getX();
                break;

            case MotionEvent.ACTION_MOVE:
                final float eventX = event.getX();
                float xDiff = Math.abs(eventX - mPrevX);

                if (xDiff > mTouchSlop) {
                    return false;
                }
        }

        return super.onInterceptTouchEvent(event);
    }

    private boolean gestureTolerance(@NonNull ScaleGestureDetector detector) {
        final float currentDistance = detector.getCurrentSpan();
        final float distanceDelta = Math.abs(mInitialDistance - currentDistance);
        return distanceDelta > mScaleTriggerDistance;
    }

    class MyOnScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            if (gestureTolerance(detector)) {
                if (mScaleListener != null) {
                    float scaleFactor = detector.getScaleFactor();
                    if (scaleFactor > 1F) {
                        mScaleListener.onScaleUp(scaleFactor);
                        mInitialDistance = detector.getCurrentSpan();
                    } else if (scaleFactor < 1F) {
                        mScaleListener.onScaleDown(scaleFactor);
                        mInitialDistance = detector.getCurrentSpan();
                    }
                }
            }
            return true;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            mInitialDistance = detector.getCurrentSpan();
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
        }
    }

    public interface ScaleListener {
        void onTwoFingersStart();

        void onTwoFingersEnd();

        void onScaleUp(float scaleFactor);

        void onScaleDown(float scaleFactor);
    }
}


来源: stackexchange

问:
Want VBA in excel to read very large CSV and create output file of a small subset of the CSV
I have a csv file of 1.2 million records of text.  The alphanumeric fields are wrapped in quotation marks, the date/time or numeric fields are not.

For example
"Fred","Smith",01/07/1967,2,"7, The High Street","Anytown","Anycounty","LS1 7AA"

What I want do is write some VBA in Excel (more or less the only tool available to me that I am reasonably proficient in the use of) that reads the CSV record by record, performs a check (as it happens on the last field, the post code) and then outputs a small subset of the 1.2m records to a new output file.

I understand how to open the two files, read the record, do what I need to do with the data and write it out (I will just output the input record with a prefix denoting an exception type)

What I don't know is how to parse the CSV in VBA properly.  I can't do a simple text scan and search for commas as the text sometimes has commas in (hence why the text fields are text delimited)

Is there a fantastic command that would let me quicky get the data from the nth field in my record?

What I want is
    s_work = field(s_input_record,5) where 5 is the field number in my CSV....

Many thanks,
C

答:
Look at the Input # statement in the Excel help

Sample usage would be:

```<code>Input #fnInput, s_Forename, s_Surname, dt_DOB, i_Something, s_Street, s_Town, s_County, s_Postcode
</code>```

and then use the Write # statement to write matching records out again

The only issue might be that the date format in the output will end up as #1967-07-01# but this format is unambiguous unlike 01/07/1967 which would represent 1st July in the UK and 7th January in the US. If you need to preserve the formatting of the date then write it out as a string:

```<code>s_DOB = Format(dt_DOB, "dd/mm/yyyy")
</code>```

OwnerDisplayName: C J

LastEditorDisplayName: eJames

ContentLicense: CC BY-SA 2.5

Body:
Look at the Input # statement in the Excel help

Sample usage would be:

Input #fnInput, s_Forename, s_Surname, dt_DOB, i_Something, s_Street, s_Town, s_County, s_Postcode

and then use the Write # statement to write matching records out again

The only issue might be that the date format in the output will end up as #1967-07-01# but this format is unambiguous unlike 01/07/1967 which would represent 1st July in the UK and 7th January in the US. If you need to preserve the formatting of the date then write it out as a string:

s_DOB = Format(dt_DOB, "dd/mm/yyyy")

OwnerDisplayName: barrowc


问:
How to create a small dataset to test my CNN?
I recently implemented a CNN (using Tensorflow Python API) and I tested it with MNIST dataset.

Now i would like to test it with bigger images (like 100x100p pixels).

To do so I am using scikit-learn.feature_extraction.image.extract_patches_2d like this just to get N (here equals 10) images :

```<code>from sklearn.feature_extraction import image
import numpy as np
from PIL import Image

HowManyPatches = 10

img = Image.open('./bulldog.jpeg')
imgarray = np.array(img)

patches = image.extract_patches_2d(imgarray, (100, 100), HowManyPatches)

for i in range(HowManyPatches):
    imgpatch = Image.fromarray(patches[i], 'RGB')
    name = 'patch_' + str(i) + '.jpeg'
    imgpatch.save(name)
</code>```

So now i would like to put a (random since it is just to test the training time) label on every single patch i get.

I noticed that MNIST dataset is extracted from this kind of files : t10k-images.idx3-ubyte which seem to be an unknown type. So I would like to know how, once i succesfully put a label on my images, can i create this kind of files ?

To sum up the two main questions are :
How ta put a label on my images ?
How to get a dataset that i can use like MNIST dataset ? Or maybe there is a simpler way of creating a dataset differently from MNIST dataset ?

Thank you all !

答:
If you just want to test training time and don't care about actual classification, you can use this:

```<code>x_pattern = np.array([[1 for i in range(100)] for i in range(100)])
x_train = np.array([x_pattern for i in range(100)])
y_train = np.array([1 if i % 2 == 0 else 2 for i in range(100)])
</code>```

This will give you 100 samples of all white 100x100 images and alternating labels of 1, 0.

And if you already have 100x100 patches, you can just set range in the y_train line above to equal the number of patches you have.

ContentLicense: CC BY-SA 3.0

Body:
I recently implemented a CNN (using Tensorflow Python API) and I tested it with MNIST dataset.

Now i would like to test it with bigger images (like 100x100p pixels).

To do so I am using scikit-learn.feature_extraction.image.extract_patches_2d like this just to get N (here equals 10) images :

from sklearn.feature_extraction import image
import numpy as np
from PIL import Image

HowManyPatches = 10

img = Image.open('./bulldog.jpeg')
imgarray = np.array(img)

patches = image.extract_patches_2d(imgarray, (100, 100), HowManyPatches)

for i in range(HowManyPatches):
    imgpatch = Image.fromarray(patches[i], 'RGB')
    name = 'patch_' + str(i) + '.jpeg'
    imgpatch.save(name)

So now i would like to put a (random since it is just to test the training time) label on every single patch i get.

I noticed that MNIST dataset is extracted from this kind of files : t10k-images.idx3-ubyte which seem to be an unknown type. So I would like to know how, once i succesfully put a label on my images, can i create this kind of files ?

To sum up the two main questions are :
How ta put a label on my images ?
How to get a dataset that i can use like MNIST dataset ? Or maybe there is a simpler way of creating a dataset differently from MNIST dataset ?

Thank you all !

Body:
If you just want to test training time and don't care about actual classification, you can use this:

x_pattern = np.array([[1 for i in range(100)] for i in range(100)])
x_train = np.array([x_pattern for i in range(100)])
y_train = np.array([1 if i % 2 == 0 else 2 for i in range(100)])

This will give you 100 samples of all white 100x100 images and alternating labels of 1, 0.

And if you already have 100x100 patches, you can just set range in the y_train line above to equal the number of patches you have.


问:
awk BEGIN compare multiple variables in if statement
I'm trying to compare some floats/version numbers in bash for which i'm using awk BEGIN with if statement.
I was able to do comparison and get proper output when i'm using 2 variables.
But in case of 3 variables i'm not able to get the output.

Objective:

What i want to achieve is if the input is between two values 4.8.0 & 4.10.0, ( i.e., 4.8.0 <= inp < 4.10.0 ) then output 1 else output 0.

CODE Block

Below is what i wrote:

```<code>inp=4.9.4
out=`awk -v n1=$inp -v n2=4.8.0 -v n3=4.10.0 \
  'BEGIN {if (n1<n2) printf (0); else if (n1<n3) printf (1); else printf (0);}'`
</code>```

another way i tried is comparing with multiple conditions

```<code>inp=4.9.4
out=`awk -v n1=$inp -v n2=4.8.0 -v n3=4.10.0 \
  'BEGIN {if (n1>n2 && n1<n3) printf (1); else printf (0);}'`
</code>```

Queries:
Please help on how can i achieve same using awk BEGIN if?
Also if there is any other way by which i can compare float inputs?

答:
Problem is not the "<" itself but the string compare element
4.9 is bigger (string point of view) than 4.10. in this case you must compare 4.09 to 4.10
so transform the input to be at the same order of comparaison and this depend on your context of versionning

```<code>inp=4.9.0
out = $(
 awk -v nt=${inp} -v nl=4.8.0 -v nh=4.10.0 \
  '# use a function to compare dotted value
    function lt( Arg1, Arg2) {
      # split version into elements
      S = ES1 = split( Arg1, E1, /[.]/)
      ES2 = split( Arg2, E2, /[.]/)
      # take longest serie
      if( ES1 < ES2) S = ES2
      # reinit lower and bigger flag
      l=b=0

      # test if bigger, smaller or equivalent
      for( i=1;i <= S && ! ( l || b ) ; i++) {
         if( E1[i] < E2[i] ) l++
          else if ( E1[i] > E2[i] ) b++
         }
      # return 1 if smaller
      return ( l )
      }

   # is between
   BEGIN { print ( lt(nl, nt) && lt( nt, nh)) }
   '
   )
</code>```

note:

the function splitting the dotted element, number are compare as number when possible

longer or shorter version number are also compare (empty equivalement element are consider as 0 )

Body:
I'm trying to compare some floats/version numbers in bash for which i'm using awk BEGIN with if statement.
I was able to do comparison and get proper output when i'm using 2 variables.
But in case of 3 variables i'm not able to get the output.

Objective:

What i want to achieve is if the input is between two values 4.8.0 & 4.10.0, ( i.e., 4.8.0 <= inp < 4.10.0 ) then output 1 else output 0.

CODE Block

Below is what i wrote:

inp=4.9.4
out=`awk -v n1=$inp -v n2=4.8.0 -v n3=4.10.0 \
  'BEGIN {if (n1<n2) printf (0); else if (n1<n3) printf (1); else printf (0);}'`

another way i tried is comparing with multiple conditions

inp=4.9.4
out=`awk -v n1=$inp -v n2=4.8.0 -v n3=4.10.0 \
  'BEGIN {if (n1>n2 && n1<n3) printf (1); else printf (0);}'`

Queries:
Please help on how can i achieve same using awk BEGIN if?
Also if there is any other way by which i can compare float inputs?

Body:
Problem is not the "<" itself but the string compare element
4.9 is bigger (string point of view) than 4.10. in this case you must compare 4.09 to 4.10
so transform the input to be at the same order of comparaison and this depend on your context of versionning

inp=4.9.0
out = $(
 awk -v nt=${inp} -v nl=4.8.0 -v nh=4.10.0 \
  '# use a function to compare dotted value
    function lt( Arg1, Arg2) {
      # split version into elements
      S = ES1 = split( Arg1, E1, /[.]/)
      ES2 = split( Arg2, E2, /[.]/)
      # take longest serie
      if( ES1 < ES2) S = ES2
      # reinit lower and bigger flag
      l=b=0

      # test if bigger, smaller or equivalent
      for( i=1;i <= S && ! ( l || b ) ; i++) {
         if( E1[i] < E2[i] ) l++
          else if ( E1[i] > E2[i] ) b++
         }
      # return 1 if smaller
      return ( l )
      }

   # is between
   BEGIN { print ( lt(nl, nt) && lt( nt, nh)) }
   '
   )

note:

the function splitting the dotted element, number are compare as number when possible

longer or shorter version number are also compare (empty equivalement element are consider as 0 )


问:
Web service using C# PureMVC framework
I am developing a web service in C# using the C# port of the PureMVC framework. The web service uses nHibernate to connect to and manipulate the database. I have tried to find information about how PureMVC should be initialized when used to manage a web service or if I call a seperate page to invoke PureMVC and have it load the .asmx file directly and pass it the post data. I'm somewhat lost when it comes to the load order so if anyone could help me out with this it would be very appeciated.

Gary

答:
I notice that WCF has a messaging system that appears to run asynchronously. This seems to much better fit the asynchronous nature of Proxies in PureMVC and indicates that I would access the web services as normal where I then instantiate PureMVC and use it to encapsulate my data and commands, I can then query nHibernate and notify the rest of my system when I get a response. This should allow me to create return data objects and send them back through the web services.

If anything about that sounds crazy, please let me know before I invest time implementing it :D

Thanks guys, and thanks to CrazyDart for his input.

Title: Web service using C# PureMVC framework


问:
Adding a small photo/image to a large graph in Matplotlib/Python
I have a large graph that I am generating in matplotlib. I'd like to add a number of icons to this graph at certain (x,y) coordinates. I am wondering if there is any way to do that in matplotlib

Thank you

答:
Many years late but for future reference.

I found that adding an AnnotationBbox with an OffsetImage in it, did the trick for me. e.g.

```<code>#!/usr/bin/env python
import matplotlib
matplotlib.use('WXAgg')
import matplotlib.pyplot as plt
from matplotlib.offsetbox import (OffsetImage,AnnotationBbox)
from matplotlib.cbook import get_sample_data
# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0.1, 0, 0, 0)  # explode a slice if required
fig, ax = plt.subplots()
ax.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True)
#Full path name to your image
fn = get_sample_data("/home/rolf/bandwidth/bandwidth.png", asfileobj=False)
arr_img = plt.imread(fn, format='png')

imagebox = OffsetImage(arr_img, zoom=1.2)
imagebox.image.axes = ax
xy = [0.75, 0.95]
ab = AnnotationBbox(imagebox, xy,
                    xybox=(120., -10.),
                    xycoords='data',
                    boxcoords="offset points",
                    pad=0.5,
                    )
ax.add_artist(ab)

# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.show()
</code>```

Move the image about within the plot with xy and xybox values.

Further reading that may be useful:

http://matplotlib.org/examples/pylab_examples/demo_annotation_box.html
https://developer.ibm.com/clouddataservices/2016/10/06/your-own-weather-forecast-in-a-python-notebook/

Body:
Many years late but for future reference.

I found that adding an AnnotationBbox with an OffsetImage in it, did the trick for me. e.g.

#!/usr/bin/env python
import matplotlib
matplotlib.use('WXAgg')
import matplotlib.pyplot as plt
from matplotlib.offsetbox import (OffsetImage,AnnotationBbox)
from matplotlib.cbook import get_sample_data
# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0.1, 0, 0, 0)  # explode a slice if required
fig, ax = plt.subplots()
ax.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True)
#Full path name to your image
fn = get_sample_data("/home/rolf/bandwidth/bandwidth.png", asfileobj=False)
arr_img = plt.imread(fn, format='png')

imagebox = OffsetImage(arr_img, zoom=1.2)
imagebox.image.axes = ax
xy = [0.75, 0.95]
ab = AnnotationBbox(imagebox, xy,
                    xybox=(120., -10.),
                    xycoords='data',
                    boxcoords="offset points",
                    pad=0.5,
                    )
ax.add_artist(ab)

# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.show()

Move the image about within the plot with xy and xybox values.

Further reading that may be useful:

http://matplotlib.org/examples/pylab_examples/demo_annotation_box.html
https://developer.ibm.com/clouddataservices/2016/10/06/your-own-weather-forecast-in-a-python-notebook/


问:
React-native build failed with undefined symbol _RCTInjectedAssertFunction
I build my project with the following tools.

```<code>react-native-cli: 2.0.1
react-native: 0.41.2
XCode Version 8.2.1 (8C1002)
</code>```

But I got an error.

```<code>Undefined symbols for architecture arm64:
  "_RCTInjectedAssertFunction", referenced from:
      -[RCTWebSocketExecutor executeJSCall:method:arguments:callback:] in libRCTWebSocketDebugger.a(RCTWebSocketExecutor.o)
      -[RCTWebSocketExecutor dealloc] in libRCTWebSocketDebugger.a(RCTWebSocketExecutor.o)
  "__RCTLogFormat", referenced from:
      -[RCTWebSocketExecutor initWithURL:] in libRCTWebSocketDebugger.a(RCTWebSocketExecutor.o)
      -[RCTWebSocketExecutor webSocket:didFailWithError:] in libRCTWebSocketDebugger.a(RCTWebSocketExecutor.o)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

What am I doing wrong? Something in the build settings?
enter image description here

答:
Try this, delete ios, android and node_modules folder from the project directory.
Then run,
 npm install react-native upgrade react-native link

This works for me.

react-native link is not supported anymore, instead, you can use npx react-native-asset

Body:
I build my project with the following tools.

react-native-cli: 2.0.1
react-native: 0.41.2
XCode Version 8.2.1 (8C1002)

But I got an error.

Undefined symbols for architecture arm64:
  "_RCTInjectedAssertFunction", referenced from:
      -[RCTWebSocketExecutor executeJSCall:method:arguments:callback:] in libRCTWebSocketDebugger.a(RCTWebSocketExecutor.o)
      -[RCTWebSocketExecutor dealloc] in libRCTWebSocketDebugger.a(RCTWebSocketExecutor.o)
  "__RCTLogFormat", referenced from:
      -[RCTWebSocketExecutor initWithURL:] in libRCTWebSocketDebugger.a(RCTWebSocketExecutor.o)
      -[RCTWebSocketExecutor webSocket:didFailWithError:] in libRCTWebSocketDebugger.a(RCTWebSocketExecutor.o)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

What am I doing wrong? Something in the build settings?
enter image description here

ContentLicense: CC BY-SA 4.0


问:
REST in Unity (send messages from webserver to unity)
Is there a way to have a simple webserver send messages to Unity?

At the moment, we're doing a GET using UnityWebRequest.Get() in the update method. Here's the code:

```<code>// Update is called once per frame
void Update () {
    StartCoroutine(GetData());
}

IEnumerator GetData()
{
    UnityWebRequest uwr = UnityWebRequest.Get(url);
    yield return uwr.Send();

    if (uwr.isError)
    {
        Debug.Log(uwr.error);
    }else
    {
        Debug.Log((float.Parse(uwr.downloadHandler.text) / 100));
        fnumber = ((float.Parse(uwr.downloadHandler.text) / 100));
        transform.position.Set(oldX, fnumber, oldZ);
    }
}
</code>```

However, this throws this error:

CANNOT RESOLVE DESTINATION HOST

I found this bug-report, which states, it would have been fixed, which doesn't seem so.

So, is there a way to have the server send messages to Unity?

Thanks

答:
Try to use the WWW call instead the UnityWebRequest which is broken.
What version of unity are you using ?

Body:
Is there a way to have a simple webserver send messages to Unity?

At the moment, we're doing a GET using UnityWebRequest.Get() in the update method. Here's the code:

// Update is called once per frame
void Update () {
    StartCoroutine(GetData());
}

IEnumerator GetData()
{
    UnityWebRequest uwr = UnityWebRequest.Get(url);
    yield return uwr.Send();

    if (uwr.isError)
    {
        Debug.Log(uwr.error);
    }else
    {
        Debug.Log((float.Parse(uwr.downloadHandler.text) / 100));
        fnumber = ((float.Parse(uwr.downloadHandler.text) / 100));
        transform.position.Set(oldX, fnumber, oldZ);
    }
}

However, this throws this error:

CANNOT RESOLVE DESTINATION HOST

I found this bug-report, which states, it would have been fixed, which doesn't seem so.

So, is there a way to have the server send messages to Unity?

Thanks


问:
How can i test if the value from mySql query is greater or less that a certain value by (a given number)?
How can I get this query to return similar users that have a rating difference of a certain number (for example 0.5)

```<code>$sql =
        "
        SELECT y.rater_id
             , GROUP_CONCAT(y.rater_id) user_id
             , GROUP_CONCAT(y.video_id) likes
             , COUNT(*) total
          FROM rating x
          JOIN rating y
            ON y.video_id = x.video_id
           AND y.rater_id <> x.rater_id
           AND y.rate = x.rate
         WHERE x.rater_id = '$session_user_id'
         GROUP
            BY 'total'
            LIMIT 0 , 30;

        ";
</code>```

The whole point of this query is to return similar users with not much of a difference in rating a certain video (or item).

答:
I think it would be enough to replace this

```<code>AND y.rate = x.rate
</code>```

with this

```<code>AND y.rate between (x.rate - 0.5) and (x.rate + 0.5)
</code>```

Body:
How can I get this query to return similar users that have a rating difference of a certain number (for example 0.5)

$sql =
        "
        SELECT y.rater_id
             , GROUP_CONCAT(y.rater_id) user_id
             , GROUP_CONCAT(y.video_id) likes
             , COUNT(*) total
          FROM rating x
          JOIN rating y
            ON y.video_id = x.video_id
           AND y.rater_id <> x.rater_id
           AND y.rate = x.rate
         WHERE x.rater_id = '$session_user_id'
         GROUP
            BY 'total'
            LIMIT 0 , 30;

        ";

The whole point of this query is to return similar users with not much of a difference in rating a certain video (or item).

Body:
I think it would be enough to replace this

AND y.rate = x.rate

with this

AND y.rate between (x.rate - 0.5) and (x.rate + 0.5)


问:
How to install icon pack on custom launcher?
I'm trying to install icon pack on my custom launcher, I've read this note How to install icon pack but I'm not able to understand how to use that class, here's what I done:</p>

```<code>IconPackManager ic = new IconPackManager();
HashMap<String, IconPackManager.IconPack> map = new HashMap<String, IconPackManager.IconPack>(ic.getAvailableIconPacks(false));
Iterator it = map.entrySet().iterator();
Drawable d = null;
String packName = null;
IconPackManager.IconPack packIcon = null;
    while (it.hasNext()) {
       Map.Entry pair = (Map.Entry)it.next();
       packName = (String)pair.getKey();
       packIcon = (IconPackManager.IconPack)pair.getValue();
       d = packIcon.getDrawableIconForPackage(packName, iconDrawable);
       setIcon(d);
    }
</code>```

答:
Solved with this:</p>

```<code>String packName = null;
IconPackManager.IconPack packIcon = null;

IconPackManager ic = new IconPackManager();
HashMap<String, IconPackManager.IconPack> map = ic.getAvailableIconPacks(true);
Iterator it = map.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();
            packName = (String)pair.getKey(); //Get icon pack name (app package)

            packIcon = (IconPackManager.IconPack)pair.getValue(); //Get icons

            if(packIcon.getDrawableIconForPackage("YourTargetPackageName", yourStandardIcon) != null) {

            //Your own method for set icon
            setIcon(packIcon.getDrawableIconForPackage("YourTargetPackageName", yourStandardIcon));

            }else{
                //Your own method for set icon
                setIcon(yourStandardIcon);
            }
        }
</code>```

Body:
I'm trying to install icon pack on my custom launcher, I've read this note How to install icon pack but I'm not able to understand how to use that class, here's what I done:

IconPackManager ic = new IconPackManager();
HashMap<String, IconPackManager.IconPack> map = new HashMap<String, IconPackManager.IconPack>(ic.getAvailableIconPacks(false));
Iterator it = map.entrySet().iterator();
Drawable d = null;
String packName = null;
IconPackManager.IconPack packIcon = null;
    while (it.hasNext()) {
       Map.Entry pair = (Map.Entry)it.next();
       packName = (String)pair.getKey();
       packIcon = (IconPackManager.IconPack)pair.getValue();
       d = packIcon.getDrawableIconForPackage(packName, iconDrawable);
       setIcon(d);
    }

Body:
Solved with this:

String packName = null;
IconPackManager.IconPack packIcon = null;

IconPackManager ic = new IconPackManager();
HashMap<String, IconPackManager.IconPack> map = ic.getAvailableIconPacks(true);
Iterator it = map.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();
            packName = (String)pair.getKey(); //Get icon pack name (app package)

            packIcon = (IconPackManager.IconPack)pair.getValue(); //Get icons

            if(packIcon.getDrawableIconForPackage("YourTargetPackageName", yourStandardIcon) != null) {

            //Your own method for set icon
            setIcon(packIcon.getDrawableIconForPackage("YourTargetPackageName", yourStandardIcon));

            }else{
                //Your own method for set icon
                setIcon(yourStandardIcon);
            }
        }


问:
How to code paypal ipn listener in laravel
I used laravel in my project. In my project using paypal for payment module. Paypal payment transactions successfully done. But i want to integrate ipn listener in laravel. I don't know how to integrate ipn listener in laravel controller.

Thanks advanced,
Saran

答:
Follow Bellow Few Step:

1)Install Laravel Application

2)Database Configuration

3)Install Required Packages

4)configuration paypal.php file

5)create route

6)create controller

7)create view file

Step 1 : Install Laravel Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

```
composer create-project --prefer-dist laravel/laravel blog
```

Step 2 : Database Configuration

In this step, we require to make database configuration, you have to add
 following details on your .env file.

1.Database Username

1.Database Password

1.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:
.env

```<code>DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
</code>```

Step 3 : Install Required Packages

We have required following 2 packages for integrate paypal payment in our laravel application.
add following two package in your composer.json file.

```<code>"guzzlehttp/guzzle": "~5.4",
"paypal/rest-api-sdk-php": "*",
</code>```

then after run following command in your terminal

```<code>php artisan vendor:publish
</code>```

after run this command, then after automatic create paypal.php file in your config/paypal.php path.

Step 4 : Configuration paypal.php file

```<code><?php

return array(
/** set your paypal credential **/
'client_id' =>'paypal client_id',
'secret' => 'paypal secret ID',
/**
* SDK configuration
*/
'settings' => array(
    /**
    * Available options 'sandbox' or 'live'
    */
    'mode' => 'sandbox',
    /**
    * Specify the max request time in seconds
    */
    'http.ConnectionTimeOut' => 1000,
    /**
    * Whether want to log to a file
    */
    'log.LogEnabled' => true,
    /**
    * Specify the file that want to write on
    */
    'log.FileName' => storage_path() . '/logs/paypal.log',
    /**
    * Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
    *
    * Logging is most verbose in the 'FINE' level and decreases as you
    * proceed towards ERROR
    */
    'log.LogLevel' => 'FINE'
    ),
);
</code>```

Step 5: Create Route

In this is step we need to create route for paypal payment. so open your routes/web.php file and add following route.
routes/web.php

```<code>Route::get('paywithpaypal', array('as' => 'addmoney.paywithpaypal','uses' => 'AddMoneyController@payWithPaypal',));
Route::post('paypal', array('as' => 'addmoney.paypal','uses' => 'AddMoneyController@postPaymentWithpaypal',));
Route::get('paypal', array('as' => 'payment.status','uses' => 'AddMoneyController@getPaymentStatus',));
</code>```

Step 6: Create Controller

In this point, now we should create new controller as AddMoneyController in this path app/Http/Controllers/AddMoneyController.php. this controller will manage layout and payment post request, So run bellow command for generate new controller:

```<code>php artisan make:controller AddMoneyController
</code>```

Ok, now put below content in controller file:

app/Http/Controllers/AddMoneyController.php

```<code><?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use URL;
use Session;
use Redirect;
use Input;

/** All Paypal Details class **/
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Transaction;

class AddMoneyController extends HomeController
{

    private $_api_context;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        /** setup PayPal api context **/
        $paypal_conf = \Config::get('paypal');
        $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
        $this->_api_context->setConfig($paypal_conf['settings']);
    }

    /**
     * Show the application paywith paypalpage.
     *
     * @return \Illuminate\Http\Response
     */
    public function payWithPaypal()
    {
        return view('paywithpaypal');
    }

    /**
     * Store a details of payment with paypal.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postPaymentWithpaypal(Request $request)
    {
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $item_1 = new Item();

        $item_1->setName('Item 1') /** item name **/
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setPrice($request->get('amount')); /** unit price **/

        $item_list = new ItemList();
        $item_list->setItems(array($item_1));

        $amount = new Amount();
        $amount->setCurrency('USD')
            ->setTotal($request->get('amount'));

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($item_list)
            ->setDescription('Your transaction description');

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::route('payment.status')) /** Specify return URL **/
            ->setCancelUrl(URL::route('payment.status'));

        $payment = new Payment();
        $payment->setIntent('Sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirect_urls)
            ->setTransactions(array($transaction));
            /** dd($payment->create($this->_api_context));exit; **/
        try {
            $payment->create($this->_api_context);
        } catch (\PayPal\Exception\PPConnectionException $ex) {
            if (\Config::get('app.debug')) {
                \Session::put('error','Connection timeout');
                return Redirect::route('addmoney.paywithpaypal');
                /** echo "Exception: " . $ex->getMessage() . PHP_EOL; **/
                /** $err_data = json_decode($ex->getData(), true); **/
                /** exit; **/
            } else {
                \Session::put('error','Some error occur, sorry for inconvenient');
                return Redirect::route('addmoney.paywithpaypal');
                /** die('Some error occur, sorry for inconvenient'); **/
            }
        }

        foreach($payment->getLinks() as $link) {
            if($link->getRel() == 'approval_url') {
                $redirect_url = $link->getHref();
                break;
            }
        }

        /** add payment ID to session **/
        Session::put('paypal_payment_id', $payment->getId());

        if(isset($redirect_url)) {
            /** redirect to paypal **/
            return Redirect::away($redirect_url);
        }

        \Session::put('error','Unknown error occurred');
        return Redirect::route('addmoney.paywithpaypal');
    }

    public function getPaymentStatus()
    {
        /** Get the payment ID before session clear **/
        $payment_id = Session::get('paypal_payment_id');
        /** clear the session payment ID **/
        Session::forget('paypal_payment_id');
        if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
            \Session::put('error','Payment failed');
            return Redirect::route('addmoney.paywithpaypal');
        }
        $payment = Payment::get($payment_id, $this->_api_context);
        /** PaymentExecution object includes information necessary **/
        /** to execute a PayPal account payment. **/
        /** The payer_id is added to the request query parameters **/
        /** when the user is redirected from paypal back to your site **/
        $execution = new PaymentExecution();
        $execution->setPayerId(Input::get('PayerID'));
        /**Execute the payment **/
        $result = $payment->execute($execution, $this->_api_context);
        /** dd($result);exit; /** DEBUG RESULT, remove it later **/
        if ($result->getState() == 'approved') {

            /** it's all right **/
            /** Here Write your database logic like that insert record or value in database if you want **/

            \Session::put('success','Payment success');
            return Redirect::route('addmoney.paywithpaypal');
        }
        \Session::put('error','Payment failed');

        return Redirect::route('addmoney.paywithpaypal');
    }
  }
</code>```

Step 7: Create View

In Last step, let's create paywithpaypal.blade.php(resources/views/paywithpaypal.blade.php) for layout and we will write design code here and also form for pay amount by paypal, So put following code:
resources/views/paywithpaypal.blade.php

```<code>@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                @if ($message = Session::get('success'))
                <div class="custom-alerts alert alert-success fade in">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('success');?>
                @endif

                @if ($message = Session::get('error'))
                <div class="custom-alerts alert alert-danger fade in">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('error');?>
                @endif
                <div class="panel-heading">Paywith Paypal</div>
                <div class="panel-body">
                    <form class="form-horizontal" method="POST" id="payment-form" role="form" action="{!! URL::route('addmoney.paypal') !!}" >
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('amount') ? ' has-error' : '' }}">
                            <label for="amount" class="col-md-4 control-label">Amount</label>

                            <div class="col-md-6">
                                <input id="amount" type="text" class="form-control" name="amount" value="{{ old('amount') }}" autofocus>

                                @if ($errors->has('amount'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('amount') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Paywith Paypal
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
</code>```

Now we are ready to run our example so run bellow command ro quick run:

```<code>php artisan serve
</code>```

Now you can open below URL on your browser:

```<code>DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
</code>```0

please visit this tutorials link...

https://www.youtube.com/watch?v=ly2xm_NM46g

Body:
Follow Bellow Few Step:

1)Install Laravel Application

2)Database Configuration

3)Install Required Packages

4)configuration paypal.php file

5)create route

6)create controller

7)create view file

Step 1 : Install Laravel Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

Step 2 : Database Configuration

In this step, we require to make database configuration, you have to add
 following details on your .env file.

1.Database Username

1.Database Password

1.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:
.env

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

Step 3 : Install Required Packages

We have required following 2 packages for integrate paypal payment in our laravel application.
add following two package in your composer.json file.

"guzzlehttp/guzzle": "~5.4",
"paypal/rest-api-sdk-php": "*",

then after run following command in your terminal

php artisan vendor:publish

after run this command, then after automatic create paypal.php file in your config/paypal.php path.

Step 4 : Configuration paypal.php file

&lt;?php

return array(
/** set your paypal credential **/
'client_id' =>'paypal client_id',
'secret' => 'paypal secret ID',
/**
* SDK configuration
*/
'settings' => array(
    /**
    * Available options 'sandbox' or 'live'
    */
    'mode' => 'sandbox',
    /**
    * Specify the max request time in seconds
    */
    'http.ConnectionTimeOut' => 1000,
    /**
    * Whether want to log to a file
    */
    'log.LogEnabled' => true,
    /**
    * Specify the file that want to write on
    */
    'log.FileName' => storage_path() . '/logs/paypal.log',
    /**
    * Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
    *
    * Logging is most verbose in the 'FINE' level and decreases as you
    * proceed towards ERROR
    */
    'log.LogLevel' => 'FINE'
    ),
);

Step 5: Create Route

In this is step we need to create route for paypal payment. so open your routes/web.php file and add following route.
routes/web.php

Route::get('paywithpaypal', array('as' => 'addmoney.paywithpaypal','uses' => 'AddMoneyController@payWithPaypal',));
Route::post('paypal', array('as' => 'addmoney.paypal','uses' => 'AddMoneyController@postPaymentWithpaypal',));
Route::get('paypal', array('as' => 'payment.status','uses' => 'AddMoneyController@getPaymentStatus',));

Step 6: Create Controller

In this point, now we should create new controller as AddMoneyController in this path app/Http/Controllers/AddMoneyController.php. this controller will manage layout and payment post request, So run bellow command for generate new controller:

php artisan make:controller AddMoneyController

Ok, now put below content in controller file:

app/Http/Controllers/AddMoneyController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use URL;
use Session;
use Redirect;
use Input;

/** All Paypal Details class **/
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Transaction;

class AddMoneyController extends HomeController
{

    private $_api_context;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        /** setup PayPal api context **/
        $paypal_conf = \Config::get('paypal');
        $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
        $this->_api_context->setConfig($paypal_conf['settings']);
    }

    /**
     * Show the application paywith paypalpage.
     *
     * @return \Illuminate\Http\Response
     */
    public function payWithPaypal()
    {
        return view('paywithpaypal');
    }

    /**
     * Store a details of payment with paypal.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postPaymentWithpaypal(Request $request)
    {
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $item_1 = new Item();

        $item_1->setName('Item 1') /** item name **/
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setPrice($request->get('amount')); /** unit price **/

        $item_list = new ItemList();
        $item_list->setItems(array($item_1));

        $amount = new Amount();
        $amount->setCurrency('USD')
            ->setTotal($request->get('amount'));

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($item_list)
            ->setDescription('Your transaction description');

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::route('payment.status')) /** Specify return URL **/
            ->setCancelUrl(URL::route('payment.status'));

        $payment = new Payment();
        $payment->setIntent('Sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirect_urls)
            ->setTransactions(array($transaction));
            /** dd($payment->create($this->_api_context));exit; **/
        try {
            $payment->create($this->_api_context);
        } catch (\PayPal\Exception\PPConnectionException $ex) {
            if (\Config::get('app.debug')) {
                \Session::put('error','Connection timeout');
                return Redirect::route('addmoney.paywithpaypal');
                /** echo "Exception: " . $ex->getMessage() . PHP_EOL; **/
                /** $err_data = json_decode($ex->getData(), true); **/
                /** exit; **/
            } else {
                \Session::put('error','Some error occur, sorry for inconvenient');
                return Redirect::route('addmoney.paywithpaypal');
                /** die('Some error occur, sorry for inconvenient'); **/
            }
        }

        foreach($payment->getLinks() as $link) {
            if($link->getRel() == 'approval_url') {
                $redirect_url = $link->getHref();
                break;
            }
        }

        /** add payment ID to session **/
        Session::put('paypal_payment_id', $payment->getId());

        if(isset($redirect_url)) {
            /** redirect to paypal **/
            return Redirect::away($redirect_url);
        }

        \Session::put('error','Unknown error occurred');
        return Redirect::route('addmoney.paywithpaypal');
    }

    public function getPaymentStatus()
    {
        /** Get the payment ID before session clear **/
        $payment_id = Session::get('paypal_payment_id');
        /** clear the session payment ID **/
        Session::forget('paypal_payment_id');
        if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
            \Session::put('error','Payment failed');
            return Redirect::route('addmoney.paywithpaypal');
        }
        $payment = Payment::get($payment_id, $this->_api_context);
        /** PaymentExecution object includes information necessary **/
        /** to execute a PayPal account payment. **/
        /** The payer_id is added to the request query parameters **/
        /** when the user is redirected from paypal back to your site **/
        $execution = new PaymentExecution();
        $execution->setPayerId(Input::get('PayerID'));
        /**Execute the payment **/
        $result = $payment->execute($execution, $this->_api_context);
        /** dd($result);exit; /** DEBUG RESULT, remove it later **/
        if ($result->getState() == 'approved') {

            /** it's all right **/
            /** Here Write your database logic like that insert record or value in database if you want **/

            \Session::put('success','Payment success');
            return Redirect::route('addmoney.paywithpaypal');
        }
        \Session::put('error','Payment failed');

        return Redirect::route('addmoney.paywithpaypal');
    }
  }

Step 7: Create View

In Last step, let's create paywithpaypal.blade.php(resources/views/paywithpaypal.blade.php) for layout and we will write design code here and also form for pay amount by paypal, So put following code:
resources/views/paywithpaypal.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                @if ($message = Session::get('success'))
                <div class="custom-alerts alert alert-success fade in">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('success');?>
                @endif

                @if ($message = Session::get('error'))
                <div class="custom-alerts alert alert-danger fade in">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('error');?>
                @endif
                <div class="panel-heading">Paywith Paypal</div>
                <div class="panel-body">
                    <form class="form-horizontal" method="POST" id="payment-form" role="form" action="{!! URL::route('addmoney.paypal') !!}" >
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('amount') ? ' has-error' : '' }}">
                            <label for="amount" class="col-md-4 control-label">Amount</label>

                            <div class="col-md-6">
                                <input id="amount" type="text" class="form-control" name="amount" value="{{ old('amount') }}" autofocus>

                                @if ($errors->has('amount'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('amount') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Paywith Paypal
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now we are ready to run our example so run bellow command ro quick run:

php artisan serve

Now you can open below URL on your browser:

http://localhost:8000/paywithpaypal

please visit this tutorials link...

https://www.youtube.com/watch?v=ly2xm_NM46g


问:
How to do a partial look up in excel and get the data in next column till four rows in VBA
I have  sheet 1 with Column name: Main task

MainTask

And, I have Sheet 2 where the Sub-tasks are given based on the characters between 1st and 2nd hyphen(-) of the Data in Main Task for eg: Under the main task column there is "Pyramid - IoT Forecast - Latin America - Argentina - 2017". So, based on the string " IoT Forecast" the sub tasks are given as in the below image.

Out Put:

Now In sheet 3  I need every title from the main task should be copied and pasted from the Sheet 1 and look for relevant sub tasks and pasted in the next column like the below image.

I have used, Wild cards, partial V-look up with Mid Function but only single sub task is populating. Please help me provide code in VBA.

答:
Your Sheet 3 is identical to Sheet 2 but with the full main task in it instead of just the extract. I suggest the following method.

Create a column in Sheet 1 in which you write only the extract. This column would be identical in contents to column A of sheet 2. Use this formula to populate that column (where A2 contains the full main task).

=TRIM(LEFT(MID($A2,FIND("-",$A2)+1,100),FIND("-",MID($A2,FIND("-",$A2)+1,100))-1))

Make a copy of Sheet 2 as Sheet 3 and add a blank column B in it. Populate this column with this formula (where A:A is the column containing the full task, and C:C the column you added in step 1.

=INDEX('Sheet 1'!A:A,MATCH(A2,'Sheet 1'!C:C,0))

Replace the formulas in Sheet 3 with values (Copy / Paste values) and Remove column A from that sheet. Sort this sheet on what is now column A.

Remove the column you added in Sheet 1 to restore Sheet 1 to its original state.


问:
Camera Preview black in Android 7
I'm using a straight forwards Camera API, for backwards compatibility. The camera view itself is overlayed slightly by an imageview and my surfaceChanged does this:

```<code>camera.setPreviewCallback((data, arg1) -> LiveView.this.invalidate());
camera.setPreviewDisplay(mHolder);
camera.startPreview();
</code>```

which works fine on all older devices. I set the preview size to the largest available  size earlier in surfaceCreated.
However on Android 7.1, it's suddenly black (on a Nexus 6 and Moto X Play, probably others - so on different devices).
The SurfaceView itself is greyed out in the Layout Inspector (willNotDraw = true), but VISIBLE (and hardware accelerated).
Strangely, I'm still able to take photos, event without preview, and the data in the preview callback contains an image.

At the same time I get the following log

```<code>E/mm-camera: mct_pipeline_send_ctrl_events: Send Set Parm events
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
D/QCameraParameters: setSnapshotSkipHint: preview hint 3 fps 15.019738
</code>```

Has anybody else experienced a completely black image in Android 7? Are there any easy fixes? (Like drawing the content of data directly?)

答:
Check Android run-time camera  permissions

if permission is not allowed, the camera will shows blank screen.

for more details :

https://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en

Title: Camera Preview black in Android 7

Body:
I'm using a straight forwards Camera API, for backwards compatibility. The camera view itself is overlayed slightly by an imageview and my surfaceChanged does this:

camera.setPreviewCallback((data, arg1) -> LiveView.this.invalidate());
camera.setPreviewDisplay(mHolder);
camera.startPreview();

which works fine on all older devices. I set the preview size to the largest available  size earlier in surfaceCreated.
However on Android 7.1, it's suddenly black (on a Nexus 6 and Moto X Play, probably others - so on different devices).
The SurfaceView itself is greyed out in the Layout Inspector (willNotDraw = true), but VISIBLE (and hardware accelerated).
Strangely, I'm still able to take photos, event without preview, and the data in the preview callback contains an image.

At the same time I get the following log

E/mm-camera: mct_pipeline_send_ctrl_events: Send Set Parm events
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
E/QCamera2HWI: static void* qcamera::QCameraCbNotifier::cbNotifyRoutine(void*) : cb message type 32768 not enabled!
D/QCameraParameters: setSnapshotSkipHint: preview hint 3 fps 15.019738

Has anybody else experienced a completely black image in Android 7? Are there any easy fixes? (Like drawing the content of data directly?)


问:
Iterator and printing details
Hey all. I've been asked to create a method that uses an iterator to print details of 'lots'. I'm able to create an iterator that prints all of the details, however, for any lots that haven't been bought, a message should print out this fact and I'm unsure how I can add that code in. It is the public void close method I'm focusing on. This is what I have so far. Help is greatly appreciated.</p>

```<code>public class Auction{

    // The list of Lots in this auction.
    private final ArrayList<Lot> lots;
    // The number that will be given to the next lot entered
    // into this auction.
    private int nextLotNumber;

    /**
     * Create a new auction.
     */
    public Auction(){
        lots = new ArrayList<Lot>();
        nextLotNumber = 1;
    }

    /**
     * Enter a new lot into the auction.
     *
     * @param description
     *            A description of the lot.
     */
    public void enterLot(final String description){
        lots.add(new Lot(nextLotNumber, description));
        nextLotNumber++;
    }

    /**
     * Show the full list of lots in this auction.
     */
    public void showLots(){
        for(final Lot lot : lots){
            System.out.println(lot.toString());
        }
    }

    public void close(){
        final Iterator<Lot> it = lots.iterator();
        while(it.hasNext()){

        }
    }

    /**
     * Bid for a lot. A message indicating whether the bid is
     * successful or not is printed.
     *
     * @param number
     *            The lot number being bid for.
     * @param bidder
     *            The person bidding for the lot.
     * @param value
     *            The value of the bid.
     */
    public void bidFor(final int lotNumber,
        final Person bidder,
        final long value){
        final Lot selectedLot = getLot(lotNumber);
        if(selectedLot != null){
            final boolean successful =
                selectedLot.bidFor(new Bid(bidder, value));
            if(successful){
                System.out.println("The bid for lot number " + lotNumber
                    + " was successful.");
            } else{
                // Report which bid is higher.
                final Bid highestBid = selectedLot.getHighestBid();
                System.out.println("Lot number: " + lotNumber
                    + " already has a bid of: " + highestBid.getValue());
            }
        }
    }

}
</code>```

答: I would add the information you want the Lot to print to the Lot.toString() I would suggest your close() method should close() each lot, and the lot should print anything which needs to be printed.</p>

Title: Iterator and printing details

Body:
Hey all. I've been asked to create a method that uses an iterator to print details of 'lots'. I'm able to create an iterator that prints all of the details, however, for any lots that haven't been bought, a message should print out this fact and I'm unsure how I can add that code in. It is the public void close method I'm focusing on. This is what I have so far. Help is greatly appreciated.

public class Auction{

    // The list of Lots in this auction.
    private final ArrayList<Lot> lots;
    // The number that will be given to the next lot entered
    // into this auction.
    private int nextLotNumber;

    /**
     * Create a new auction.
     */
    public Auction(){
        lots = new ArrayList<Lot>();
        nextLotNumber = 1;
    }

    /**
     * Enter a new lot into the auction.
     *
     * @param description
     *            A description of the lot.
     */
    public void enterLot(final String description){
        lots.add(new Lot(nextLotNumber, description));
        nextLotNumber++;
    }

    /**
     * Show the full list of lots in this auction.
     */
    public void showLots(){
        for(final Lot lot : lots){
            System.out.println(lot.toString());
        }
    }

    public void close(){
        final Iterator<Lot> it = lots.iterator();
        while(it.hasNext()){

        }
    }

    /**
     * Bid for a lot. A message indicating whether the bid is
     * successful or not is printed.
     *
     * @param number
     *            The lot number being bid for.
     * @param bidder
     *            The person bidding for the lot.
     * @param value
     *            The value of the bid.
     */
    public void bidFor(final int lotNumber,
        final Person bidder,
        final long value){
        final Lot selectedLot = getLot(lotNumber);
        if(selectedLot != null){
            final boolean successful =
                selectedLot.bidFor(new Bid(bidder, value));
            if(successful){
                System.out.println("The bid for lot number " + lotNumber
                    + " was successful.");
            } else{
                // Report which bid is higher.
                final Bid highestBid = selectedLot.getHighestBid();
                System.out.println("Lot number: " + lotNumber
                    + " already has a bid of: " + highestBid.getValue());
            }
        }
    }

}


问:
How to make HTTP POST on website that uses asp.net?
I'm using Python library requests for this, but I can't seem to be able to log in to this website.
The url is https://www.bet365affiliates.com/ui/pages/affiliates/, and I've been trying post requests to https://www.bet365affiliates.com/Members/CMSitePages/SiteLogin.aspx?lng=1 with the data of "ctl00$MasterHeaderPlaceHolder$ctl00$passwordTextbox", "ctl00$MasterHeaderPlaceHolder$ctl00$userNameTextbox", etc, but I never seem to be able to get logged in.

Could someone more experienced check the page's source code and tell me what am I am missing here?

答:
Did you inspected the http request used by the browser to log you in?
You should replicate it.

FB


问:
Can't import `multivariate_normal` when using `scipy.stats`
I'm trying to generate the value of the pdf of a multivariate distribution with scipy. This is the import statement in my script:

```<code>from scipy.stats import multivariate_normal
</code>```

but it's throwing an ImportError:

```<code>ImportError: cannot import name multivariate_normal
</code>```

Everything else is working normally.

答:
I had this issue on my Ubuntu 14.04 and python 2.7. I resolved it by following the steps given here . The problem arises because the scipy must be atleast 0.14 for stats package to work. Just doing sudo pip install scipy --upgrade
did not work for me. I had to upgrade the numpy and then try to upgrade the scipy, because scipy is dependent on numpy. We also need to update the build dependencies.Below are the steps I followed to fix it

Step 1) First need to make sure all scipy dependencies are installed properly

```<code>sudo apt-get install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose
</code>```

Step 2) Make sure the numpy, which scipy is dependent on is up-to-date

```<code>sudo pip install numpy --upgrade
</code>```

Step 3) Make sure all the build dependencies of scipy is available

```<code>sudo apt-get build-dep python-scipy
</code>```

Step 4) Rerun the upgrade

```<code>sudo pip install scipy --upgrade
</code>```

Body:
I'm trying to generate the value of the pdf of a multivariate distribution with scipy. This is the import statement in my script:

from scipy.stats import multivariate_normal

but it's throwing an ImportError:

ImportError: cannot import name multivariate_normal

Everything else is working normally.

Body:
I had this issue on my Ubuntu 14.04 and python 2.7. I resolved it by following the steps given here . The problem arises because the scipy must be atleast 0.14 for stats package to work. Just doing sudo pip install scipy --upgrade
did not work for me. I had to upgrade the numpy and then try to upgrade the scipy, because scipy is dependent on numpy. We also need to update the build dependencies.Below are the steps I followed to fix it

Step 1) First need to make sure all scipy dependencies are installed properly

sudo apt-get install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose

Step 2) Make sure the numpy, which scipy is dependent on is up-to-date

sudo pip install numpy --upgrade

Step 3) Make sure all the build dependencies of scipy is available

sudo apt-get build-dep python-scipy

Step 4) Rerun the upgrade

sudo pip install scipy --upgrade


问:
how to optimize the following mysql query
I  have  a trouble in the mysql query . the query is following.

```<code>SELECT *
FROM group
WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6);
</code>```

how can I  optimize the query  to  which maybe can drop the OR word . thanks.

also,  the query  may be  extended like follow .

```<code>SELECT *
    FROM group
    WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
    OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6)
    OR     ... ;
</code>```

can someone explain about the Train of thought of  The solution， thanks very much.

答:
Often the quickest solution is the split it to multiple UNIONed queries. Then each smaller query can use indexes efficiently.</p>

```<code>SELECT *
FROM group
WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
UNION
SELECT *
FROM group
WHERE  (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6);
</code>```

Body:
I  have  a trouble in the mysql query . the query is following.

SELECT *
FROM group
WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6);

how can I  optimize the query  to  which maybe can drop the OR word . thanks.

also,  the query  may be  extended like follow .

SELECT *
    FROM group
    WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
    OR     (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6)
    OR     ... ;

can someone explain about the Train of thought of  The solution， thanks very much.

Body:
Often the quickest solution is the split it to multiple UNIONed queries. Then each smaller query can use indexes efficiently.

SELECT *
FROM group
WHERE  (level IN (3,4,5,6) AND  last_time BETWEEN  0 AND 3)
UNION
SELECT *
FROM group
WHERE  (level IN (4,5,6,7) AND  last_time BETWEEN  0 AND 6);


问:
How to make wordpress " kitsune theme" live
I have download kitsune wordpress theme. But i am getting issue .

How to make wordpress kitsune theme live .

I have purchase this theme . The site is running when i am login through wp login but not working when i am not login .

Please help me out . because i am unable to make this site live.

答:
It might be maintenance mode is on please read the documentation or approach the support forum through themeforest or where you have purchased it.

If you still have the same issue, it may need to look into the your site and admin section.


问:
assign value as per ratio defined
I have one scenario here. Let me explain by small example.

I have 10 pens, I have to give it to 3 people. Those person's ratio are like 6:6:1 means if I am giving 1 pen to Person C I have to give 6-6 pens to Person A and Person B.

I have tried to solve it by using simple calculation which I have described below.

```<code>PerPersonPen = (TotalCountofPens * PerPersonRatio)/(SumofAllPersonsRatio)

Person A =(Int) (10*6)/13 = 4
Person B = (Int) (10*6)/13 = 4
Person C = (Int) (10*1)/13 = 0
</code>```

Here, Person C will get 0 pens, but it shouldn't happen. I would like that Person A & B are getting 4 pens, which are right. But Person C should get 1 pen also which remains.

This happens in a case of any person have 1 ratio count compare to others.

Can anybody help me to sort out this? Or How can I achieve it?

答:
When looking at your example it is clear that each persone should get at least the rsult you calculated.
And only some will get more.

I suggest the following algorithem:

calculate how much each presone should get in double. Same as you did without the cast.

sum the descrete sum of all persons (8 in our example).

Sort the persons by the Mantissa (After the point vaule).

For the first k persons Use Math.Ceiling(assigned value) where k is the desired value - sum we calculated in step 2. 10-8 in our example.

For the other persons use regular cast like (int) (assigned value).

Title: assign value as per ratio defined

Body:
I have one scenario here. Let me explain by small example.

I have 10 pens, I have to give it to 3 people. Those person's ratio are like 6:6:1 means if I am giving 1 pen to Person C I have to give 6-6 pens to Person A and Person B.

I have tried to solve it by using simple calculation which I have described below.

PerPersonPen = (TotalCountofPens * PerPersonRatio)/(SumofAllPersonsRatio)

Person A =(Int) (10*6)/13 = 4
Person B = (Int) (10*6)/13 = 4
Person C = (Int) (10*1)/13 = 0

Here, Person C will get 0 pens, but it shouldn't happen. I would like that Person A & B are getting 4 pens, which are right. But Person C should get 1 pen also which remains.

This happens in a case of any person have 1 ratio count compare to others.

Can anybody help me to sort out this? Or How can I achieve it?


问:
google chart pass segment value
I am trying to figure out how to pass value from segment from google donut chart through javascript. Following this example (the donut one), I modified html like: onmouseover="segmentMouseOver(event)"
to pass the event onMouseOver. Although, I cannot find a way to pass the value of donut's segment, on which is mouse over.

Any help is welcome!

答:
```<code>// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));

function selectHandler() {
  var selectedItem = chart.getSelection()[0];
  if (selectedItem) {
    var topping = data.getValue(selectedItem.row, 0);
    alert('The user selected ' + topping);
  }
}

google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
</code>```

you can find out more here.

Title: google chart pass segment value

Body:
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));

function selectHandler() {
  var selectedItem = chart.getSelection()[0];
  if (selectedItem) {
    var topping = data.getValue(selectedItem.row, 0);
    alert('The user selected ' + topping);
  }
}

google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);

you can find out more here.


问:
Tomcat 8.0 64-bit server not starting and getting error from Catalina.bat
I am unable to start Tomcat 8.0 64-bit server. I have catalina.bat run also. I am getting the below message.

```<code>01-Oct-2014 10:22:11.415 SEVERE [main] org.apache.catalina.startup.Bootstrap.ini
tClassLoaders Class loader creation threw exception
java.io.IOException: The filename, directory name, or volume label syntax is incorrect
    at java.io.WinNTFileSystem.canonicalize0(Native Method)
    at java.io.WinNTFileSystem.canonicalize(WinNTFileSystem.java:428)
    at java.io.File.getCanonicalPath(File.java:618)
    at java.io.File.getCanonicalFile(File.java:643)
    at org.apache.catalina.startup.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:165)
    at org.apache.catalina.startup.Bootstrap.createClassLoader(Bootstrap.java:201)
    at org.apache.catalina.startup.Bootstrap.initClassLoaders(Bootstrap.java:146)
    at org.apache.catalina.startup.Bootstrap.init(Bootstrap.java:256)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
</code>```

Could you please advise?

答: I had the exact same issue and just deleted the server from my workspace and added a new one, didnt get the error again. Its working fine for now.</p>

Body:
I am unable to start Tomcat 8.0 64-bit server. I have catalina.bat run also. I am getting the below message.

01-Oct-2014 10:22:11.415 SEVERE [main] org.apache.catalina.startup.Bootstrap.ini
tClassLoaders Class loader creation threw exception
java.io.IOException: The filename, directory name, or volume label syntax is incorrect
    at java.io.WinNTFileSystem.canonicalize0(Native Method)
    at java.io.WinNTFileSystem.canonicalize(WinNTFileSystem.java:428)
    at java.io.File.getCanonicalPath(File.java:618)
    at java.io.File.getCanonicalFile(File.java:643)
    at org.apache.catalina.startup.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:165)
    at org.apache.catalina.startup.Bootstrap.createClassLoader(Bootstrap.java:201)
    at org.apache.catalina.startup.Bootstrap.initClassLoaders(Bootstrap.java:146)
    at org.apache.catalina.startup.Bootstrap.init(Bootstrap.java:256)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)

Could you please advise?


问:
Difference between Oracle forms and E-business suite
What is the difference between Oracle forms and Oracle E-business suite?
Is there any similarities between Oracle 11G and Oracle E-business suite?</p>

答:
Oracle Forms is a 4GL for building applications. One of those applications is Oracle E-Business Suite (even after fifteen years of JDeveloper, ADF and Fusion Apps). So the relationship is Lego bricks vs finished model.

We can use Forms to extend Oracle EBS and/or to build our own applications.


问:
How to get Notification from standalone class (Swift 3)
I want to call method in a class as soon as observer get Notification in another one. The problem is that I cannot call one class from another, because I will get recursion call then.

1) Controller class with Player instance:

```<code>//  PlayerController.swift
//  player

import UIKit
import MediaPlayer

class NowPlayingController: NSObject {

    var musicPlayer: MPMusicPlayerController {
        if musicPlayer_Lazy == nil {
            musicPlayer_Lazy = MPMusicPlayerController.systemMusicPlayer()
            let center = NotificationCenter.default
            center.addObserver(
                self,
                selector: #selector(self.playingItemDidChange),
                name: NSNotification.Name.MPMusicPlayerControllerNowPlayingItemDidChange,
                object: musicPlayer_Lazy)
            musicPlayer_Lazy!.beginGeneratingPlaybackNotifications()
        }

        return musicPlayer_Lazy!
    }

    //If song changes
    func playingItemDidChange(notification: NSNotification) {
        //somehow call updateSongInfo() method from 2nd class
    }

    //Get song metadata
    func getSongData() -> (UIImage, String?, String?) {
        let nowPlaying = musicPlayer.nowPlayingItem

        //...some code
        return (albumImage, songName, artistAlbum)
    }

    func updateProgressBar() -> (Int?, Float?){
        let nowPlaying = musicPlayer.nowPlayingItem
        var songDuration: Int?
        var elapsedTime: Float?

        songDuration = nowPlaying?.value(forProperty: MPMediaItemPropertyPlaybackDuration) as? Int
        elapsedTime = Float(musicPlayer.currentPlaybackTime)

        return(songDuration, elapsedTime)
    }
}
</code>```

2) View controller which should be updated when Player Controller get notification

```<code>//  MainViewController.swift
//  player

import UIKit

class MainViewController: UIViewController {

    let playerController = PlayerController()
    @IBOutlet weak var albumView: UIImageView!
    @IBOutlet weak var songLabel: UILabel!
    @IBOutlet weak var artistAlbum: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        //Start updating progress bar
        Timer.scheduledTimer(timeInterval: 0.5,
                         target: self,
                         selector: #selector(MainViewController.updateProgressBar),
                         userInfo: nil,
                         repeats: true)
    }

    private func updateSongInfo(){
        (albumView.image!, songLabel.text, artistAlbum.text) = playerController.getSongData()
    }

    private func updateProgressBar(){
        (progressBar.maximumValue, progressBar.value) = playerController.playingItemProgress()
}
}
</code>```

Solution for Swift 3:

In NowPlayingController:

```<code>let newSongNotifications = NSNotification(name:NSNotification.Name(rawValue: "updateSongNotification"), object: nil, userInfo: nil)

func playingItemDidChange(notification: NSNotification) {
        NotificationCenter.default.post(newSongNotifications as Notification)
}
</code>```

And in other controller:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(self.updateSongInfo), name: NSNotification.Name(rawValue: "updateSongNotification"), object: nil)
}
</code>```

答: You can use delegate method to update MainViewController</p>

Body:
I want to call method in a class as soon as observer get Notification in another one. The problem is that I cannot call one class from another, because I will get recursion call then.

1) Controller class with Player instance:

//  PlayerController.swift
//  player

import UIKit
import MediaPlayer

class NowPlayingController: NSObject {

    var musicPlayer: MPMusicPlayerController {
        if musicPlayer_Lazy == nil {
            musicPlayer_Lazy = MPMusicPlayerController.systemMusicPlayer()
            let center = NotificationCenter.default
            center.addObserver(
                self,
                selector: #selector(self.playingItemDidChange),
                name: NSNotification.Name.MPMusicPlayerControllerNowPlayingItemDidChange,
                object: musicPlayer_Lazy)
            musicPlayer_Lazy!.beginGeneratingPlaybackNotifications()
        }

        return musicPlayer_Lazy!
    }

    //If song changes
    func playingItemDidChange(notification: NSNotification) {
        //somehow call updateSongInfo() method from 2nd class
    }

    //Get song metadata
    func getSongData() -> (UIImage, String?, String?) {
        let nowPlaying = musicPlayer.nowPlayingItem

        //...some code
        return (albumImage, songName, artistAlbum)
    }

    func updateProgressBar() -> (Int?, Float?){
        let nowPlaying = musicPlayer.nowPlayingItem
        var songDuration: Int?
        var elapsedTime: Float?

        songDuration = nowPlaying?.value(forProperty: MPMediaItemPropertyPlaybackDuration) as? Int
        elapsedTime = Float(musicPlayer.currentPlaybackTime)

        return(songDuration, elapsedTime)
    }
}

2) View controller which should be updated when Player Controller get notification

//  MainViewController.swift
//  player

import UIKit

class MainViewController: UIViewController {

    let playerController = PlayerController()
    @IBOutlet weak var albumView: UIImageView!
    @IBOutlet weak var songLabel: UILabel!
    @IBOutlet weak var artistAlbum: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        //Start updating progress bar
        Timer.scheduledTimer(timeInterval: 0.5,
                         target: self,
                         selector: #selector(MainViewController.updateProgressBar),
                         userInfo: nil,
                         repeats: true)
    }

    private func updateSongInfo(){
        (albumView.image!, songLabel.text, artistAlbum.text) = playerController.getSongData()
    }

    private func updateProgressBar(){
        (progressBar.maximumValue, progressBar.value) = playerController.playingItemProgress()
}
}

Solution for Swift 3:

In NowPlayingController:

let newSongNotifications = NSNotification(name:NSNotification.Name(rawValue: "updateSongNotification"), object: nil, userInfo: nil)

func playingItemDidChange(notification: NSNotification) {
        NotificationCenter.default.post(newSongNotifications as Notification)
}

And in other controller:

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(self.updateSongInfo), name: NSNotification.Name(rawValue: "updateSongNotification"), object: nil)
}


问:
How to align main menu to center? Theme Uncode Child - Wordpress
I am using Uncode theme 1.4 and I am stuck on a small problem. My main menu shifts to left with 27.5 px and I can't seem to override that in CSS. Here's my website http://ralucacozma.com/

I've tried the following unsuccessfully:

```<code>.menu-primary-inner menu-smart sm {
left: 0px !important;
}
.menu-main-menu {
left: 0px !important;
}
</code>```

Your help is highly appreciated!
Thannk you

答:
I have verified with your website, this css does override,</p>

```<code>.menu-primary-inner.menu-smart.sm {
    left: 0 !important;
}
</code>```

Body:
I am using Uncode theme 1.4 and I am stuck on a small problem. My main menu shifts to left with 27.5 px and I can't seem to override that in CSS. Here's my website http://ralucacozma.com/

I've tried the following unsuccessfully:

.menu-primary-inner menu-smart sm {
left: 0px !important;
}
.menu-main-menu {
left: 0px !important;
}

Your help is highly appreciated!
Thannk you

Body:
I have verified with your website, this css does override,

.menu-primary-inner.menu-smart.sm {
    left: 0 !important;
}