问:
Samsung S9(18:9) camera preview stretched
I am using Android Camera API and it works good 16:9 ratio devices on both portrait and landscape modes. But in Samsung S9 18:9 ratio device, on landscape mode the preview looks stretched. On Samsung S9 I got following supported preview sizes, 1920X1080,1440X1080, 1088X1088,1280X720,1056X704, 1024X768, 960X720,800X450,720X720,720X480,640X480,352X288,320X240,256X144,176X144 So optimal preview size is 1920X1080 but actual resolution of device is 2,220 x 1,080. So that it looks stretched.But I need preview on full screen.How default camera preview shows on fullscreen?

```<code>@SuppressLint("ClickableViewAccessibility")
    @SuppressWarnings("deprecation")
    public CameraPreview(Context context, Camera.PreviewCallback previewCallback) {
        super(context);
        this.previewCallback = previewCallback;
        mContext = context;
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void setCameraDisplayOrientation(Context activity,
                                            int cameraId, Camera camera) {
        Camera.CameraInfo info =
                new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId, info);
        int rotation = ((AppCompatActivity) activity).getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }

        mDisplayOrientation = result;

        Log.d(TAG, "setCameraDisplayOrientation: "+mDisplayOrientation);

        camera.setDisplayOrientation(result);

    }

    public void takePhoto(final PictureCallback pCalback) {
        mCamera.takePicture(null, null, pCalback);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, acquire the camera and tell it where
        // to draw.
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
            //previewCount = 0;
        }

        try {
            mCamera = Camera.open();

            //setCameraDisplayOrientation(mContext, 0, mCamera);
            /*mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
            int screenWidth = displayMetrics.widthPixels;
            int screenHeight = displayMetrics.heightPixels;
            optimalPreviewSize = getBestAspectPreviewSize(mParameters.getSupportedPreviewSizes(), screenWidth, screenHeight);//Bug Fix for Samsung A8
            mParameters.setPreviewSize(optimalPreviewSize.width, optimalPreviewSize.height);
            mParameters.setPictureSize(optimalPreviewSize.width, optimalPreviewSize.height);
            mParameters.setPreviewFpsRange(30000, 30000);
            mCamera.setParameters(mParameters);*/
            /*mCamera.setPreviewDisplay(holder);
            mCamera.setPreviewCallback(previewCallback);*/

            mCamera.setPreviewDisplay(holder);
        } catch (IOException exception) {
            mCamera.release();
            mCamera = null;
            //previewCount = 0;
        } catch (Exception exception) {
            mCamera = null;
            //previewCount = 0;
        }

        if (mCameraPreviewListener != null) {
            mCameraPreviewListener.onCameraSurfaceCreated();
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
            //previewCount = 0;
        }
        if (mCameraPreviewListener != null) {
            mCameraPreviewListener.onCameraSurfaceDestroyed();
        }
    }

    public void stopCamera() {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
            //previewCount = 0;
        }
    }

    @SuppressWarnings("null")
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        try {
            // Now that the size is known, set up the camera parameters and begin
            // the preview.
            mParameters = mCamera.getParameters();

            Log.d("CameraFix", "parameters -> " + mParameters.flatten());

            setCameraDisplayOrientation(mContext, 0, mCamera);

            mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);

            //Size optimalPreviewSize = getOptimalPreviewSize(mParameters.getSupportedPreviewSizes(), getWidth(), getHeight());
            DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
            int screenWidth = displayMetrics.widthPixels;
            int screenHeight = displayMetrics.heightPixels;

            //Size optimalPreviewSize = getOptimalPreviewSize(mParameters.getSupportedPreviewSizes(), screenWidth, screenHeight, getHeight());
            mSupportedPreviewSizes = mParameters.getSupportedPreviewSizes();
            optimalPreviewSize = getBestAspectPreviewSize(mParameters.getSupportedPreviewSizes(), screenWidth, screenHeight);//Bug Fix for Samsung A8

            Log.d("CameraFix", "optimalPreviewSize.width -> " + optimalPreviewSize.width);
            Log.d("CameraFix", "optimalPreviewSize.height -> " + optimalPreviewSize.height);

            mParameters.setPreviewSize(optimalPreviewSize.width, optimalPreviewSize.height);
            mParameters.setPictureSize(optimalPreviewSize.width, optimalPreviewSize.height);
            mParameters.setPreviewFpsRange(30000, 30000);

            /*if (mDisplayOrientation == 0 || mDisplayOrientation == 180) {
                setLayoutParams(new FrameLayout.LayoutParams(optimalPreviewSize.width, optimalPreviewSize.height,Gravity.CENTER));
            }*/

            Log.d("CameraFix", "setPreviewFpsRange");

            mCamera.setParameters(mParameters);

            mCamera.setPreviewDisplay(holder);

            //SurfaceTexture st = new SurfaceTexture(10);
            //mCamera.setPreviewTexture(st);
            mCamera.setPreviewCallback(previewCallback);
            mCamera.startPreview();
            Log.d("CameraFix", "start preview");
            if (mCameraPreviewListener != null) {
                mCameraPreviewListener.onCameraSurfaceChanged();
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.d("CameraFix", e.toString());
        }

    }

public void toggleFlash(boolean flashModeOn) {
        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
            Parameters parameters = mCamera.getParameters();
            if (flashModeOn) {
                //parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
                parameters.setFlashMode(Parameters.FLASH_MODE_ON);
                mCamera.setParameters(parameters);
                mCamera.startPreview();
                //Toast.makeText(mContext, R.string.flash_mode_on, Toast.LENGTH_SHORT).show();
            } else {
                parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
                mCamera.setParameters(parameters);
                //Toast.makeText(mContext, R.string.flash_mode_off, Toast.LENGTH_SHORT).show();
            }

        } else {
            Toast.makeText(mContext, R.string.flash_not_available, Toast.LENGTH_SHORT).show();
        }
    }

/**
     * Source for this solution - https://stackoverflow.com/questions/21354313/camera-preview-quality-in-android-is-poor/21354442#21354442
     *
     * @param supportedPreviewSizes
     * @param screenWidth
     * @param screenHeight
     * @return
     */
    private Size getBestAspectPreviewSize(List<Size> supportedPreviewSizes, int screenWidth, int screenHeight) {
        double targetRatio = (double) screenWidth / screenHeight;
        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        for (int i = 0; i < supportedPreviewSizes.size(); i++) {
            Size size = supportedPreviewSizes.get(i);
            Log.d(TAG, "getBestAspectPreviewSize: supportedPreviewSizes -> "+size.width +"X"+size.height);
        }

        Log.d(TAG, "getBestAspectPreviewSize: supportedPreviewSizes -> "+supportedPreviewSizes.toString());
        Log.d(TAG, "getBestAspectPreviewSize: mDisplayOrientation -> "+mDisplayOrientation);

        if (mDisplayOrientation == 90 || mDisplayOrientation == 270) {
            Log.d(TAG, "getBestAspectPreviewSize: inside 90 - 270 ");
            targetRatio = (double) screenHeight / screenWidth;
        }

        Log.d(TAG, "getBestAspectPreviewSize: targetRatio -> "+targetRatio);

        Collections.sort(supportedPreviewSizes,
                Collections.reverseOrder(new SizeComparator()));

        for (Size size : supportedPreviewSizes) {
            double ratio = (double) size.width / size.height;

            if (Math.abs(ratio - targetRatio) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(ratio - targetRatio);
            }

            if (minDiff < 0.0d) {
                break;
            }
        }
        return (optimalSize);

        /*if (mDisplayOrientation == 0 || mDisplayOrientation == 180) {
            if (optimalSize != null) {
                return mCamera.new Size(optimalSize.height, optimalSize.width);
            } else {
                return null;
            }
        }
        else{
            return (optimalSize);
        }*/

        //return mCamera.new Size(2220,1080);
    }

    public int getDisplayOrientation() {
        return mDisplayOrientation;
    }

    public void setDisplayOrientation(int displayOrientation) {
        this.mDisplayOrientation = displayOrientation;
    }

    public Parameters getCameraParameters() {
        return mCamera.getParameters();
    }

public void setCameraPreviewListener(CameraPreviewListener cameraPreviewListener) {
        mCameraPreviewListener = cameraPreviewListener;
    }

    public interface CameraPreviewListener {
        void onCameraSurfaceCreated();

        void onCameraSurfaceChanged();

        void onCameraSurfaceDestroyed();

        void onCameraPreviewStarted();
    }

    private static class SizeComparator implements
            Comparator<Size> {
        @Override
        public int compare(Size lhs, Size rhs) {
            int left = lhs.width * lhs.height;
            int right = rhs.width * rhs.height;

            if (left < right) {
                return (-1);
            } else if (left > right) {
                return (1);
            }

            return (0);
        }
    }
</code>```

答:
Please take look into my answer hope it will help, I resolved the stretch issue by the following code, method name might change. I share my implementation, Because I know how hard to implement camera in Android, So please don't hesitate to see the following section.

Invoke loadCamera method in ButtonAction.

```<code>private void loadCamera() {
        if (CommonUtils.deviceHasCamera(getActivityContext)) {
            startBackgroundThread();
            mCameraTimeOut=(isPermissionGranted?2500:5000);
            if (mTextureView.isAvailable()) {
                openCamera(mTextureView.getWidth(), mTextureView.getHeight());
            } else {
                mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
            }
        }else{
            ShowToastUtils.INSTANCE.showCustomToast(getActivityContext, getString(R.string.msg_no_camera));
        }
    }
</code>```

Initially SurfaceListener Invoked for Camera

```<code>private TextureView.SurfaceTextureListener mSurfaceTextureListener
            = new TextureView.SurfaceTextureListener() {

        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture,
                                              int width, int height) {
            mCameraTimeOut=(isPermissionGranted?2500:5000);
            Log.e(TAG1, "chooseOptimalSize"+"-SurfaceTextureListener ---=>Width---=>"+width);
            Log.e(TAG1, "chooseOptimalSize"+"-SurfaceTextureListener ---=>Height---=>"+height);
            openCamera(width, height);
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture,
                                                int width, int height) {
            configureTransform(width, height);
        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
            return true;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {}

    };
</code>```

To Choose Optimal Preview Size for Texture

```<code>//Samsung-S6-choices[0]
//Samsung-S7-edge-choices[6]
//OnePlus-5T-choices[15]
/*Following is used for Camera Preview in TextureView,  based on device camera resolution*/
    /*
     * Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
     * width and height are at least as large as the respective requested values, and whose aspect
     * ratio matches with the specified value.
     *
     * @param choices     The list of sizes that the camera supports for the intended output class
     * @param width       The minimum desired width
     * @param height      The minimum desired height
     * @param aspectRatio The aspect ratio
     * @return The optimal {@code Size}, or an arbitrary one if none were big enough
     */

     private  Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
        // Collect the supported resolutions that are at least as big as the preview Surface

        int loopCounter=0;
        Log.e(TAG1, "Screen-->Width x Height="+screenWidth+" x "+screenHeight);
        for (Size size : choices) {
            Log.e(TAG1, "chooseOptimalSize:"+size);
        }
        for (Size size : choices) {
            int orientation = getActivityContext.getResources().getConfiguration().orientation;
            if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                if((size.getWidth()/16) == (size.getHeight()/9) && size.getWidth() <=7680 ) {//8K UHDTV Super Hi-Vision
                    Log.e(TAG1, "chooseOptimalSize:"+size.getWidth()+"x"+size.getHeight()+"--LoopPosition---==>"+loopCounter);
                    return size;
                }
            } else {
                Log.e(TAG1, "chooseOptimalSize:--given--"+size);
                if((size.getWidth()/16) == (size.getHeight()/9) && ((size.getWidth() <=1280)||(size.getHeight()<=1920))) {
                    mCameraRatio=RATIO_16_9;
                    Log.e(TAG1, "chooseOptimalSize:"+size.getWidth()+"x"+size.getHeight()+"-16:9"+"--LoopPosition---==>"+loopCounter);
                    return size;
                }else if((size.getWidth()/18) == (size.getHeight()/9) && ((size.getWidth() <=2160)||(size.getHeight()<=3840))) {
                    mCameraRatio=RATIO_18_9;
                    Log.e(TAG1, "chooseOptimalSize:"+size.getWidth()+"x"+size.getHeight()+"-18:9"+"--LoopPosition---==>"+loopCounter);
                    return size;
                }else if((size.getWidth()/18.5) == (size.getHeight()/9) && ((size.getWidth() <=2160)||(size.getHeight()<=3840))) {
                    mCameraRatio=RATIO_18_9;
                    Log.e(TAG1, "chooseOptimalSize:"+size.getWidth()+"x"+size.getHeight()+"-18.5:9"+"--LoopPosition---==>"+loopCounter);
                    return size;
                }else if((width/19) == (height/9) && ((width <=2208)||(height<=3216))) {
                    mCameraRatio=RATIO_19_9;
                    Log.e(TAG1, "chooseOptimalSize:"+size.getWidth()+"x"+size.getHeight()+"-19:9"+"--LoopPosition---==>"+loopCounter);
                    return size;
                }else if((size.getWidth()/19.5) == (size.getHeight()/9) && ((size.getWidth() <=3840)||(size.getHeight()<=2160))) {
                    mCameraRatio=RATIO_19_9;
                    Log.e(TAG1, "chooseOptimalSize:"+size.getWidth()+"x"+size.getHeight()+"-19.5:9"+"--LoopPosition---==>"+loopCounter);
                    return size;
                }else{
                    Log.e(TAG1, "chooseOptimalSize"+" not proper aspect resolution");
                }
            }
                  loopCounter++;
        }
}
</code>```

To Open Camera

```<code>    private void openCamera(int width, int height) {
                CameraManager manager = (CameraManager) getActivityContext.getSystemService(Context.CAMERA_SERVICE);
                try {
                    Log.e(TAG, "tryAcquire");
                    if (!mCameraOpenCloseLock.tryAcquire(mCameraTimeOut, TimeUnit.MILLISECONDS)) {
                        throw new RuntimeException("Time out waiting to lock camera opening.");
                    }
                    String mCameraId = manager.getCameraIdList()[cameraId];
                    // Choose the sizes for camera preview and video recording
                    characteristics = manager.getCameraCharacteristics(mCameraId);
                    StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                    try {
                        mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
                        maximumZoomLevel = characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);
                        if (map == null) {
                            throw new RuntimeException("Cannot get available preview/video sizes");
                        }
                        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
    /*This Line will configure the Texture size*/
                        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);

int orientation = getResources().getConfiguration().orientation;
                    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                        Log.e(TAG1, "Width" + mPreviewSize.getWidth() + "X Height" + mPreviewSize.getHeight());
                        mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
                    } else {
                        Log.e(TAG1, "Width" + mPreviewSize.getHeight() + "X Height" + mPreviewSize.getWidth());
                        mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
    //S10 preview Size
                        /* mTextureView.setAspectRatio(1080, 2280);*/
                        //mTextureView.setAspectRatio(2208, 2944);
                    }
                    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                        configureTransform(width, height);
                    }

                    if (isPermissionGranted) {
                        manager.openCamera(mCameraId, mStateCallback, null);
                    }

                }catch (Exception ex){ex.printStackTrace();}finally {
                    map=null;
                    Runtime.getRuntime().gc();
                }
            } catch (CameraAccessException e) {
                Toast.makeText(getActivityContext, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
                //getActivityContext.finish();
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();

            } catch (InterruptedException e) {
                e.printStackTrace();
                throw new RuntimeException("Interrupted while trying to lock camera opening.");
            }
        }
</code>```

ConfigureTransform method used for orientation handling

```<code>/*
     * Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`.
     * This method should not to be called until the camera preview size is determined in
     * openCamera, or until the size of `mTextureView` is fixed.
     *
     * @param viewWidth  The width of `mTextureView`
     * @param viewHeight The height of `mTextureView`
     */

private void configureTransform(int viewWidth, int viewHeight) {
    if (null == mTextureView || null == mPreviewSize) {
        return;
    }
    int rotation = getActivityContext.getWindowManager().getDefaultDisplay().getRotation();
    Matrix matrix = new Matrix();
    RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
    RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
    float centerX = viewRect.centerX();
    float centerY = viewRect.centerY();
    if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
        bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
        matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
        float scale = Math.max((float) viewHeight / mPreviewSize.getHeight(),(float) viewWidth / mPreviewSize.getWidth());
        matrix.postScale(scale, scale, centerX, centerY);
        matrix.postRotate(90 * (rotation - 2), centerX, centerY);
    }else if (Surface.ROTATION_0 == rotation) {
        bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
        matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
        float scale=Math.max((float) viewWidth / mPreviewSize.getWidth(), (float) viewHeight / mPreviewSize.getHeight());
        matrix.postScale(scale, scale, centerX, centerY);
        matrix.postRotate(0, centerX, centerY);
    }else if(Surface.ROTATION_180== rotation){
        bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
        matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
        float scale=Math.max((float) viewWidth / mPreviewSize.getWidth(), (float) viewHeight / mPreviewSize.getHeight());
        matrix.postScale(scale, scale, centerX, centerY);
        matrix.postRotate(0, centerX, centerY);
    }
    try {
        mTextureView.setTransform(matrix);
    }catch (Exception ex){ex.printStackTrace();}finally {
        bufferRect=null;
        viewRect=null;
        matrix=null;
    }
}
</code>```

Finally to Start Preview

```<code>private void startPreview() {
        if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
            return;
        }
        try {
            closePreviewSession();
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            //texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            Surface previewSurface = new Surface(texture);
            mPreviewBuilder.addTarget(previewSurface);
            mCameraDevice.createCaptureSession(Collections.singletonList(previewSurface),
                    new CameraCaptureSession.StateCallback() {
                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession session) {
                            mPreviewSession = session;
                            updatePreview();
                        }
                        @Override
                        public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                            Toast.makeText(getActivityContext, "Failed", Toast.LENGTH_SHORT).show();
                        }
                    }, mBackgroundHandler);
            //previewSurface=null;
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
</code>```

Body:
I am using Android Camera API and it works good 16:9 ratio devices on both portrait and landscape modes. But in Samsung S9 18:9 ratio device, on landscape mode the preview looks stretched. On Samsung S9 I got following supported preview sizes, 1920X1080,1440X1080, 1088X1088,1280X720,1056X704, 1024X768, 960X720,800X450,720X720,720X480,640X480,352X288,320X240,256X144,176X144 So optimal preview size is 1920X1080 but actual resolution of device is 2,220 x 1,080. So that it looks stretched.But I need preview on full screen.How default camera preview shows on fullscreen?

@SuppressLint("ClickableViewAccessibility")
    @SuppressWarnings("deprecation")
    public CameraPreview(Context context, Camera.PreviewCallback previewCallback) {
        super(context);
        this.previewCallback = previewCallback;
        mContext = context;
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void setCameraDisplayOrientation(Context activity,
                                            int cameraId, Camera camera) {
        Camera.CameraInfo info =
                new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId, info);
        int rotation = ((AppCompatActivity) activity).getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }

        mDisplayOrientation = result;

        Log.d(TAG, "setCameraDisplayOrientation: "+mDisplayOrientation);

        camera.setDisplayOrientation(result);

    }

    public void takePhoto(final PictureCallback pCalback) {
        mCamera.takePicture(null, null, pCalback);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, acquire the camera and tell it where
        // to draw.
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
            //previewCount = 0;
        }

        try {
            mCamera = Camera.open();

            //setCameraDisplayOrientation(mContext, 0, mCamera);
            /*mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
            int screenWidth = displayMetrics.widthPixels;
            int screenHeight = displayMetrics.heightPixels;
            optimalPreviewSize = getBestAspectPreviewSize(mParameters.getSupportedPreviewSizes(), screenWidth, screenHeight);//Bug Fix for Samsung A8
            mParameters.setPreviewSize(optimalPreviewSize.width, optimalPreviewSize.height);
            mParameters.setPictureSize(optimalPreviewSize.width, optimalPreviewSize.height);
            mParameters.setPreviewFpsRange(30000, 30000);
            mCamera.setParameters(mParameters);*/
            /*mCamera.setPreviewDisplay(holder);
            mCamera.setPreviewCallback(previewCallback);*/

            mCamera.setPreviewDisplay(holder);
        } catch (IOException exception) {
            mCamera.release();
            mCamera = null;
            //previewCount = 0;
        } catch (Exception exception) {
            mCamera = null;
            //previewCount = 0;
        }

        if (mCameraPreviewListener != null) {
            mCameraPreviewListener.onCameraSurfaceCreated();
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
            //previewCount = 0;
        }
        if (mCameraPreviewListener != null) {
            mCameraPreviewListener.onCameraSurfaceDestroyed();
        }
    }

    public void stopCamera() {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
            //previewCount = 0;
        }
    }

    @SuppressWarnings("null")
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        try {
            // Now that the size is known, set up the camera parameters and begin
            // the preview.
            mParameters = mCamera.getParameters();

            Log.d("CameraFix", "parameters -> " + mParameters.flatten());

            setCameraDisplayOrientation(mContext, 0, mCamera);

            mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);

            //Size optimalPreviewSize = getOptimalPreviewSize(mParameters.getSupportedPreviewSizes(), getWidth(), getHeight());
            DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
            int screenWidth = displayMetrics.widthPixels;
            int screenHeight = displayMetrics.heightPixels;

            //Size optimalPreviewSize = getOptimalPreviewSize(mParameters.getSupportedPreviewSizes(), screenWidth, screenHeight, getHeight());
            mSupportedPreviewSizes = mParameters.getSupportedPreviewSizes();
            optimalPreviewSize = getBestAspectPreviewSize(mParameters.getSupportedPreviewSizes(), screenWidth, screenHeight);//Bug Fix for Samsung A8

            Log.d("CameraFix", "optimalPreviewSize.width -> " + optimalPreviewSize.width);
            Log.d("CameraFix", "optimalPreviewSize.height -> " + optimalPreviewSize.height);

            mParameters.setPreviewSize(optimalPreviewSize.width, optimalPreviewSize.height);
            mParameters.setPictureSize(optimalPreviewSize.width, optimalPreviewSize.height);
            mParameters.setPreviewFpsRange(30000, 30000);

            /*if (mDisplayOrientation == 0 || mDisplayOrientation == 180) {
                setLayoutParams(new FrameLayout.LayoutParams(optimalPreviewSize.width, optimalPreviewSize.height,Gravity.CENTER));
            }*/

            Log.d("CameraFix", "setPreviewFpsRange");

            mCamera.setParameters(mParameters);

            mCamera.setPreviewDisplay(holder);

            //SurfaceTexture st = new SurfaceTexture(10);
            //mCamera.setPreviewTexture(st);
            mCamera.setPreviewCallback(previewCallback);
            mCamera.startPreview();
            Log.d("CameraFix", "start preview");
            if (mCameraPreviewListener != null) {
                mCameraPreviewListener.onCameraSurfaceChanged();
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.d("CameraFix", e.toString());
        }

    }

public void toggleFlash(boolean flashModeOn) {
        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
            Parameters parameters = mCamera.getParameters();
            if (flashModeOn) {
                //parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
                parameters.setFlashMode(Parameters.FLASH_MODE_ON);
                mCamera.setParameters(parameters);
                mCamera.startPreview();
                //Toast.makeText(mContext, R.string.flash_mode_on, Toast.LENGTH_SHORT).show();
            } else {
                parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
                mCamera.setParameters(parameters);
                //Toast.makeText(mContext, R.string.flash_mode_off, Toast.LENGTH_SHORT).show();
            }

        } else {
            Toast.makeText(mContext, R.string.flash_not_available, Toast.LENGTH_SHORT).show();
        }
    }

/**
     * Source for this solution - https://stackoverflow.com/questions/21354313/camera-preview-quality-in-android-is-poor/21354442#21354442
     *
     * @param supportedPreviewSizes
     * @param screenWidth
     * @param screenHeight
     * @return
     */
    private Size getBestAspectPreviewSize(List<Size> supportedPreviewSizes, int screenWidth, int screenHeight) {
        double targetRatio = (double) screenWidth / screenHeight;
        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        for (int i = 0; i < supportedPreviewSizes.size(); i++) {
            Size size = supportedPreviewSizes.get(i);
            Log.d(TAG, "getBestAspectPreviewSize: supportedPreviewSizes -> "+size.width +"X"+size.height);
        }

        Log.d(TAG, "getBestAspectPreviewSize: supportedPreviewSizes -> "+supportedPreviewSizes.toString());
        Log.d(TAG, "getBestAspectPreviewSize: mDisplayOrientation -> "+mDisplayOrientation);

        if (mDisplayOrientation == 90 || mDisplayOrientation == 270) {
            Log.d(TAG, "getBestAspectPreviewSize: inside 90 - 270 ");
            targetRatio = (double) screenHeight / screenWidth;
        }

        Log.d(TAG, "getBestAspectPreviewSize: targetRatio -> "+targetRatio);

        Collections.sort(supportedPreviewSizes,
                Collections.reverseOrder(new SizeComparator()));

        for (Size size : supportedPreviewSizes) {
            double ratio = (double) size.width / size.height;

            if (Math.abs(ratio - targetRatio) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(ratio - targetRatio);
            }

            if (minDiff < 0.0d) {
                break;
            }
        }
        return (optimalSize);

        /*if (mDisplayOrientation == 0 || mDisplayOrientation == 180) {
            if (optimalSize != null) {
                return mCamera.new Size(optimalSize.height, optimalSize.width);
            } else {
                return null;
            }
        }
        else{
            return (optimalSize);
        }*/

        //return mCamera.new Size(2220,1080);
    }

    public int getDisplayOrientation() {
        return mDisplayOrientation;
    }

    public void setDisplayOrientation(int displayOrientation) {
        this.mDisplayOrientation = displayOrientation;
    }

    public Parameters getCameraParameters() {
        return mCamera.getParameters();
    }

public void setCameraPreviewListener(CameraPreviewListener cameraPreviewListener) {
        mCameraPreviewListener = cameraPreviewListener;
    }

    public interface CameraPreviewListener {
        void onCameraSurfaceCreated();

        void onCameraSurfaceChanged();

        void onCameraSurfaceDestroyed();

        void onCameraPreviewStarted();
    }

    private static class SizeComparator implements
            Comparator<Size> {
        @Override
        public int compare(Size lhs, Size rhs) {
            int left = lhs.width * lhs.height;
            int right = rhs.width * rhs.height;

            if (left < right) {
                return (-1);
            } else if (left > right) {
                return (1);
            }

            return (0);
        }
    }

Body:
Please take look into my answer hope it will help, I resolved the stretch issue by the following code, method name might change. I share my implementation, Because I know how hard to implement camera in Android, So please don't hesitate to see the following section.

Invoke loadCamera method in ButtonAction.

private void loadCamera() {
        if (CommonUtils.deviceHasCamera(getActivityContext)) {
            startBackgroundThread();
            mCameraTimeOut=(isPermissionGranted?2500:5000);
            if (mTextureView.isAvailable()) {
                openCamera(mTextureView.getWidth(), mTextureView.getHeight());
            } else {
                mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
            }
        }else{
            ShowToastUtils.INSTANCE.showCustomToast(getActivityContext, getString(R.string.msg_no_camera));
        }
    }

Initially SurfaceListener Invoked for Camera

private TextureView.SurfaceTextureListener mSurfaceTextureListener
            = new TextureView.SurfaceTextureListener() {

        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture,
                                              int width, int height) {
            mCameraTimeOut=(isPermissionGranted?2500:5000);
            Log.e(TAG1, "chooseOptimalSize"+"-SurfaceTextureListener ---=>Width---=>"+width);
            Log.e(TAG1, "chooseOptimalSize"+"-SurfaceTextureListener ---=>Height---=>"+height);
            openCamera(width, height);
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture,
                                                int width, int height) {
            configureTransform(width, height);
        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
            return true;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {}

    };

To Choose Optimal Preview Size for Texture

//Samsung-S6-choices[0]
//Samsung-S7-edge-choices[6]
//OnePlus-5T-choices[15]
/*Following is used for Camera Preview in TextureView,  based on device camera resolution*/
    /*
     * Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
     * width and height are at least as large as the respective requested values, and whose aspect
     * ratio matches with the specified value.
     *
     * @param choices     The list of sizes that the camera supports for the intended output class
     * @param width       The minimum desired width
     * @param height      The minimum desired height
     * @param aspectRatio The aspect ratio
     * @return The optimal {@code Size}, or an arbitrary one if none were big enough
     */

     private  Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
        // Collect the supported resolutions that are at least as big as the preview Surface

        int loopCounter=0;
        Log.e(TAG1, "Screen-->Width x Height="+screenWidth+" x "+screenHeight);
        for (Size size : choices) {
            Log.e(TAG1, "chooseOptimalSize:"+size);
        }
        for (Size size : choices) {
            int orientation = getActivityContext.getResources().getConfiguration().orientation;
            if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                if((size.getWidth()/16) == (size.getHeight()/9) && size.getWidth() <=7680 ) {//8K UHDTV Super Hi-Vision
                    Log.e(TAG1, "chooseOptimalSize:"+size.getWidth()+"x"+size.getHeight()+"--LoopPosition---==>"+loopCounter);
                    return size;
                }
            } else {
                Log.e(TAG1, "chooseOptimalSize:--given--"+size);
                if((size.getWidth()/16) == (size.getHeight()/9) && ((size.getWidth() <=1280)||(size.getHeight()<=1920))) {
                    mCameraRatio=RATIO_16_9;
                    Log.e(TAG1, "chooseOptimalSize:"+size.getWidth()+"x"+size.getHeight()+"-16:9"+"--LoopPosition---==>"+loopCounter);
                    return size;
                }else if((size.getWidth()/18) == (size.getHeight()/9) && ((size.getWidth() <=2160)||(size.getHeight()<=3840))) {
                    mCameraRatio=RATIO_18_9;
                    Log.e(TAG1, "chooseOptimalSize:"+size.getWidth()+"x"+size.getHeight()+"-18:9"+"--LoopPosition---==>"+loopCounter);
                    return size;
                }else if((size.getWidth()/18.5) == (size.getHeight()/9) && ((size.getWidth() <=2160)||(size.getHeight()<=3840))) {
                    mCameraRatio=RATIO_18_9;
                    Log.e(TAG1, "chooseOptimalSize:"+size.getWidth()+"x"+size.getHeight()+"-18.5:9"+"--LoopPosition---==>"+loopCounter);
                    return size;
                }else if((width/19) == (height/9) && ((width <=2208)||(height<=3216))) {
                    mCameraRatio=RATIO_19_9;
                    Log.e(TAG1, "chooseOptimalSize:"+size.getWidth()+"x"+size.getHeight()+"-19:9"+"--LoopPosition---==>"+loopCounter);
                    return size;
                }else if((size.getWidth()/19.5) == (size.getHeight()/9) && ((size.getWidth() <=3840)||(size.getHeight()<=2160))) {
                    mCameraRatio=RATIO_19_9;
                    Log.e(TAG1, "chooseOptimalSize:"+size.getWidth()+"x"+size.getHeight()+"-19.5:9"+"--LoopPosition---==>"+loopCounter);
                    return size;
                }else{
                    Log.e(TAG1, "chooseOptimalSize"+" not proper aspect resolution");
                }
            }
                  loopCounter++;
        }
}

To Open Camera

    private void openCamera(int width, int height) {
                CameraManager manager = (CameraManager) getActivityContext.getSystemService(Context.CAMERA_SERVICE);
                try {
                    Log.e(TAG, "tryAcquire");
                    if (!mCameraOpenCloseLock.tryAcquire(mCameraTimeOut, TimeUnit.MILLISECONDS)) {
                        throw new RuntimeException("Time out waiting to lock camera opening.");
                    }
                    String mCameraId = manager.getCameraIdList()[cameraId];
                    // Choose the sizes for camera preview and video recording
                    characteristics = manager.getCameraCharacteristics(mCameraId);
                    StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                    try {
                        mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
                        maximumZoomLevel = characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);
                        if (map == null) {
                            throw new RuntimeException("Cannot get available preview/video sizes");
                        }
                        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
    /*This Line will configure the Texture size*/
                        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);

int orientation = getResources().getConfiguration().orientation;
                    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                        Log.e(TAG1, "Width" + mPreviewSize.getWidth() + "X Height" + mPreviewSize.getHeight());
                        mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
                    } else {
                        Log.e(TAG1, "Width" + mPreviewSize.getHeight() + "X Height" + mPreviewSize.getWidth());
                        mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
    //S10 preview Size
                        /* mTextureView.setAspectRatio(1080, 2280);*/
                        //mTextureView.setAspectRatio(2208, 2944);
                    }
                    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                        configureTransform(width, height);
                    }

                    if (isPermissionGranted) {
                        manager.openCamera(mCameraId, mStateCallback, null);
                    }

                }catch (Exception ex){ex.printStackTrace();}finally {
                    map=null;
                    Runtime.getRuntime().gc();
                }
            } catch (CameraAccessException e) {
                Toast.makeText(getActivityContext, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
                //getActivityContext.finish();
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();

            } catch (InterruptedException e) {
                e.printStackTrace();
                throw new RuntimeException("Interrupted while trying to lock camera opening.");
            }
        }

ConfigureTransform method used for orientation handling

/*
     * Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`.
     * This method should not to be called until the camera preview size is determined in
     * openCamera, or until the size of `mTextureView` is fixed.
     *
     * @param viewWidth  The width of `mTextureView`
     * @param viewHeight The height of `mTextureView`
     */

private void configureTransform(int viewWidth, int viewHeight) {
    if (null == mTextureView || null == mPreviewSize) {
        return;
    }
    int rotation = getActivityContext.getWindowManager().getDefaultDisplay().getRotation();
    Matrix matrix = new Matrix();
    RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
    RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
    float centerX = viewRect.centerX();
    float centerY = viewRect.centerY();
    if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
        bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
        matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
        float scale = Math.max((float) viewHeight / mPreviewSize.getHeight(),(float) viewWidth / mPreviewSize.getWidth());
        matrix.postScale(scale, scale, centerX, centerY);
        matrix.postRotate(90 * (rotation - 2), centerX, centerY);
    }else if (Surface.ROTATION_0 == rotation) {
        bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
        matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
        float scale=Math.max((float) viewWidth / mPreviewSize.getWidth(), (float) viewHeight / mPreviewSize.getHeight());
        matrix.postScale(scale, scale, centerX, centerY);
        matrix.postRotate(0, centerX, centerY);
    }else if(Surface.ROTATION_180== rotation){
        bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
        matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
        float scale=Math.max((float) viewWidth / mPreviewSize.getWidth(), (float) viewHeight / mPreviewSize.getHeight());
        matrix.postScale(scale, scale, centerX, centerY);
        matrix.postRotate(0, centerX, centerY);
    }
    try {
        mTextureView.setTransform(matrix);
    }catch (Exception ex){ex.printStackTrace();}finally {
        bufferRect=null;
        viewRect=null;
        matrix=null;
    }
}

Finally to Start Preview

private void startPreview() {
        if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
            return;
        }
        try {
            closePreviewSession();
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            //texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            Surface previewSurface = new Surface(texture);
            mPreviewBuilder.addTarget(previewSurface);
            mCameraDevice.createCaptureSession(Collections.singletonList(previewSurface),
                    new CameraCaptureSession.StateCallback() {
                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession session) {
                            mPreviewSession = session;
                            updatePreview();
                        }
                        @Override
                        public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                            Toast.makeText(getActivityContext, "Failed", Toast.LENGTH_SHORT).show();
                        }
                    }, mBackgroundHandler);
            //previewSurface=null;
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }


来源: stackexchange

问:
SQL Grouping with Multiple Column Criteria
I have a table like below. GiverID and TakerID are both foreign keys to another table, say Person Table. GiverID and TakerID won't be same within a row.

```<code>ID  GiverPersonID  TakerPersonID  Amount
 1              1              3     100
 2              2              1     200
 3              2              3     400
 4              3              2     800
</code>```

The first row for that table means that Person with ID 1 gives 100 to Person with ID 3.

I need a query to get the result like below

```<code>PersonID     TotalAmount
       1             100
       2             200
       3            -300
</code>```

Basically, computing the final amount of each person.
For person with ID 1, he gives 100 to person with ID 3, but take 200 from person with ID 2, so his final amount is 200 - 100, which is 100.

I've reading about pivoting, but I think pivoting is not the correct step.

What is the efficient SQL to calculate that result?

答:
If you wanted all people -- not just those who are in the table -- then you can try:

```<code>select p.*,
       (select sum(case when p.PersonId = t.GiverPersonID then t.amount else - t.amount end)
        from t
        where p.PersonId in (t.GiverPersonID, t.takerPersonID)
       ) as net_amount
from persons;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a table like below. GiverID and TakerID are both foreign keys to another table, say Person Table. GiverID and TakerID won't be same within a row.

ID  GiverPersonID  TakerPersonID  Amount
 1              1              3     100
 2              2              1     200
 3              2              3     400
 4              3              2     800

The first row for that table means that Person with ID 1 gives 100 to Person with ID 3.

I need a query to get the result like below

PersonID     TotalAmount
       1             100
       2             200
       3            -300

Basically, computing the final amount of each person.
For person with ID 1, he gives 100 to person with ID 3, but take 200 from person with ID 2, so his final amount is 200 - 100, which is 100.

I've reading about pivoting, but I think pivoting is not the correct step.

What is the efficient SQL to calculate that result?

Body:
If you wanted all people -- not just those who are in the table -- then you can try:

select p.*,
       (select sum(case when p.PersonId = t.GiverPersonID then t.amount else - t.amount end)
        from t
        where p.PersonId in (t.GiverPersonID, t.takerPersonID)
       ) as net_amount
from persons;


问:
How to add objects into an array of reducer?
I need to add objects from Actions to the Reducers Array. For the first time, the value is added to the reducer. When I dispatch the action again, it's overriding the existing value in the array with the object.

check the below code:

Action:

```<code>let itemImgObj = {
  itemid: "",
  itemimgurl: ""
};
export const setItemsImages = (itemid, itemimgurl) => {
  itemImgObj.itemid = itemid;
  itemImgObj.itemimgurl = itemimgurl;
  console.log("as", itemImgObj);
  return {
    type: 'SET_ITEMS_IMAGES',
    itemImgObj
  };
};
</code>```

Reducer:

```<code>const Reducer = (state = { cartItemsImages= [] }, action) => {
  console.log(action);
  switch (action.type) {
    case 'SET_ITEMS_IMAGES':
      return {
        ...state,
        cartItemsImages: [...state.cartItemsImages, action.itemImgObj]
      };
    default:
      return state;
  }
};
</code>```

How to update the array value with the object from the action on every dispatch?

答:
The reason is that you always set the value of state to cartItemsImages of an empty array. So whenever the reducer is called, the value of your state is always an empty array, that why it overrided the existing value instead of append new one.

You can do the following code:

```<code>// declare a new const which contains your cartItemsImages
const initialSate = {
   cartItemsImages: []
};

const Reducer = (state = initialSate, action) => {
  console.log(action);
  switch (action.type) {
    case 'SET_ITEMS_IMAGES':
      return {
        ...state,
        cartItemsImages: [...state.cartItemsImages, action.itemImgObj]
      };
    default:
      return state;
  }
};
</code>```

Body:
I need to add objects from Actions to the Reducers Array. For the first time, the value is added to the reducer. When I dispatch the action again, it's overriding the existing value in the array with the object.

check the below code:

Action:

let itemImgObj = {
  itemid: "",
  itemimgurl: ""
};
export const setItemsImages = (itemid, itemimgurl) => {
  itemImgObj.itemid = itemid;
  itemImgObj.itemimgurl = itemimgurl;
  console.log("as", itemImgObj);
  return {
    type: 'SET_ITEMS_IMAGES',
    itemImgObj
  };
};

Reducer:

const Reducer = (state = { cartItemsImages= [] }, action) => {
  console.log(action);
  switch (action.type) {
    case 'SET_ITEMS_IMAGES':
      return {
        ...state,
        cartItemsImages: [...state.cartItemsImages, action.itemImgObj]
      };
    default:
      return state;
  }
};

How to update the array value with the object from the action on every dispatch?

Body:
The reason is that you always set the value of state to cartItemsImages of an empty array. So whenever the reducer is called, the value of your state is always an empty array, that why it overrided the existing value instead of append new one.

You can do the following code:

// declare a new const which contains your cartItemsImages
const initialSate = {
   cartItemsImages: []
};

const Reducer = (state = initialSate, action) => {
  console.log(action);
  switch (action.type) {
    case 'SET_ITEMS_IMAGES':
      return {
        ...state,
        cartItemsImages: [...state.cartItemsImages, action.itemImgObj]
      };
    default:
      return state;
  }
};


问:
What's the fastest way to test the validity of a large number of well-formed URLs
My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs

I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).

Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.

Can it be done?

答:
This is a trivial case for twisted.  There are a couple of concurrency tools you can use to slow it down, otherwise, it'll pretty much do it all at once.

Twisted is definitely my favorite thing about python.  :)

OwnerDisplayName: Salim Fadhley

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Dustin


问:
Black berry camera programming
I want take pictures using black berry camera for my app, it is possible in v5.0 and yes then how?</p>

答:
Yes it is definitely possible, but not a very simple task if you don't get some advice up front.

First and foremost, there is some sample code that is shipped with the Eclipse package at least (CameraDemo) that shows how to create a viewfiender using a Field, Player, and VideoScreen. The biggest issue is third party developers cannot overlay anything on top of the view finder (which is the what they'll call the Field after you set it as such with a VideoControl.

Also, you are very limited to what size you can set the Field -- I only got half size and fullscreen working, some dimensions got ignored and others caused it to not be displayed at all.

Here is some code that shows this:

```<code>private Field _videoField;
private Player _player;
private VideoControl _videoControl;

private void initCamera() {
        try{
            _player = Manager.createPlayer( "capture://video??encoding=jpeg&width=640&height=480" );
            _player.realize();
            _player.prefetch();
            _videoControl = (VideoControl)_player.getControl("VideoControl");
            _player.start();
            if (_videoControl != null){

                _videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
                _videoControl.setDisplayFullScreen(true);
                add(_videoField);
            }
        }
        catch(Exception e)
        {
           //show error
        }
    }
</code>```

After you do this you can use

```<code>            byte[] image = _videoControl.getSnapshot(sizeAndEncodingParamters);
</code>```

to snap the picture. To determine what sizeAndEncodingParameters your device supports, you can use System.getProperty("video.snapshot.encodings"); which will return a String[] that you can iterate over to determine what to use.

ContentLicense: CC BY-SA 3.0

Title: Black berry camera programming

Body:
Yes it is definitely possible, but not a very simple task if you don't get some advice up front.

First and foremost, there is some sample code that is shipped with the Eclipse package at least (CameraDemo) that shows how to create a viewfiender using a Field, Player, and VideoScreen. The biggest issue is third party developers cannot overlay anything on top of the view finder (which is the what they'll call the Field after you set it as such with a VideoControl.

Also, you are very limited to what size you can set the Field -- I only got half size and fullscreen working, some dimensions got ignored and others caused it to not be displayed at all.

Here is some code that shows this:

private Field _videoField;
private Player _player;
private VideoControl _videoControl;

private void initCamera() {
        try{
            _player = Manager.createPlayer( "capture://video??encoding=jpeg&width=640&height=480" );
            _player.realize();
            _player.prefetch();
            _videoControl = (VideoControl)_player.getControl("VideoControl");
            _player.start();
            if (_videoControl != null){

                _videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
                _videoControl.setDisplayFullScreen(true);
                add(_videoField);
            }
        }
        catch(Exception e)
        {
           //show error
        }
    }

After you do this you can use

            byte[] image = _videoControl.getSnapshot(sizeAndEncodingParamters);

to snap the picture. To determine what sizeAndEncodingParameters your device supports, you can use System.getProperty("video.snapshot.encodings"); which will return a String[] that you can iterate over to determine what to use.


问:
Parse properties string in an array to For Each loop
I am trying to get information about the battery in my laptop by using VBScript.

It is more properties. I want to parse arrayItems("Name","Availability","BatteryStatus","Chemistry") for each objItem.

For example:

```<code>For iii = 0 To UBound(arrayItems)
    WScript.Echo "Result of iii:" & objItem.arrayItems (iii)
Next
</code>```

I do not want to enter manually as "Availability: " & objItem.Availability, "BatteryStatus: " & objItem.BatteryStatus, ...

```<code>On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_Battery",,48)
For Each objItem In colItems
    WScript.Echo "Name: " & objItem.Name
    WScript.Echo "Availability: " & objItem.Availability
    WScript.Echo "BatteryStatus: " & objItem.BatteryStatus
    WScript.Echo "Chemistry: " & objItem.Chemistry
    WScript.Echo "DesignVoltage: " & objItem.DesignVoltage
    WScript.Echo "EstimatedChargeRemaining: " & objItem.EstimatedChargeRemaining
    WScript.Echo "Status: " & objItem.Status
Next
</code>```

答:
What you want can be done via the object's properties_ property set:

```<code>arrayItems = Array("Name", "Availability", "BatteryStatus", "Chemistry")
For Each objItem In colItems
    For Each name In arrayItems
        WScript.Echo name & ": " & objItem.properties_(name)
    Next
Next
</code>```

Body:
I am trying to get information about the battery in my laptop by using VBScript.

It is more properties. I want to parse arrayItems("Name","Availability","BatteryStatus","Chemistry") for each objItem.

For example:

For iii = 0 To UBound(arrayItems)
    WScript.Echo "Result of iii:" & objItem.arrayItems (iii)
Next

I do not want to enter manually as "Availability: " & objItem.Availability, "BatteryStatus: " & objItem.BatteryStatus, ...

On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_Battery",,48)
For Each objItem In colItems
    WScript.Echo "Name: " & objItem.Name
    WScript.Echo "Availability: " & objItem.Availability
    WScript.Echo "BatteryStatus: " & objItem.BatteryStatus
    WScript.Echo "Chemistry: " & objItem.Chemistry
    WScript.Echo "DesignVoltage: " & objItem.DesignVoltage
    WScript.Echo "EstimatedChargeRemaining: " & objItem.EstimatedChargeRemaining
    WScript.Echo "Status: " & objItem.Status
Next

Body:
What you want can be done via the object's properties_ property set:

arrayItems = Array("Name", "Availability", "BatteryStatus", "Chemistry")
For Each objItem In colItems
    For Each name In arrayItems
        WScript.Echo name & ": " & objItem.properties_(name)
    Next
Next


问:
Create a record in Google contacts
I am trying to send a post request to create a record in Google contacts from my app and I am sending the "name" field in the request body as below.

```<code>-(void)exportGoogleContact:(NSString*)name {

CLNetworkDataModel *dataModel = [[CLNetworkDataModel alloc] init];
dataModel.httpMethod = eNetworkOperationTypePost;

NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *token = [data stringForKey:@"Accesstoken"];
NSLog(@"token is %@",token);

dataModel.apiUrl = [NSString stringWithFormat:@"https://people.googleapis.com/v1/people:createContact?access_token=%@",token];
NSString * requestString = [NSString stringWithFormat:@"name=%@",name];

dataModel.requestParams = requestString;
CLNetworkOperation *uuidOperation = [CLNetworkOperation operationForTarget:self callBackSelector:@selector(exportGoogleReponseData:)
                                                                 dataModel:dataModel];

[[CLGlobalNetworkQueue sharedInstance] addOperation:uuidOperation];
  }
</code>```

I am getting the following error message:

```<code> {
 "error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"name\":
  Cannot bind query parameter. Field 'name' could not be found in
request message.",
"status": "INVALID_ARGUMENT",
"details": [
  {
    "@type": "type.googleapis.com/google.rpc.BadRequest",
    "fieldViolations": [
      {
        "description": "Invalid JSON payload received. Unknown name \"name\": Cannot bind query parameter. Field 'name' could not be found in request message."
      }
    ]
  }
]
         }
 }
</code>```

Anyone have idea, how to fix the this error, Thanks in advance

答:
Here is the full code which is working fine for me

```<code> // Export to Google contacts

 -(void)exportGoogleContact:(NSString*)name mobile:(NSString *)mobile phone:
 (NSString *)phone email:(NSString*)email company:(NSString *)company
 designation:
 (NSString *)designation website:(NSString *)website address:(NSString
 *)address
 notes:(NSString*)notes {
CLNetworkDataModel *dataModel = [[CLNetworkDataModel alloc] init];
dataModel.httpMethod = eNetworkOperationTypePostJson;
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *token = [data stringForKey:@"Accesstoken"];
NSLog(@"token is %@",token);

NSMutableDictionary * reqDict = [[NSMutableDictionary alloc] init];
[reqDict setObject:name forKey:@"Name"];
[reqDict setObject:mobile forKey:@"MobileValue"];

[reqDict setObject:phone forKey:@"PhoneValue"];

[reqDict setObject:email forKey:@"EmailValue"];
[reqDict setObject:company forKey:@"CompanyValue"];
[reqDict setObject:designation forKey:@"DesignasionValue"];
[reqDict setObject:website forKey:@"WebsiteValue"];
[reqDict setObject:address forKey:@"AddressValue"];

if([notes  isEqual: @""]){

    notes = @"Added through APPName";
}

[reqDict setObject:notes forKey:@"NotesValue"];

    dataModel.apiUrl = [NSString
stringWithFormat:@"https://people.googleapis.com/v1/people:createContact?
access_token=%@",token];
//NSString * requestString = [NSString stringWithFormat:@"name=%@",name];
NSString *requestString = [CLUtils createJsonContentForGoogleSync:reqDict];
dataModel.requestParams = requestString;
CLNetworkOperation *uuidOperation = [CLNetworkOperation operationForTarget:self
callBackSelector:@selector(exportGoogleReponseData:)

dataModel:dataModel];

[[CLGlobalNetworkQueue sharedInstance] addOperation:uuidOperation];
}
</code>```

//Here is the code to create json request

```<code> + (NSString *) createJsonContentForGoogleSync:(NSDictionary *)reqDict{

NSMutableDictionary *phoneDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict2 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict3 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict4= [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict5 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict6 = [[NSMutableDictionary alloc] init];

NSMutableDictionary *companyDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *emailDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *designatioDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *websiteDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *nameDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *mobileDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *addressDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *notesDataDict = [[NSMutableDictionary alloc] init];

[nameDataDict setObject:[reqDict objectForKey:@"Name"] forKey:@"givenName"];
[websiteDataDict setObject:[reqDict objectForKey:@"WebsiteValue"]
forKey:@"value"];
//[designatioDataDict setObject:[reqDict objectForKey:@"DesignasionValue"]
forKey:@"value"];
[emailDataDict setObject:[reqDict objectForKey:@"EmailValue"] forKey:@"value"];
[designatioDataDict setObject:[reqDict objectForKey:@"DesignasionValue"]
forKey:@"title"];
[companyDataDict setObject:[reqDict objectForKey:@"CompanyValue"]
forKey:@"name"];

[mobileDataDict setObject:[reqDict objectForKey:@"MobileValue"]
forKey:@"value"];
[mobileDataDict setObject:@"mobile" forKey:@"type"];

[phoneDataDict setObject:[reqDict objectForKey:@"PhoneValue"] forKey:@"value"];
[phoneDataDict setObject:@"work" forKey:@"type"];

NSArray *companyArry;
if(![[companyDataDict objectForKey:@"name"]  isEqual: @""]){
companyArry = [NSArray arrayWithObjects:companyDataDict,
designatioDataDict,nil];
}

else{

    [companyDataDict setObject:@" " forKey:@"name"];
    companyArry = [NSArray arrayWithObjects:companyDataDict,
designatioDataDict,nil];

}
NSArray *phoneNosArry;
phoneNosArry = [NSArray arrayWithObjects:mobileDataDict,phoneDataDict,nil];

if([reqDict.allKeys containsObject:@"PhoneValue2"]){
    [phoneDataDict2 setObject:[reqDict objectForKey:@"PhoneValue2"]
forKey:@"value"];
    [phoneDataDict2 setObject:@"work" forKey:@"type"];
    phoneNosArry = [NSArray
arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2 ,nil];

}
if([reqDict.allKeys containsObject:@"PhoneValue3"]){

    [phoneDataDict3 setObject:[reqDict objectForKey:@"PhoneValue3"]
forKey:@"value"];
    [phoneDataDict3 setObject:@"work" forKey:@"type"];
    phoneNosArry = [NSArray
arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2,phoneDataDict3
,nil];

    }

    if([reqDict.allKeys containsObject:@"PhoneValue4"]){
        [phoneDataDict4 setObject:[reqDict objectForKey:@"PhoneValue4"]
forKey:@"value"];
[phoneDataDict4 setObject:@"work" forKey:@"type"];
phoneNosArry = [NSArray

    }
    if([reqDict.allKeys containsObject:@"PhoneValue5"]){
        [phoneDataDict5 setObject:[reqDict objectForKey:@"PhoneValue5"]
forKey:@"value"];
        [phoneDataDict5 setObject:@"work" forKey:@"type"];
        phoneNosArry = [NSArray arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2,phoneDataDict3,phoneDataDict4,phoneDataDict5 ,nil];

    }

        if([reqDict.allKeys containsObject:@"PhoneValue6"]){
        [phoneDataDict6 setObject:[reqDict objectForKey:@"PhoneValue6"] forKey:@"value"];
        [phoneDataDict6 setObject:@"work" forKey:@"type"];

            phoneNosArry = [NSArray arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2,phoneDataDict3,phoneDataDict4,phoneDataDict5,phoneDataDict6 ,nil];

        }
//[phoneDataDict addEntriesFromDictionary:mobileDataDict];
[addressDataDict setObject:[reqDict objectForKey:@"AddressValue"] forKey:@"formattedValue"];
[notesDataDict setObject:[reqDict objectForKey:@"NotesValue"] forKey:@"value"];

[notesDataDict setObject:@"TEXT_PLAIN" forKey:@"contentType"];

NSMutableDictionary *parentDict = [[NSMutableDictionary alloc] init];

[parentDict setObject:nameDataDict forKey:@"names"];
[parentDict setObject:emailDataDict forKey:@"emailAddresses"];
[parentDict setObject:companyArry forKey:@"organizations"];
[parentDict setObject:websiteDataDict forKey:@"urls"];
 // [parentDict setObject:designatioDataDict forKey:@"occupations"];
//[parentDict setObject:phoneDataDict forKey:@"phoneNumbers"];
[parentDict setObject:phoneNosArry forKey:@"phoneNumbers"];
//[parentDict setObject:mobileDataDict forKey:@"phoneNumbers"];
[parentDict setObject:addressDataDict forKey:@"addresses"];
[parentDict setObject:notesDataDict forKey:@"biographies"];
NSData *resultData = [NSJSONSerialization dataWithJSONObject:parentDict
options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString ;
if(resultData != nil){
    jsonString = [[NSString alloc] initWithData:resultData
encoding:NSUTF8StringEncoding];
}
NSLog(@"####### Final json string is %@",jsonString);
return jsonString;

}
</code>```

Title: Create a record in Google contacts

Body:
I am trying to send a post request to create a record in Google contacts from my app and I am sending the "name" field in the request body as below.

-(void)exportGoogleContact:(NSString*)name {

CLNetworkDataModel *dataModel = [[CLNetworkDataModel alloc] init];
dataModel.httpMethod = eNetworkOperationTypePost;

NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *token = [data stringForKey:@"Accesstoken"];
NSLog(@"token is %@",token);

dataModel.apiUrl = [NSString stringWithFormat:@"https://people.googleapis.com/v1/people:createContact?access_token=%@",token];
NSString * requestString = [NSString stringWithFormat:@"name=%@",name];

dataModel.requestParams = requestString;
CLNetworkOperation *uuidOperation = [CLNetworkOperation operationForTarget:self callBackSelector:@selector(exportGoogleReponseData:)
                                                                 dataModel:dataModel];

[[CLGlobalNetworkQueue sharedInstance] addOperation:uuidOperation];
  }

I am getting the following error message:

 {
 "error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"name\":
  Cannot bind query parameter. Field 'name' could not be found in
request message.",
"status": "INVALID_ARGUMENT",
"details": [
  {
    "@type": "type.googleapis.com/google.rpc.BadRequest",
    "fieldViolations": [
      {
        "description": "Invalid JSON payload received. Unknown name \"name\": Cannot bind query parameter. Field 'name' could not be found in request message."
      }
    ]
  }
]
         }
 }

Anyone have idea, how to fix the this error, Thanks in advance

Body:
Here is the full code which is working fine for me

 // Export to Google contacts

 -(void)exportGoogleContact:(NSString*)name mobile:(NSString *)mobile phone:
 (NSString *)phone email:(NSString*)email company:(NSString *)company
 designation:
 (NSString *)designation website:(NSString *)website address:(NSString
 *)address
 notes:(NSString*)notes {
CLNetworkDataModel *dataModel = [[CLNetworkDataModel alloc] init];
dataModel.httpMethod = eNetworkOperationTypePostJson;
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *token = [data stringForKey:@"Accesstoken"];
NSLog(@"token is %@",token);

NSMutableDictionary * reqDict = [[NSMutableDictionary alloc] init];
[reqDict setObject:name forKey:@"Name"];
[reqDict setObject:mobile forKey:@"MobileValue"];

[reqDict setObject:phone forKey:@"PhoneValue"];

[reqDict setObject:email forKey:@"EmailValue"];
[reqDict setObject:company forKey:@"CompanyValue"];
[reqDict setObject:designation forKey:@"DesignasionValue"];
[reqDict setObject:website forKey:@"WebsiteValue"];
[reqDict setObject:address forKey:@"AddressValue"];

if([notes  isEqual: @""]){

    notes = @"Added through APPName";
}

[reqDict setObject:notes forKey:@"NotesValue"];

    dataModel.apiUrl = [NSString
stringWithFormat:@"https://people.googleapis.com/v1/people:createContact?
access_token=%@",token];
//NSString * requestString = [NSString stringWithFormat:@"name=%@",name];
NSString *requestString = [CLUtils createJsonContentForGoogleSync:reqDict];
dataModel.requestParams = requestString;
CLNetworkOperation *uuidOperation = [CLNetworkOperation operationForTarget:self
callBackSelector:@selector(exportGoogleReponseData:)

dataModel:dataModel];

[[CLGlobalNetworkQueue sharedInstance] addOperation:uuidOperation];
}

//Here is the code to create json request

 + (NSString *) createJsonContentForGoogleSync:(NSDictionary *)reqDict{

NSMutableDictionary *phoneDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict2 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict3 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict4= [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict5 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict6 = [[NSMutableDictionary alloc] init];

NSMutableDictionary *companyDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *emailDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *designatioDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *websiteDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *nameDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *mobileDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *addressDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *notesDataDict = [[NSMutableDictionary alloc] init];

[nameDataDict setObject:[reqDict objectForKey:@"Name"] forKey:@"givenName"];
[websiteDataDict setObject:[reqDict objectForKey:@"WebsiteValue"]
forKey:@"value"];
//[designatioDataDict setObject:[reqDict objectForKey:@"DesignasionValue"]
forKey:@"value"];
[emailDataDict setObject:[reqDict objectForKey:@"EmailValue"] forKey:@"value"];
[designatioDataDict setObject:[reqDict objectForKey:@"DesignasionValue"]
forKey:@"title"];
[companyDataDict setObject:[reqDict objectForKey:@"CompanyValue"]
forKey:@"name"];

[mobileDataDict setObject:[reqDict objectForKey:@"MobileValue"]
forKey:@"value"];
[mobileDataDict setObject:@"mobile" forKey:@"type"];

[phoneDataDict setObject:[reqDict objectForKey:@"PhoneValue"] forKey:@"value"];
[phoneDataDict setObject:@"work" forKey:@"type"];

NSArray *companyArry;
if(![[companyDataDict objectForKey:@"name"]  isEqual: @""]){
companyArry = [NSArray arrayWithObjects:companyDataDict,
designatioDataDict,nil];
}

else{

    [companyDataDict setObject:@" " forKey:@"name"];
    companyArry = [NSArray arrayWithObjects:companyDataDict,
designatioDataDict,nil];

}
NSArray *phoneNosArry;
phoneNosArry = [NSArray arrayWithObjects:mobileDataDict,phoneDataDict,nil];

if([reqDict.allKeys containsObject:@"PhoneValue2"]){
    [phoneDataDict2 setObject:[reqDict objectForKey:@"PhoneValue2"]
forKey:@"value"];
    [phoneDataDict2 setObject:@"work" forKey:@"type"];
    phoneNosArry = [NSArray
arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2 ,nil];

}
if([reqDict.allKeys containsObject:@"PhoneValue3"]){

    [phoneDataDict3 setObject:[reqDict objectForKey:@"PhoneValue3"]
forKey:@"value"];
    [phoneDataDict3 setObject:@"work" forKey:@"type"];
    phoneNosArry = [NSArray
arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2,phoneDataDict3
,nil];

    }

    if([reqDict.allKeys containsObject:@"PhoneValue4"]){
        [phoneDataDict4 setObject:[reqDict objectForKey:@"PhoneValue4"]
forKey:@"value"];
[phoneDataDict4 setObject:@"work" forKey:@"type"];
phoneNosArry = [NSArray

    }
    if([reqDict.allKeys containsObject:@"PhoneValue5"]){
        [phoneDataDict5 setObject:[reqDict objectForKey:@"PhoneValue5"]
forKey:@"value"];
        [phoneDataDict5 setObject:@"work" forKey:@"type"];
        phoneNosArry = [NSArray arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2,phoneDataDict3,phoneDataDict4,phoneDataDict5 ,nil];

    }

        if([reqDict.allKeys containsObject:@"PhoneValue6"]){
        [phoneDataDict6 setObject:[reqDict objectForKey:@"PhoneValue6"] forKey:@"value"];
        [phoneDataDict6 setObject:@"work" forKey:@"type"];

            phoneNosArry = [NSArray arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2,phoneDataDict3,phoneDataDict4,phoneDataDict5,phoneDataDict6 ,nil];

        }
//[phoneDataDict addEntriesFromDictionary:mobileDataDict];
[addressDataDict setObject:[reqDict objectForKey:@"AddressValue"] forKey:@"formattedValue"];
[notesDataDict setObject:[reqDict objectForKey:@"NotesValue"] forKey:@"value"];

[notesDataDict setObject:@"TEXT_PLAIN" forKey:@"contentType"];

NSMutableDictionary *parentDict = [[NSMutableDictionary alloc] init];

[parentDict setObject:nameDataDict forKey:@"names"];
[parentDict setObject:emailDataDict forKey:@"emailAddresses"];
[parentDict setObject:companyArry forKey:@"organizations"];
[parentDict setObject:websiteDataDict forKey:@"urls"];
 // [parentDict setObject:designatioDataDict forKey:@"occupations"];
//[parentDict setObject:phoneDataDict forKey:@"phoneNumbers"];
[parentDict setObject:phoneNosArry forKey:@"phoneNumbers"];
//[parentDict setObject:mobileDataDict forKey:@"phoneNumbers"];
[parentDict setObject:addressDataDict forKey:@"addresses"];
[parentDict setObject:notesDataDict forKey:@"biographies"];
NSData *resultData = [NSJSONSerialization dataWithJSONObject:parentDict
options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString ;
if(resultData != nil){
    jsonString = [[NSString alloc] initWithData:resultData
encoding:NSUTF8StringEncoding];
}
NSLog(@"####### Final json string is %@",jsonString);
return jsonString;

}


问:
Do we need to pass only int values for the 'INT' type data in MYSQL select query?
Actually following values are not there in the 'status' column(i.e 1ooo,1ee)" but result is comming. status column is containing only one record that is with the 1.

```<code>QRY-1:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status=1;

QRY-2:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status="1";

QRY-3:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status="1ooo";

QRY-4:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status="1ee";
</code>```

QRY-1:OK

For the above QRY-2,QRY-3,QRY-4 also I'm getting same result?Why?

答:
This happend because the implict convdrsione performed  by SQL  ..  and in each case the firts char (or set of chars ) is valid number </p>

```<code>'1' , '1ooooì, '1ee'   became 1 for implict conversion to destination type
</code>```

<p>all the queries became  </p>

```<code>select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status=1
</code>```

Body:
Actually following values are not there in the 'status' column(i.e 1ooo,1ee)" but result is comming. status column is containing only one record that is with the 1.

QRY-1:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status=1;

QRY-2:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status="1";

QRY-3:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status="1ooo";

QRY-4:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status="1ee";

QRY-1:OK

For the above QRY-2,QRY-3,QRY-4 also I'm getting same result?Why?

Body:
This happend because the implict convdrsione performed  by SQL  ..  and in each case the firts char (or set of chars ) is valid number

'1' , '1ooooì, '1ee'   became 1 for implict conversion to destination type

all the queries became

select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status=1


问:
removing special character from pandas.Series in python?
i'm working on project called financial and in that i got output but i want to remove '-' symbol from my dataframe i tried more please can anyone help me thanks in advance.

my python code:

```<code>import pandas as pd
import numpy as np
from datetime import date
from flask import Flask, request
from flask.json import jsonify

app = Flask(__name__)

@app.route("/sampleCalc", methods=['post'])
def samplecalc():
    interestrate = float(request.json['interest'])
    years = int(request.json['duration'])/12
    paymentsyear = 12
    principal = int(request.json['principal'])
    currentdate = date.today()
    start_date = (date(currentdate.year, currentdate.month, currentdate.day))
    rng = pd.date_range(start_date, periods=years * paymentsyear, freq='MS')
    rng.name = "paymentDate"
    df = pd.DataFrame(index=rng, columns=['payment', 'roundpayment', 'principal', 'roundprincipal', 'interest', 'roundinterest', 'balance'],
                      dtype='float')
    df.reset_index(inplace=True)
    df.index += 1
    df.index.name = "Period"
    df["payment"] = np.pmt(interestrate / paymentsyear, years * paymentsyear, principal)
    df['roundpayment'] = round(df['payment'])
    df["principal"] = np.ppmt(interestrate / paymentsyear, df.index, years * paymentsyear, principal)
    df['roundprincipal'] = round(df['principal'])
    df["interest"] = np.ipmt(interestrate / paymentsyear, df.index, years * paymentsyear, principal)
    df['roundinterest'] = round(df['interest'])
    df = df.round(2)
    df["balance"] = 0
    df.loc[1, "balance"] = principal + df.loc[1, "principal"]
    for i in range(2, len(df) + 1):
        prev_balance = df.ix[i - 1, 'balance']
        principal = df.ix[i, 'principal']

        if prev_balance == 0:
            df.ix[i, ['payment', 'roundpayment', 'principal', 'roundprincipal', 'interest', 'roundinterest', 'balance']] = 0
            continue
        if abs(principal) <= prev_balance:
            df.ix[i, 'balance'] = principal + prev_balance

        else:

            if prev_balance <= abs(principal):
                principal = -prev_balance
                # addl_principal = 0
            else:
                print('else')
            df.ix[i, 'balance'] = 0
            df.ix[i, 'principal'] = principal
            df.ix[i, "payment"] = principal + df.ix[i, "interest"]
    df = df.round(2)
    d = [{k: df.values[i][v] for v, k in enumerate(df.columns)} for i in range(len(df))]
    return jsonify({"data": d})

if __name__ == '__main__':
    app.run(debug=True)
</code>```

This is my code from this will get the emi calculation based on principal amount and interest and duration below i mentioned my input by using that input will get the output like this

```<code>{
    "data": [
        {
            "balance": 100414.94,
            "interest": -1666.67,
            "payment": -101251.73,
            "paymentDate": "Sat, 01 Jun 2019 00:00:00 GMT",
            "principal": -99585.06,
            "roundinterest": -1667,
            "roundpayment": -101252,
            "roundprincipal": -99585
        },
        {
            "balance": 0,
            "interest": -836.79,
            "payment": -101251.73,
            "paymentDate": "Mon, 01 Jul 2019 00:00:00 GMT",
            "principal": -100414.94,
            "roundinterest": -837,
            "roundpayment": -101252,
            "roundprincipal": -100415
        }
    ]
}
</code>```

my input is

```<code>{
    "principal":200000,
    "interest":0.10,
    "duration":2
}
</code>```

i want to remove - symbol from the output.

答:
If you want to keep the Dataframe in tact but just affect the JSON output, then get the absolute value of the number when you create the dict that you jsonify.

```<code># d = [{k: df.values[i][v] for v, k in enumerate(df.columns)} for i in range(len(df))]
d = df.to_dict("records")

keys_to_change = ["principal", "interest"]   # add whatever keys you want here

for record in d:
    for key in keys_to_change:
        record[key] = abs(record[key])

json_data = jsonify({"data": d})
</code>```

To do this for dynamically all numeric values:

```<code>from pandas.api.types import is_numeric_dtype
#...
for record in d:
    for key in record.keys():
        if pd.api.types.is_number(record[key]:
            record[key] = abs(record[key])
</code>```

Body:
i'm working on project called financial and in that i got output but i want to remove '-' symbol from my dataframe i tried more please can anyone help me thanks in advance.

my python code:

import pandas as pd
import numpy as np
from datetime import date
from flask import Flask, request
from flask.json import jsonify

app = Flask(__name__)

@app.route("/sampleCalc", methods=['post'])
def samplecalc():
    interestrate = float(request.json['interest'])
    years = int(request.json['duration'])/12
    paymentsyear = 12
    principal = int(request.json['principal'])
    currentdate = date.today()
    start_date = (date(currentdate.year, currentdate.month, currentdate.day))
    rng = pd.date_range(start_date, periods=years * paymentsyear, freq='MS')
    rng.name = "paymentDate"
    df = pd.DataFrame(index=rng, columns=['payment', 'roundpayment', 'principal', 'roundprincipal', 'interest', 'roundinterest', 'balance'],
                      dtype='float')
    df.reset_index(inplace=True)
    df.index += 1
    df.index.name = "Period"
    df["payment"] = np.pmt(interestrate / paymentsyear, years * paymentsyear, principal)
    df['roundpayment'] = round(df['payment'])
    df["principal"] = np.ppmt(interestrate / paymentsyear, df.index, years * paymentsyear, principal)
    df['roundprincipal'] = round(df['principal'])
    df["interest"] = np.ipmt(interestrate / paymentsyear, df.index, years * paymentsyear, principal)
    df['roundinterest'] = round(df['interest'])
    df = df.round(2)
    df["balance"] = 0
    df.loc[1, "balance"] = principal + df.loc[1, "principal"]
    for i in range(2, len(df) + 1):
        prev_balance = df.ix[i - 1, 'balance']
        principal = df.ix[i, 'principal']

        if prev_balance == 0:
            df.ix[i, ['payment', 'roundpayment', 'principal', 'roundprincipal', 'interest', 'roundinterest', 'balance']] = 0
            continue
        if abs(principal) <= prev_balance:
            df.ix[i, 'balance'] = principal + prev_balance

        else:

            if prev_balance <= abs(principal):
                principal = -prev_balance
                # addl_principal = 0
            else:
                print('else')
            df.ix[i, 'balance'] = 0
            df.ix[i, 'principal'] = principal
            df.ix[i, "payment"] = principal + df.ix[i, "interest"]
    df = df.round(2)
    d = [{k: df.values[i][v] for v, k in enumerate(df.columns)} for i in range(len(df))]
    return jsonify({"data": d})

if __name__ == '__main__':
    app.run(debug=True)

This is my code from this will get the emi calculation based on principal amount and interest and duration below i mentioned my input by using that input will get the output like this

{
    "data": [
        {
            "balance": 100414.94,
            "interest": -1666.67,
            "payment": -101251.73,
            "paymentDate": "Sat, 01 Jun 2019 00:00:00 GMT",
            "principal": -99585.06,
            "roundinterest": -1667,
            "roundpayment": -101252,
            "roundprincipal": -99585
        },
        {
            "balance": 0,
            "interest": -836.79,
            "payment": -101251.73,
            "paymentDate": "Mon, 01 Jul 2019 00:00:00 GMT",
            "principal": -100414.94,
            "roundinterest": -837,
            "roundpayment": -101252,
            "roundprincipal": -100415
        }
    ]
}

my input is

{
    "principal":200000,
    "interest":0.10,
    "duration":2
}

i want to remove - symbol from the output.

Body:
If you want to keep the Dataframe in tact but just affect the JSON output, then get the absolute value of the number when you create the dict that you jsonify.

# d = [{k: df.values[i][v] for v, k in enumerate(df.columns)} for i in range(len(df))]
d = df.to_dict("records")

keys_to_change = ["principal", "interest"]   # add whatever keys you want here

for record in d:
    for key in keys_to_change:
        record[key] = abs(record[key])

json_data = jsonify({"data": d})

To do this for dynamically all numeric values:

from pandas.api.types import is_numeric_dtype
#...
for record in d:
    for key in record.keys():
        if pd.api.types.is_number(record[key]:
            record[key] = abs(record[key])


答:
You can do this in two steps:

Filter rows by condition, for example by creating a boolean mask

Directly address the underlying numpy-arrays via .loc (in order to prevent the alignment of index values)

.loc: Access a group of rows and columns by label(s) or a boolean array.
  (Link to pandas-Documentation)

```<code>    #Boolean mask of the entire dataframe in order to identify relevant rows
    mask = df['Category'].eq('A')     #Anlog to mask = (df["Category"] == 'A')

    #pandas >= 0.24
    df.loc[mask] = df.loc[mask].sort_values('Layer').to_numpy()

    #pandas < 0.24
    df.loc[mask] = df.loc[mmask.sort_values('Layer').values

    #Result
    print (df)
           Category Content  Layer
    Index
    000001        A   Dummy      0
    000002        A   Dummy      0
    000003        A   Dummy      1
    000004        A   Dummy      1
    000005        B   Dummy      2
    000006        B   Dummy      0
    000007        B   Dummy      4
</code>```

Title: Reorder only a part of a pandas DataFrame

Body:
Context

I have a pandas-DataFrame with a structure analogous to something like the table on the left:

      + Category + Content + Layer                + Category + Content + Layer
Index |          |         |                Index |          |         |
----------------------------------          ----------------------------------
000001|   "A"    | "Dummy" |  0         ->  000001|   "A"    | "Dummy" |  0
----------------------------------          ----------------------------------
000002|   "A"    | "Dummy" |  1         ->  000003|   "A"    | "Dummy" |  0
----------------------------------          ----------------------------------
000003|   "A"    | "Dummy" |  0         ->  000002|   "A"    | "Dummy" |  1
----------------------------------          ----------------------------------
000004|   "A"    | "Dummy" |  1         ->  000004|   "A"    | "Dummy" |  1
----------------------------------          ----------------------------------
000005|   "B"    | "Dummy" |  2         =   000005|   "B"    | "Dummy" |  2
----------------------------------          ----------------------------------
000006|   "B"    | "Dummy" |  0         =   000006|   "B"    | "Dummy" |  0
----------------------------------          ----------------------------------
000007|   "B"    | "Dummy" |  4         =   000007|   "B"    | "Dummy" |  4
----------------------------------          ----------------------------------

What I want to achieve is to reorder the dataframe like on the right.

Question

As shown in the right table, only a part of the dataframe is supposed to be reordered - Only elements of category == "A" shall be ordered in ascending manner of their layer.
All elements of category == "B"have to stay as they are (which is my current problem when working with dataframe.sort_values() etc.).

How can I reorder (resort) only the specified part of the dataframe without affecting the rest?

Body:
You can do this in two steps:

Filter rows by condition, for example by creating a boolean mask

Directly address the underlying numpy-arrays via .loc (in order to prevent the alignment of index values)

.loc: Access a group of rows and columns by label(s) or a boolean array.
  (Link to pandas-Documentation)

    #Boolean mask of the entire dataframe in order to identify relevant rows
    mask = df['Category'].eq('A')     #Anlog to mask = (df["Category"] == 'A')

    #pandas >= 0.24
    df.loc[mask] = df.loc[mask].sort_values('Layer').to_numpy()

    #pandas < 0.24
    df.loc[mask] = df.loc[mmask.sort_values('Layer').values

    #Result
    print (df)
           Category Content  Layer
    Index
    000001        A   Dummy      0
    000002        A   Dummy      0
    000003        A   Dummy      1
    000004        A   Dummy      1
    000005        B   Dummy      2
    000006        B   Dummy      0
    000007        B   Dummy      4


问:
Error with loops in javascript?
I have, in multiple parts of my code, snippits similar to this:

```<code>function updateScore() {
    var currentPoints=0;
    for (nni=0;nni<currentSession.Questions.length+1;nni++) {
        currentPoints+=currentSession.Questions[nni].Score;
    }
    alert('hi');
    document.getElementById('quiz_score').innerHTML='%'+(currentPoints/currentSession.TotalPoints)*100
}
</code>```

Everything works fine... until after the loop.  This happens in multiple cases.  The alert won't even show after the loop ends.  It's like the function just stops...

I'm also having problems where the iterator (in this case, nni) stays global.  Basically, I can't use that variable ever again in my code because for some reason, if I change nni, it messes up the for loop.  I'm obvisouly not doing something right.  I'm a self tought Javascripter (basically googling anything I don't know, I've never taken a lesson).  I must be missing something about for loops.

Thanks if you can!

答:
What does the JS console report?

If you’ve no idea what the JS console is, Google it, or add an exception handler to your function:

```<code>function updateScore() {
    try {
        var currentPoints=0;
        for (nni=0;nni<currentSession.Questions.length+1;nni++) {
            currentPoints+=currentSession.Questions[nni].Score;
        }
        alert('hi');
        document.getElementById('quiz_score').innerHTML='%'+(currentPoints/currentSession.TotalPoints)*100
    } catch (err) {
        alert('Error ' + err.name + ': ' + err.message);
    }
}
</code>```

Also, you’re letting the loop go too far; you should stop at .length, and not at .length + 1.

And as has been noticed by others: you should really declare your nni variable using var.

Title: Error with loops in javascript?

Body:
I have, in multiple parts of my code, snippits similar to this:

function updateScore() {
    var currentPoints=0;
    for (nni=0;nni<currentSession.Questions.length+1;nni++) {
        currentPoints+=currentSession.Questions[nni].Score;
    }
    alert('hi');
    document.getElementById('quiz_score').innerHTML='%'+(currentPoints/currentSession.TotalPoints)*100
}

Everything works fine... until after the loop.  This happens in multiple cases.  The alert won't even show after the loop ends.  It's like the function just stops...

I'm also having problems where the iterator (in this case, nni) stays global.  Basically, I can't use that variable ever again in my code because for some reason, if I change nni, it messes up the for loop.  I'm obvisouly not doing something right.  I'm a self tought Javascripter (basically googling anything I don't know, I've never taken a lesson).  I must be missing something about for loops.

Thanks if you can!

Body:
What does the JS console report?

If you’ve no idea what the JS console is, Google it, or add an exception handler to your function:

function updateScore() {
    try {
        var currentPoints=0;
        for (nni=0;nni<currentSession.Questions.length+1;nni++) {
            currentPoints+=currentSession.Questions[nni].Score;
        }
        alert('hi');
        document.getElementById('quiz_score').innerHTML='%'+(currentPoints/currentSession.TotalPoints)*100
    } catch (err) {
        alert('Error ' + err.name + ': ' + err.message);
    }
}

Also, you’re letting the loop go too far; you should stop at .length, and not at .length + 1.

And as has been noticed by others: you should really declare your nni variable using var.