问:
Torch for camera "0" is not available due to an existing camera user
I want to create an app that has a button to record video and another separate toggle button to turn on the flah during recording the video.

I have built the camera app using camera2 API for recent androids which is accesssed by a image button. And i set torch mode access to a toggle button but this is not working at all. But the toggle button is able to access the flash separetly.

public class MainActivity extends AppCompatActivity {

    private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            setupCamera(width,height);
            connectCamera();
        }

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

        createFolder();

        mMediaRecorder = new MediaRecorder();

        mTextureView = (TextureView) findViewById(R.id.textureView);
        mRecordButtonimg = (ImageButton) findViewById(R.id.video_online_button);
                mRecordButtonimg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                if (misRecording) {
                    misRecording = false;
                    mRecordButtonimg.setImageResource(R.mipmap.ic_launcher);
                    mMediaRecorder.stop();
                    mMediaRecorder.reset();
                    startPreview();
                } else {
                    checkWriteStoragePermission();
                    misRecording = true;
                    mRecordButtonimg.setImageResource(R.mipmap.ic_launcher_round);
                }
            }
        });

        mButtonLights = (ToggleButton) findViewById(R.id.buttonLights);
        mButtonLights.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    cameraManager.setTorchMode(mCameraId, mButtonLights.isChecked());
                }catch (CameraAccessException e){
                    e.printStackTrace();
                }
            }
            });
    }
}
```

I have just added the set torch mode to the onClickListenser. Should i add it elsewhere? Beacuse it doesn't make any to add it to the preview! And i am already checking for the back camera in the code(id is 0 with a flashlight), so i don't know why the code isn't working.

答:
Use below code</p>

```<code>// write below line in Manifest file
 <uses-feature android:name="android.hardware.camera"
    android:required="true" />

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<permission android:name="android.permission.FLASHLIGHT"
    android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
    android:protectionLevel="normal" />
<uses-feature android:name="android.hardware.camera.flash" android:required="false" />

// write below code in activity xml
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
<LinearLayout
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
  <FrameLayout
      android:id="@+id/videoview"
      android:layout_width="500px"
      android:layout_height="480px"/>
  <LinearLayout
      android:orientation="vertical"
      android:layout_width="match_parent"
      android:layout_height="match_parent">
     <Button
         android:id="@+id/mybutton"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="REC"
         android:textSize="12dp"/>
     <RadioGroup
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:id="@+id/radio_group"
         android:orientation="vertical">
        <RadioButton
            android:id="@+id/flashoff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OFF"
            android:textSize="8dp"
            android:checked="true"/>
        <RadioButton
            android:id="@+id/flashtorch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Torch"
            android:textSize="8dp"/>
     </RadioGroup>
    </LinearLayout>
   </LinearLayout>
  </LinearLayout>

 // Activity source code

 import android.Manifest;
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.hardware.Camera;
 import android.media.CamcorderProfile;
 import android.media.MediaRecorder;
 import android.os.Bundle;
 import android.support.annotation.NonNull;
 import android.support.v4.app.ActivityCompat;
 import android.support.v4.content.ContextCompat;
 import android.support.v7.app.AppCompatActivity;
 import android.util.Log;
 import android.view.MotionEvent;
  import android.view.SurfaceHolder;
 import android.view.SurfaceView;
 import android.view.View;
 import android.widget.Button;
 import android.widget.FrameLayout;
 import android.widget.RadioButton;
 import android.widget.Toast;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
private Camera myCamera;
private MyCameraSurfaceView myCameraSurfaceView;
private MediaRecorder mediaRecorder;
private Button myButton;
private RadioButton flashOff, flashTorch;
private SurfaceHolder surfaceHolder;
boolean recording;
private int PERMISSION_CODE=1021;
private static final String LOG_TAG=MainActivity.class.getName();
private String[] getDeviceIdPermissions = new String[]{
        Manifest.permission.CAMERA,
        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
        android.Manifest.permission.READ_EXTERNAL_STORAGE,
        android.Manifest.permission.RECORD_AUDIO};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if(!checkPermission()) {
        askPermission();
    }else{
        init();
    }
}

private boolean checkPermission() {
    if(isPermitted(getDeviceIdPermissions)){
        return true;
    }
    return false;
}

private void askPermission(){
    ActivityCompat.requestPermissions(this,getDeviceIdPermissions,PERMISSION_CODE);
}

Button.OnTouchListener flashButtonOnTouchListener
        = new Button.OnTouchListener(){

    @Override
    public boolean onTouch(View arg0, MotionEvent arg1) {
        // TODO Auto-generated method stub

        if(myCamera != null){
            Camera.Parameters parameters = myCamera.getParameters();

            switch (arg1.getAction()){
                case MotionEvent.ACTION_DOWN:
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                    myCamera.setParameters(parameters);
                    break;
                case MotionEvent.ACTION_UP:
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                    myCamera.setParameters(parameters);
                    break;
            };
        }

        return true;
    }};

Button.OnClickListener flashModeButtonOnClickListener
        = new Button.OnClickListener(){

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
};

Button.OnClickListener myButtonOnClickListener
        = new Button.OnClickListener(){

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(recording){
            // stop recording and release camera
            mediaRecorder.stop();  // stop the recording
            releaseMediaRecorder(); // release the MediaRecorder object

            //Exit after saved
            finish();
        }else{

            //Release Camera before MediaRecorder start
            releaseCamera();

            if(!prepareMediaRecorder()){
                Toast.makeText(MainActivity.this,
                        "Fail in prepareMediaRecorder()!\n - Ended -",
                        Toast.LENGTH_LONG).show();
                finish();
            }

            mediaRecorder.start();
            recording = true;
            myButton.setText("STOP");
        }
    }};

private Camera getCameraInstance(){
    // TODO Auto-generated method stub
    Camera c = null;
    try {
        c = Camera.open(); // attempt to get a Camera instance
    }
    catch (Exception e){
        // Camera is not available (in use or does not exist)
    }
    return c; // returns null if camera is unavailable
}

private void init(){
    myCamera = getCameraInstance();
    if(myCamera == null){
        Log.d(LOG_TAG,"Failed to get camera");
    }

    myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
    FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
    myCameraPreview.addView(myCameraSurfaceView);

    myButton = (Button)findViewById(R.id.mybutton);
    myButton.setOnClickListener(myButtonOnClickListener);

    flashOff = (RadioButton)findViewById(R.id.flashoff);
    flashTorch = (RadioButton)findViewById(R.id.flashtorch);
}

private String getFlashModeSetting(){
    if(flashTorch.isChecked()){
        return Camera.Parameters.FLASH_MODE_TORCH;
    }else {
        return Camera.Parameters.FLASH_MODE_OFF;
    }
}

private boolean prepareMediaRecorder(){
    myCamera = getCameraInstance();

    Camera.Parameters parameters = myCamera.getParameters();
    parameters.setFlashMode(getFlashModeSetting());
    myCamera.setDisplayOrientation(90);
    myCamera.setParameters(parameters);

    mediaRecorder = new MediaRecorder();

    myCamera.unlock();
    mediaRecorder.setCamera(myCamera);

    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

    mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

    mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
    mediaRecorder.setMaxDuration(60000); // Set max duration 60 sec.
    mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M

    mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());

    try {
        mediaRecorder.prepare();
    } catch (IllegalStateException e) {
        releaseMediaRecorder();
        return false;
    } catch (IOException e) {
        releaseMediaRecorder();
        return false;
    }
    return true;

}

@Override
protected void onPause() {
    super.onPause();
    releaseMediaRecorder();       // if you are using MediaRecorder, release it first
    releaseCamera();              // release the camera immediately on pause event
}

private void releaseMediaRecorder(){
    if (mediaRecorder != null) {
        mediaRecorder.reset();   // clear recorder configuration
        mediaRecorder.release(); // release the recorder object
        mediaRecorder = null;
        myCamera.lock();           // lock camera for later use
    }
}

private void releaseCamera(){
    if (myCamera != null){
        myCamera.release();        // release the camera for other applications
        myCamera = null;
    }
}

public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{

    private SurfaceHolder mHolder;
    private Camera mCamera;

    public MyCameraSurfaceView(Context context, Camera camera) {
        super(context);
        mCamera = camera;
        mCamera.setDisplayOrientation(90);
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int weight,
                               int height) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // make any resize, rotate or reformatting changes here

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub

    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    boolean isPermitted =isPermitted(permissions);
    if(isPermitted){
        if(requestCode==PERMISSION_CODE){
            init();
        }
    }
}

public boolean isPermitted(String[] permissions) {
    boolean havePermission;
    for (String permission : permissions) {
        havePermission = (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED);
        if (!havePermission)
            return false;
    }
    return true;
}
}
</code>```

Body:
I want to create an app that has a button to record video and another separate toggle button to turn on the flah during recording the video.

I have built the camera app using camera2 API for recent androids which is accesssed by a image button. And i set torch mode access to a toggle button but this is not working at all. But the toggle button is able to access the flash separetly.

public class MainActivity extends AppCompatActivity {

    private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            setupCamera(width,height);
            connectCamera();
        }

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

        createFolder();

        mMediaRecorder = new MediaRecorder();

        mTextureView = (TextureView) findViewById(R.id.textureView);
        mRecordButtonimg = (ImageButton) findViewById(R.id.video_online_button);
                mRecordButtonimg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                if (misRecording) {
                    misRecording = false;
                    mRecordButtonimg.setImageResource(R.mipmap.ic_launcher);
                    mMediaRecorder.stop();
                    mMediaRecorder.reset();
                    startPreview();
                } else {
                    checkWriteStoragePermission();
                    misRecording = true;
                    mRecordButtonimg.setImageResource(R.mipmap.ic_launcher_round);
                }
            }
        });

        mButtonLights = (ToggleButton) findViewById(R.id.buttonLights);
        mButtonLights.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    cameraManager.setTorchMode(mCameraId, mButtonLights.isChecked());
                }catch (CameraAccessException e){
                    e.printStackTrace();
                }
            }
            });
    }
}

I have just added the set torch mode to the onClickListenser. Should i add it elsewhere? Beacuse it doesn't make any to add it to the preview! And i am already checking for the back camera in the code(id is 0 with a flashlight), so i don't know why the code isn't working.

Body:
Use below code

// write below line in Manifest file
 <uses-feature android:name="android.hardware.camera"
    android:required="true" />

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<permission android:name="android.permission.FLASHLIGHT"
    android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
    android:protectionLevel="normal" />
<uses-feature android:name="android.hardware.camera.flash" android:required="false" />

// write below code in activity xml
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
<LinearLayout
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
  <FrameLayout
      android:id="@+id/videoview"
      android:layout_width="500px"
      android:layout_height="480px"/>
  <LinearLayout
      android:orientation="vertical"
      android:layout_width="match_parent"
      android:layout_height="match_parent">
     <Button
         android:id="@+id/mybutton"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="REC"
         android:textSize="12dp"/>
     <RadioGroup
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:id="@+id/radio_group"
         android:orientation="vertical">
        <RadioButton
            android:id="@+id/flashoff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OFF"
            android:textSize="8dp"
            android:checked="true"/>
        <RadioButton
            android:id="@+id/flashtorch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Torch"
            android:textSize="8dp"/>
     </RadioGroup>
    </LinearLayout>
   </LinearLayout>
  </LinearLayout>

 // Activity source code

 import android.Manifest;
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.hardware.Camera;
 import android.media.CamcorderProfile;
 import android.media.MediaRecorder;
 import android.os.Bundle;
 import android.support.annotation.NonNull;
 import android.support.v4.app.ActivityCompat;
 import android.support.v4.content.ContextCompat;
 import android.support.v7.app.AppCompatActivity;
 import android.util.Log;
 import android.view.MotionEvent;
  import android.view.SurfaceHolder;
 import android.view.SurfaceView;
 import android.view.View;
 import android.widget.Button;
 import android.widget.FrameLayout;
 import android.widget.RadioButton;
 import android.widget.Toast;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
private Camera myCamera;
private MyCameraSurfaceView myCameraSurfaceView;
private MediaRecorder mediaRecorder;
private Button myButton;
private RadioButton flashOff, flashTorch;
private SurfaceHolder surfaceHolder;
boolean recording;
private int PERMISSION_CODE=1021;
private static final String LOG_TAG=MainActivity.class.getName();
private String[] getDeviceIdPermissions = new String[]{
        Manifest.permission.CAMERA,
        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
        android.Manifest.permission.READ_EXTERNAL_STORAGE,
        android.Manifest.permission.RECORD_AUDIO};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if(!checkPermission()) {
        askPermission();
    }else{
        init();
    }
}

private boolean checkPermission() {
    if(isPermitted(getDeviceIdPermissions)){
        return true;
    }
    return false;
}

private void askPermission(){
    ActivityCompat.requestPermissions(this,getDeviceIdPermissions,PERMISSION_CODE);
}

Button.OnTouchListener flashButtonOnTouchListener
        = new Button.OnTouchListener(){

    @Override
    public boolean onTouch(View arg0, MotionEvent arg1) {
        // TODO Auto-generated method stub

        if(myCamera != null){
            Camera.Parameters parameters = myCamera.getParameters();

            switch (arg1.getAction()){
                case MotionEvent.ACTION_DOWN:
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                    myCamera.setParameters(parameters);
                    break;
                case MotionEvent.ACTION_UP:
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                    myCamera.setParameters(parameters);
                    break;
            };
        }

        return true;
    }};

Button.OnClickListener flashModeButtonOnClickListener
        = new Button.OnClickListener(){

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
};

Button.OnClickListener myButtonOnClickListener
        = new Button.OnClickListener(){

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(recording){
            // stop recording and release camera
            mediaRecorder.stop();  // stop the recording
            releaseMediaRecorder(); // release the MediaRecorder object

            //Exit after saved
            finish();
        }else{

            //Release Camera before MediaRecorder start
            releaseCamera();

            if(!prepareMediaRecorder()){
                Toast.makeText(MainActivity.this,
                        "Fail in prepareMediaRecorder()!\n - Ended -",
                        Toast.LENGTH_LONG).show();
                finish();
            }

            mediaRecorder.start();
            recording = true;
            myButton.setText("STOP");
        }
    }};

private Camera getCameraInstance(){
    // TODO Auto-generated method stub
    Camera c = null;
    try {
        c = Camera.open(); // attempt to get a Camera instance
    }
    catch (Exception e){
        // Camera is not available (in use or does not exist)
    }
    return c; // returns null if camera is unavailable
}

private void init(){
    myCamera = getCameraInstance();
    if(myCamera == null){
        Log.d(LOG_TAG,"Failed to get camera");
    }

    myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
    FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
    myCameraPreview.addView(myCameraSurfaceView);

    myButton = (Button)findViewById(R.id.mybutton);
    myButton.setOnClickListener(myButtonOnClickListener);

    flashOff = (RadioButton)findViewById(R.id.flashoff);
    flashTorch = (RadioButton)findViewById(R.id.flashtorch);
}

private String getFlashModeSetting(){
    if(flashTorch.isChecked()){
        return Camera.Parameters.FLASH_MODE_TORCH;
    }else {
        return Camera.Parameters.FLASH_MODE_OFF;
    }
}

private boolean prepareMediaRecorder(){
    myCamera = getCameraInstance();

    Camera.Parameters parameters = myCamera.getParameters();
    parameters.setFlashMode(getFlashModeSetting());
    myCamera.setDisplayOrientation(90);
    myCamera.setParameters(parameters);

    mediaRecorder = new MediaRecorder();

    myCamera.unlock();
    mediaRecorder.setCamera(myCamera);

    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

    mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

    mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
    mediaRecorder.setMaxDuration(60000); // Set max duration 60 sec.
    mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M

    mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());

    try {
        mediaRecorder.prepare();
    } catch (IllegalStateException e) {
        releaseMediaRecorder();
        return false;
    } catch (IOException e) {
        releaseMediaRecorder();
        return false;
    }
    return true;

}

@Override
protected void onPause() {
    super.onPause();
    releaseMediaRecorder();       // if you are using MediaRecorder, release it first
    releaseCamera();              // release the camera immediately on pause event
}

private void releaseMediaRecorder(){
    if (mediaRecorder != null) {
        mediaRecorder.reset();   // clear recorder configuration
        mediaRecorder.release(); // release the recorder object
        mediaRecorder = null;
        myCamera.lock();           // lock camera for later use
    }
}

private void releaseCamera(){
    if (myCamera != null){
        myCamera.release();        // release the camera for other applications
        myCamera = null;
    }
}

public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{

    private SurfaceHolder mHolder;
    private Camera mCamera;

    public MyCameraSurfaceView(Context context, Camera camera) {
        super(context);
        mCamera = camera;
        mCamera.setDisplayOrientation(90);
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int weight,
                               int height) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // make any resize, rotate or reformatting changes here

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub

    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    boolean isPermitted =isPermitted(permissions);
    if(isPermitted){
        if(requestCode==PERMISSION_CODE){
            init();
        }
    }
}

public boolean isPermitted(String[] permissions) {
    boolean havePermission;
    for (String permission : permissions) {
        havePermission = (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED);
        if (!havePermission)
            return false;
    }
    return true;
}
}


来源: stackexchange

问:
Is NULL necessary?
Is NULL or NOT NULL necessary for Adding a column in SQL Server? (If you are going to run UPDATE statement after)

I tested without it locally, and it seems to work fine both in SQL and on the website; but I wanted to make sure before running release/production.

I looked up some other articles, including microsoft website. Some show it with, some without. SO articles say some benefits of NULL, like if you have information that may be added later. But assuming I am going to run UPDATE to add values after, will it matter?

I am guessing it does not matter from what I've tested and read.

```<code>ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150);
UPDATE [dbo].[MyTable] SET NewColumn ='Math' WHERE ID = 1
UPDATE [dbo].[MyTable] SET NewColumn ='Science' WHERE ID = 2
</code>```

答: I'd make sure you have something declarative. And if you are setting as "not null," be sure you have a default value or use can suffer LOTS of data loss if data previously exists. It makes me nervous because this an ALTER vs a CREATE.</p>

ContentLicense: CC BY-SA 4.0

Title: Is NULL necessary?

Body:
Is NULL or NOT NULL necessary for Adding a column in SQL Server? (If you are going to run UPDATE statement after)

I tested without it locally, and it seems to work fine both in SQL and on the website; but I wanted to make sure before running release/production.

I looked up some other articles, including microsoft website. Some show it with, some without. SO articles say some benefits of NULL, like if you have information that may be added later. But assuming I am going to run UPDATE to add values after, will it matter?

I am guessing it does not matter from what I've tested and read.

ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150);
UPDATE [dbo].[MyTable] SET NewColumn ='Math' WHERE ID = 1
UPDATE [dbo].[MyTable] SET NewColumn ='Science' WHERE ID = 2


问:
Find out how many times a regex matches in a string in Python
Is there a way that I can find out how many matches of a regex are in a string in Python? For example, if I have the string "It actually happened when it acted out of turn."

I want to know how many times "t a" appears in the string. In that string, "t a" appears twice. I want my function to tell me it appeared twice. Is this possible?

答:
To avoid creating a list of matches one may also use re.sub with a callable as replacement. It will be called on each match, incrementing internal counter.</p>

```<code>class Counter(object):
    def __init__(self):
        self.matched = 0
    def __call__(self, matchobj):
        self.matched += 1

counter = Counter()
re.sub(some_pattern, counter, text)

print counter.matched
</code>```

ContentLicense: CC BY-SA 2.5

Body:
To avoid creating a list of matches one may also use re.sub with a callable as replacement. It will be called on each match, incrementing internal counter.

class Counter(object):
    def __init__(self):
        self.matched = 0
    def __call__(self, matchobj):
        self.matched += 1

counter = Counter()
re.sub(some_pattern, counter, text)

print counter.matched

ContentLicense: CC BY-SA 3.0


问:
'uri.match' is undefined trying to require audio file into video source
Here is my code around this <Video /> element

```<code>class Menu extends Component {
    ...
    audioFile = null
    componentWillMount(){
        this.audioFile = require('../../assets/audio/subtle.mp3');
    }
}

<Video source={{uri: this.audioFile}}   // Can be a URL or a local file.
  ref={(ref) => {
    this.player = ref
  }}
  onError={this.audioError}
  audioOnly
  style={styles.backgroundVideo}
  playInBackground
  playWhenInactive
  ignoreSilentSwitch={"ignore"}
/>
</code>```

The specific error I get is...

```<code>TypeError: uri.match is not a function. (In 'uri.match(/^\//)', 'uri.match' is undefined)
</code>```

Here are the versions

expo: 30.0.0

expokit: 1.7.1

react: 16.3.1

react-native: https://github.com/expo/react-native/archive/sdk-30.0.0.tar.gz

react-native-video: 3.2.1

I'm trying to load an audio asset from the local package here, but I can't seem to get it to work, if I remove the audio file from that folder it throws an error that it can't find it so it's definitely finding the file.

Would love some help with this

答:
This is what made it work in my use case

<Video source={require('../../assets/audio/file.mp3')} ... />

Body:
Here is my code around this <Video /> element

class Menu extends Component {
    ...
    audioFile = null
    componentWillMount(){
        this.audioFile = require('../../assets/audio/subtle.mp3');
    }
}

<Video source={{uri: this.audioFile}}   // Can be a URL or a local file.
  ref={(ref) => {
    this.player = ref
  }}
  onError={this.audioError}
  audioOnly
  style={styles.backgroundVideo}
  playInBackground
  playWhenInactive
  ignoreSilentSwitch={"ignore"}
/>

The specific error I get is...

TypeError: uri.match is not a function. (In 'uri.match(/^\//)', 'uri.match' is undefined)

Here are the versions

expo: 30.0.0

expokit: 1.7.1

react: 16.3.1

react-native: https://github.com/expo/react-native/archive/sdk-30.0.0.tar.gz

react-native-video: 3.2.1

I'm trying to load an audio asset from the local package here, but I can't seem to get it to work, if I remove the audio file from that folder it throws an error that it can't find it so it's definitely finding the file.

Would love some help with this


问:
/usr/local/bin/ffmpeg: cannot execute binary file
Want to convert my m4a files into mp3 files using a script. It would save some time... I have over 100 GB of music files.

OS: OSX10.14 / Terminal vs Bash script

I can run ffmpeg -v 5 -y -i musicFile.m4a -acodec libmp3lame -ac 2 -b:a 320k musicFile.mp3 from the terminal. It converts the file and I can see and play the file from itunes.

When I run the same from a bash script it fails to convert.

ffmpeg -v 5 -y -i $ENTRY_FILE -acodec libmp3lame -ac 2 -b:a 320k $MP3NAME

My ipod nano just died and I got a new mp3 player. Now I need to convert my itunes files from AAC format to MP3.
ffmpeg is an established video and music file converter.

When I run it from the bash script I tried a few things.

I added ./ in front of the file, that failed because it was installed under /usr/local/bin and not under the same directory.

I also tried sh ffmpeg... and that gave me the cannot execute a binary file.

#!/usr/bin/env bash

# convert m4a file to mp3
set -e

file_convert() {
    ENTRY_FILE=$(printf %q "${entry}")
    FILE_NAME=$(printf %q "$(basename "${entry}")")
    DIR=$(printf %q "$(dirname "${entry}")")
    NAME="${FILE_NAME%.*}"
    EXT="${FILE_NAME##*.}"
    MP3NAME="${DIR}/${NAME}.mp3"

    printf "%*s%s\n"                    $((indent+2)) '' "$ENTRY_FILE"
    printf "%*s\tNew File :\t%s\n"      $((indent+2)) '' "$MP3NAME"

    if [ $EXT == "m4a" ]
    then
      printf "%*s\tConverting: \t%s\n" $((index+2)) '' "$ENTRY_FILE"
      ffmpeg -v 5 -y -i $ENTRY_FILE -acodec libmp3lame -ac 2 -b:a 320k $MP3NAME
    fi
}

walk() {
    local indent="${2:-0}"
    printf "\n%*s%s\n\n" "$indent" '' "$1"
    # If the entry is a file convert it
    for entry in "$1"/*; do [[ -f "$entry" ]] && file_convert; done
    # If the entry is a directory recurse
    for entry in "$1"/*; do [[ -d "$entry" ]] && walk "$entry" $((indent+2)); done
}

# If the path is empty use the current, otherwise convert relative to absolute; Exec walk()
[[ -z "${1}" ]] && ABS_PATH="${PWD}" || pushd "${1}" && ABS_PATH="${PWD}"
walk "${ABS_PATH}"
popd
echo

```

I expect >./aacToMp3.sh ./music to traverses the music directory and convert each m4a file to .mp3.

It is walking the file system and printing out correct files, with the spaces escaped. When it hits the ffmpeg line it halts. I put the set -e at the top of the file to force it to fail if the command fails. Without the set -e it happily walks all the music files and prints them to the stdout.

答:
If you have lots of files to process and a decent multi-core CPU and fast disk, I would recommend GNU Parallel which you can install with homebrew:

```<code>brew install parallel
</code>```

Then make a copy of a few files in a test directory and try:

```<code>parallel --dry-run ffmpeg -v 5 -y -i {} -acodec libmp3lame -ac 2 -b:a 320k {.}.mp3 ::: *.m4a
</code>```

If that looks good, replace --dry-run with --progress.

If that looks good, you can (make a backup first) and do the whole lot:

```<code>find path/to/music -name "*.m4a" -print0 | parallel -0 --progress ffmpeg -v 5 -y -i {} -acodec libmp3lame -ac 2 -b:a 320k {.}.mp3
</code>```

Body:
Want to convert my m4a files into mp3 files using a script. It would save some time... I have over 100 GB of music files.

OS: OSX10.14 / Terminal vs Bash script

I can run ffmpeg -v 5 -y -i musicFile.m4a -acodec libmp3lame -ac 2 -b:a 320k musicFile.mp3 from the terminal. It converts the file and I can see and play the file from itunes.

When I run the same from a bash script it fails to convert.

ffmpeg -v 5 -y -i $ENTRY_FILE -acodec libmp3lame -ac 2 -b:a 320k $MP3NAME

My ipod nano just died and I got a new mp3 player. Now I need to convert my itunes files from AAC format to MP3.
ffmpeg is an established video and music file converter.

When I run it from the bash script I tried a few things.

I added ./ in front of the file, that failed because it was installed under /usr/local/bin and not under the same directory.

I also tried sh ffmpeg... and that gave me the cannot execute a binary file.

#!/usr/bin/env bash

# convert m4a file to mp3
set -e

file_convert() {
    ENTRY_FILE=$(printf %q "${entry}")
    FILE_NAME=$(printf %q "$(basename "${entry}")")
    DIR=$(printf %q "$(dirname "${entry}")")
    NAME="${FILE_NAME%.*}"
    EXT="${FILE_NAME##*.}"
    MP3NAME="${DIR}/${NAME}.mp3"

    printf "%*s%s\n"                    $((indent+2)) '' "$ENTRY_FILE"
    printf "%*s\tNew File :\t%s\n"      $((indent+2)) '' "$MP3NAME"

    if [ $EXT == "m4a" ]
    then
      printf "%*s\tConverting: \t%s\n" $((index+2)) '' "$ENTRY_FILE"
      ffmpeg -v 5 -y -i $ENTRY_FILE -acodec libmp3lame -ac 2 -b:a 320k $MP3NAME
    fi
}

walk() {
    local indent="${2:-0}"
    printf "\n%*s%s\n\n" "$indent" '' "$1"
    # If the entry is a file convert it
    for entry in "$1"/*; do [[ -f "$entry" ]] && file_convert; done
    # If the entry is a directory recurse
    for entry in "$1"/*; do [[ -d "$entry" ]] && walk "$entry" $((indent+2)); done
}

# If the path is empty use the current, otherwise convert relative to absolute; Exec walk()
[[ -z "${1}" ]] && ABS_PATH="${PWD}" || pushd "${1}" && ABS_PATH="${PWD}"
walk "${ABS_PATH}"
popd
echo

I expect >./aacToMp3.sh ./music to traverses the music directory and convert each m4a file to .mp3.

It is walking the file system and printing out correct files, with the spaces escaped. When it hits the ffmpeg line it halts. I put the set -e at the top of the file to force it to fail if the command fails. Without the set -e it happily walks all the music files and prints them to the stdout.

Body:
If you have lots of files to process and a decent multi-core CPU and fast disk, I would recommend GNU Parallel which you can install with homebrew:

brew install parallel

Then make a copy of a few files in a test directory and try:

parallel --dry-run ffmpeg -v 5 -y -i {} -acodec libmp3lame -ac 2 -b:a 320k {.}.mp3 ::: *.m4a

If that looks good, replace --dry-run with --progress.

If that looks good, you can (make a backup first) and do the whole lot:

find path/to/music -name "*.m4a" -print0 | parallel -0 --progress ffmpeg -v 5 -y -i {} -acodec libmp3lame -ac 2 -b:a 320k {.}.mp3


问:
How to connect to the correct region or endpoint?
After downloading npm using cmd on pc, I Submit a training run to WML using the cacli train and I got thru the authentication for in order to connect to cloud storage. The problem is when I get to entering the region (us-geo) no of the endpoint provided on IBM cloud website works. Keep in mind I'm from Canada, Ottawa. Does anyone have a solution? Thank you.

答:
Use the public endpoint corresponding to your bucket location if running from a machine outside the IBM Cloud compute.
https://cloud.ibm.com/docs/services/cloud-object-storage/basics/endpoints.html#select-regions-and-endpoints

If your bucket is in US Cross Region the public endpoint is
s3.us.cloud-object-storage.appdomain.cloud


问:
Understanding Precision@K, AP@K, MAP@K
I'm currently evaluating a recommender system based on implicit feedback. I've been a bit confused with regard to the evaluation metrics for ranking tasks. Specifically, I am looking to evaluate by both precision and recall.

Precision@k has the advantage of not requiring any estimate of the
  size of the set of relevant documents but the disadvantages that it is
  the least stable of the commonly used evaluation measures and that it
  does not average well, since the total number of relevant documents
  for a query has a strong influence on precision at k

I have noticed myself that it tends to be quite volatile and as such, I would like to average the results from multiple evaluation logs.

I was wondering; say if I run an evaluation function which returns the following array:

Numpy array containing precision@k scores for each user.

And now I have an array for all of the precision@3 scores across my dataset.

If I take the mean of this array and average across say, 20 different scores: Is this equivalent to Mean Average Precision@K or MAP@K or am I understanding this a little too literally?

I am writing a dissertation with an evaluation section so the accuracy of the definitions is quite important to me.

答:
There are two averages involved which make the concepts somehow obscure, but they are pretty straightforward -at least in the recsys context-, let me clarify them:

P@K

How many relevant items are present in the top-k recommendations of your system

For example, to calculate P@3: take the top 3 recommendations for a given user and check how many of them are good ones. That number divided by 3 gives you the P@3

AP@K

The mean of P@i for i=1, ..., K.

For example, to calculate AP@3: sum P@1, P@2 and P@3 and divide that value by 3

AP@K is typically calculated for one user.

MAP@K

The mean of the AP@K for all the users.

For example, to calculate MAP@3: sum AP@3 for all the users and divide that value by the amount of users

If you are a programmer, you can check this code, which is the implementation of the functions apk and mapk of ml_metrics, a library mantained by the CTO of Kaggle.

Hope it helped!

Title: Understanding Precision@K, AP@K, MAP@K


问:
Change text of local notification in Swift
I developp an application for student. He can create his timetable.
I tried to create a notification how summarize the next day. So I need to change the text notification, how can I do that?

Another example, the student can write his homework. One day before to return the homework, notify him.

I'have already tried to do a simple notification, but the text of the notification is static.

```<code>let content = UNMutableNotificationContent()
content.title = "Changement de semaine"
content.body = "Nous sommes en semaine \(notificationSemaineAB())"
content.sound = UNNotificationSound.default

var dateComponent = DateComponents()
dateComponent.weekday = 2
dateComponent.hour = 11

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)

let request = UNNotificationRequest(identifier: "semaineAB", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
</code>```

For this one, I would like for each week, the text of notification tell me if we are in a even week or odd week. But in output, I have always the same text.

答:
You can remove the old notification with this code </p>

```<code>UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers:["semaineAB"])
</code>```

<p>And after that, you can reuse your code to create a new one. </p>

Body:
I developp an application for student. He can create his timetable.
I tried to create a notification how summarize the next day. So I need to change the text notification, how can I do that?

Another example, the student can write his homework. One day before to return the homework, notify him.

I'have already tried to do a simple notification, but the text of the notification is static.

let content = UNMutableNotificationContent()
content.title = "Changement de semaine"
content.body = "Nous sommes en semaine \(notificationSemaineAB())"
content.sound = UNNotificationSound.default

var dateComponent = DateComponents()
dateComponent.weekday = 2
dateComponent.hour = 11

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)

let request = UNNotificationRequest(identifier: "semaineAB", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)

For this one, I would like for each week, the text of notification tell me if we are in a even week or odd week. But in output, I have always the same text.

Body:
You can remove the old notification with this code

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers:["semaineAB"])

And after that, you can reuse your code to create a new one.


问:
How to continuously deploy from jenkins to Kubernetes
i have a Maven project on my local machine and a docker image in my repo and im using gitlab and jenkins to automate builds, and now with current setup I want to continously deploy to Kubernetes. I have no idea on how this is done. Any input will be appreciated.

my yaml file looks like this

apiVersion: v1
kind: Pod
metadata:
  name: client-pod
  labels:
    component: web
spec:
  containers:
    - name: client
      image: <image>
      ports:
        - containerPort: 3000```

答:
The easiest way will be to set the name of the new image. See here:

```<code>kubectl --record deployment.apps/nginx-deployment set image deployment.v1.apps/nginx-deployment nginx=nginx:1.9.1
</code>```

You will need to have access from your gitlab/Jenkins to your cluster.

Another option will be to use some kind of kubernetes deployment tool such as helm, or any other solution. This case will help you in more complicated scenarios where you also want to update your configuration files (k8s yamls).

Body:
The easiest way will be to set the name of the new image. See here:

kubectl --record deployment.apps/nginx-deployment set image deployment.v1.apps/nginx-deployment nginx=nginx:1.9.1

You will need to have access from your gitlab/Jenkins to your cluster.

Another option will be to use some kind of kubernetes deployment tool such as helm, or any other solution. This case will help you in more complicated scenarios where you also want to update your configuration files (k8s yamls).


问:
Power BI relativity measure with mutiple groups
I have a data that I simply create:

```<code>Col1      Col2   Col3   Col4
2014/1/1  A      Y      10
2014/4/1  A      Y      15
2015/1/1  A      Z      15
2015/4/1  A      Z      30
2014/1/1  B      Y      20
2014/4/1  B      Y      30
2015/1/1  B      Z      40
2015/4/1  B      Z      80
</code>```

I want to create a measure in Power BI so I can create an interactive visualization. The above data is created for example so we need to suppose that col2, col3 have multiple factors.

The measure I want is relativity, the value in Col4 divide the first value under Col1 and Col2.

Result I supposed but I do not need this in data table since when I create the visualization and add the filter for other columns, Col5, Col6, and etc. that I did not show in this example:

```<code>Col1      Col2   Col3   Col4   relativity_Col3ALL   relativity_Col3EqualsYorZ
2014/1/1  A      Y      10     1                    1
2014/4/1  A      Y      15     1.5                  1.5
2015/1/1  A      Z      15     1.5                  1
2015/4/1  A      Z      30     3                    2
2014/1/1  B      Y      20     1                    1
2014/4/1  B      Y      30     1.5                  1.5
2015/1/1  B      Z      40     2                    1
2015/4/1  B      Z      80     4                    2
</code>```

So I plot it and add filters beside the plot. When I select Y in the filter Col3, the plot will automatically change.

I provide the code I think in R:

```<code>dt <- data.table::as.data.table(dt)
dt[, relativity := Col4 / Col4[1], by = .(Col1, Col2)]
</code>```

But above code is incorrect because it did not consider Col3. I just want to mention Col4 / Col4[1] or Col4 / first(Col4).

I tried measure in Power BI:

```<code>relativity = CALCULATE(DIVIDE(dt[Col4], dt[AnotherMeasure]), MIN(dt[Col1]))
</code>```

I know this is false.

Can anyone help?

UPDATE

I tried @Alexis Olson's code and modified as:

```<code>relativity =
VAR YR = MIN(dt[Col1].[Year])
VAR QT = MIN(dt[Col1].[Quarter])
VAR PF = CALCULATE(TOTALQTD(SUM(dt[Col4]), dt[Col1].[Date]), dt[Col1].[Year] = YR, dt[Col1].[Quarter] = QT)
RETURN
    DIVIDE(SUM(dt[Col4]), PF)
</code>```

However, when I visualize in the report, it all shows 1.

I also tried this:

```<code>relativity =
VAR YR = CALCULATE(MIN(dt[Col1].[Year]), ALLEXCEPT(dt, dt[Col2]))
VAR QT = CALCULATE(MIN(dt[Col1].[Quarter]), ALLEXCEPT(dt, dt[Col2]))
VAR PFQTD = TOTALQTD(SUM(dt[Col4]), dt[Col1].[Date])
VAR MPFQTD = CALCULATE(MAX(PFQTD), FILTER(dt, dt[Col1].[Year] = YR), FILTER(dt, dt[Col1].[Quarter] = QT))
RETURN
    MPFQTD
</code>```

Failed either

答:
Using the logic from this Q&A, you can create a calculated column as follows:

```<code>relativity =
VAR FirstCol1 = CALCULATE ( MIN ( dt[Col1] ), ALLEXCEPT ( dt, dt[Col2], dt[Col3] ) )
VAR FirstCol4 = CALCULATE ( VALUES ( dt[Col4] ), dt[Col1] = FirstCol1 )
RETURN
    DIVIDE ( dt[Col4], FirstCol4 )
</code>```

This looks up the first date when Col2 and Col3 are the same value, then finds the Col4 value on that first date, and finally divides the current Col4 value by that first Col4 value.

The ALLEXCEPT removes the row context except for the columns you specify. If you want relativity_Col3_All, then simply remove that column from the ALLEXCEPT specification.

Body:
I have a data that I simply create:

Col1      Col2   Col3   Col4
2014/1/1  A      Y      10
2014/4/1  A      Y      15
2015/1/1  A      Z      15
2015/4/1  A      Z      30
2014/1/1  B      Y      20
2014/4/1  B      Y      30
2015/1/1  B      Z      40
2015/4/1  B      Z      80

I want to create a measure in Power BI so I can create an interactive visualization. The above data is created for example so we need to suppose that col2, col3 have multiple factors.

The measure I want is relativity, the value in Col4 divide the first value under Col1 and Col2.

Result I supposed but I do not need this in data table since when I create the visualization and add the filter for other columns, Col5, Col6, and etc. that I did not show in this example:

Col1      Col2   Col3   Col4   relativity_Col3ALL   relativity_Col3EqualsYorZ
2014/1/1  A      Y      10     1                    1
2014/4/1  A      Y      15     1.5                  1.5
2015/1/1  A      Z      15     1.5                  1
2015/4/1  A      Z      30     3                    2
2014/1/1  B      Y      20     1                    1
2014/4/1  B      Y      30     1.5                  1.5
2015/1/1  B      Z      40     2                    1
2015/4/1  B      Z      80     4                    2

So I plot it and add filters beside the plot. When I select Y in the filter Col3, the plot will automatically change.

I provide the code I think in R:

dt <- data.table::as.data.table(dt)
dt[, relativity := Col4 / Col4[1], by = .(Col1, Col2)]

But above code is incorrect because it did not consider Col3. I just want to mention Col4 / Col4[1] or Col4 / first(Col4).

I tried measure in Power BI:

relativity = CALCULATE(DIVIDE(dt[Col4], dt[AnotherMeasure]), MIN(dt[Col1]))

I know this is false.

Can anyone help?

UPDATE

I tried @Alexis Olson's code and modified as:

relativity =
VAR YR = MIN(dt[Col1].[Year])
VAR QT = MIN(dt[Col1].[Quarter])
VAR PF = CALCULATE(TOTALQTD(SUM(dt[Col4]), dt[Col1].[Date]), dt[Col1].[Year] = YR, dt[Col1].[Quarter] = QT)
RETURN
    DIVIDE(SUM(dt[Col4]), PF)

However, when I visualize in the report, it all shows 1.

I also tried this:

relativity =
VAR YR = CALCULATE(MIN(dt[Col1].[Year]), ALLEXCEPT(dt, dt[Col2]))
VAR QT = CALCULATE(MIN(dt[Col1].[Quarter]), ALLEXCEPT(dt, dt[Col2]))
VAR PFQTD = TOTALQTD(SUM(dt[Col4]), dt[Col1].[Date])
VAR MPFQTD = CALCULATE(MAX(PFQTD), FILTER(dt, dt[Col1].[Year] = YR), FILTER(dt, dt[Col1].[Quarter] = QT))
RETURN
    MPFQTD

Failed either

Body:
Using the logic from this Q&A, you can create a calculated column as follows:

relativity =
VAR FirstCol1 = CALCULATE ( MIN ( dt[Col1] ), ALLEXCEPT ( dt, dt[Col2], dt[Col3] ) )
VAR FirstCol4 = CALCULATE ( VALUES ( dt[Col4] ), dt[Col1] = FirstCol1 )
RETURN
    DIVIDE ( dt[Col4], FirstCol4 )

This looks up the first date when Col2 and Col3 are the same value, then finds the Col4 value on that first date, and finally divides the current Col4 value by that first Col4 value.

The ALLEXCEPT removes the row context except for the columns you specify. If you want relativity_Col3_All, then simply remove that column from the ALLEXCEPT specification.


问:
Difference between .bind and other events
What is the difference between the following lines of code, or are they just 2 different ways to write the same thing:

```<code>$("p").click(function() { some code here });

$("p").bind("click", function(){ some other code here });
</code>```

Am I over simplifying this? Because if you wanted to bind more than one event you could just chain the events, correct?

答:
Also note that binds allows for custom events</p>

```<code>$(elem).bind('myEvent', function(){
   alert('myEvent!');
});
$(elem).trigger('myEvent'); //alerts 'myEvent!'
</code>```

OwnerDisplayName: Mike Fielden

Body:
What is the difference between the following lines of code, or are they just 2 different ways to write the same thing:

$("p").click(function() { some code here });

$("p").bind("click", function(){ some other code here });

Am I over simplifying this? Because if you wanted to bind more than one event you could just chain the events, correct?

Body:
Also note that binds allows for custom events

$(elem).bind('myEvent', function(){
   alert('myEvent!');
});
$(elem).trigger('myEvent'); //alerts 'myEvent!'

OwnerDisplayName: Pim Jager


问:
why the main method is printing nothing in the sub class?
"mysecondclass" which is a sub class of the super class "myfirstclass"
should inherit all the properties of the super class "myfirstclass"
and it's expected to output the value of x but instead it prints nothing

```<code>package myfirstproject;

public class myfirstclass {
    protected int x = 10;
    //getter
    public void getX() {
     System.out.println(x);
    }
    public static void main(String[] args) {
/* it asked me to define this main method here although it's useless in this situation
   */
    }
}
class mysecondclass extends myfirstclass {
    public static void main(String[] args) {
    mysecondclass mysecondobject = new mysecondclass();
    mysecondobject.getX(); //prints nothing
    }
}
</code>```

i am really newbie in java and i am actually still learning it's basics
also i do not know why it always asks me to add the main method in the super class although i have already declared one in the sub class (i heard one main method is enough for one java file)
any help is really appreciated , thanks in advance

答:
You are not understanding the function

```<code>public static void main(String[] args)
</code>```

In Java Docs :

The public static void keywords mean the Java 1 virtual machine (JVM)
  interpreter can call the program's main method to start the program
  (public) without creating an instance of the class (static), and the
  program does not return data to the Java VM interpreter (void) when it
  ends.

You have two

```<code>public static void main(String[] args)
</code>```

In two different classes! You are running or compiling the one that uses myfirstclass So for this type of example or test is a good practice to have only one Java class Main

```<code>public class Main {
    public static void main(String[] args) {
        // Call Your classes
    }
}
</code>```

Be more clean and organized in your code!

And one other thing. For running by Command Line use this type of commands

```<code>java MyApp arg1 arg2
</code>```

When in doubt always read the Docs!

Body:
"mysecondclass" which is a sub class of the super class "myfirstclass"
should inherit all the properties of the super class "myfirstclass"
and it's expected to output the value of x but instead it prints nothing

package myfirstproject;

public class myfirstclass {
    protected int x = 10;
    //getter
    public void getX() {
     System.out.println(x);
    }
    public static void main(String[] args) {
/* it asked me to define this main method here although it's useless in this situation
   */
    }
}
class mysecondclass extends myfirstclass {
    public static void main(String[] args) {
    mysecondclass mysecondobject = new mysecondclass();
    mysecondobject.getX(); //prints nothing
    }
}

i am really newbie in java and i am actually still learning it's basics
also i do not know why it always asks me to add the main method in the super class although i have already declared one in the sub class (i heard one main method is enough for one java file)
any help is really appreciated , thanks in advance

Body:
You are not understanding the function

public static void main(String[] args)

In Java Docs :

The public static void keywords mean the Java 1 virtual machine (JVM)
  interpreter can call the program's main method to start the program
  (public) without creating an instance of the class (static), and the
  program does not return data to the Java VM interpreter (void) when it
  ends.

You have two

public static void main(String[] args)

In two different classes! You are running or compiling the one that uses myfirstclass So for this type of example or test is a good practice to have only one Java class Main

public class Main {
    public static void main(String[] args) {
        // Call Your classes
    }
}

Be more clean and organized in your code!

And one other thing. For running by Command Line use this type of commands

java MyApp arg1 arg2

When in doubt always read the Docs!


问:
Why can’t HashSet just use bit array internally instead of HashMap to save some space?
I see that HashSet in Java internally use HashMap to check whether a HashSet contains a element or not. Can’t it just use a bitmap for storing all the hash results from strings. Eg. String abc hashed to say, 12 index and we can just set this index to show that it is present. It would save lot of space as compared to HashMap as we don’t have to store actual keys in the data.</p>

答:
If a HashSet were used for a contains() lookup only, an optimization like that might be possible. It would still be dangerous, because hash collisions can always occur. I think what you are looking for is a Bloom Filter (note that a Bloom Filter doesn't give exact answers, it just rules out false negatives).

A Hash Set is a collection, and a collection needs to have a possibility to retrieve the values stored. Hashes are not reversible, you can't calculate the original string from its hash.


问:
Google Admin SDK: How to use the service account email instead of a privileged user's for retrieving G Suite logs?
I am using a serverless Python function for retrieving G Suite logs. I have done the following to authenticate against Admin SDK:

1) Created a project
2) Created a service account with the Project->Owner role
3) Create a private key (JSON) file
4) Enabled domain-wide delegation
5) Enabled the Admin SDK
6) Delegate domain-wide authority via 'One or More API Scopes' by authorizing my service account with https://www.googleapis.com/auth/admin.reports.audit.readonly

Now, when running my authorized application I use 1) the username (privileged user's email address) with access to the created service account and 2) the private key (JSON) file for the service account.

When authorizing my application, I use ServiceAccountCredentials from the oauth2client.service_account package.

The Question:

When running my application, I can't authorize against G Suite unless I use the username (email address) of a privileged user. When I substitute this email address for the service account's email address, I can't retrieve G Suite logs.

Is it possible to configure the service account to allow authorization via the service account email address? If so, how can I do that?

答:
I have found the answer to the question. A service account's email address cannot be used.

The proper steps for retrieving G Suite logs is to either 1) use or 2) create a user with the access rights for reviewing the logs.

If a user must be created, this can be done at the user's console on from Google Admin console. After, the appropriate role(s) can be created at Google IAM. Finally, these roles can be applied to the user at the Google Admin console.


问:
If my pipeline rekeys elements - how do I get values for one key in the same worker without GroupByKey?
Let's say I have a pipeline, and I have a series of ParDo operations where element keys change. How can I ensure that elements for the same key some to the same worker without having to do a GroupByKey with windowing?

```<code>input_pcoll = p | beam.ReadFromXYZ(...)

rekeyed_pcoll = (input_pcoll
                 | beam.FlatMap(some_operation)
                 | beam.Map(lambda x: (compute_new_key(x), x['value'])))
</code>```

After this, I would like to have elements of the same key go to the same worker without having to run a GroupByKey that uses windowing or triggering.

答:
There are two ways to accomplish this.

The first one is by doing a GroupByKey, and having a trigger that triggers after every single element. Something like so:

```<code>keys_together_pcoll = (rekeyed_pcoll
                       | beam.WindowInto(window.GlobalWindows()
                                         trigger=AfterCount(1))
                       | beam.GroupByKey()
                       | beam.FlatMap(lambda x: x[1]))

result_pcoll = (keys_together_pcoll
                | beam.ParDo(DoFnWithElementsInCorrespondingWorkers()))
</code>```

Granted, this is a little awkward.

Another way to do this is to make your DoFn stateful. This will force the runner to shuffle the elements into their corresponding workers by key. Something like this:

```<code>class DoFnWithElementsInCorrespondingWorkers(beam.DoFn):
  UNUSED_STATE = BagStateSpec('unused', VarIntCoder())

  def process(self,
              element,
              unused=beam.DoFn.StateParam(UNUSED_STATE)):
    # .. My processing

result_pcoll = (rekeyed_pcoll
                | beam.ParDo(DoFnWithElementsInCorrespondingWorkers()))
</code>```

Why does this happen?

Remember that in Beam (and Flink, and similar systems), state is organized by key, so if you insert a stateful DoFn, Beam will recognize that elements need to be shuffled into the correct workers according to their keys.

Body:
Let's say I have a pipeline, and I have a series of ParDo operations where element keys change. How can I ensure that elements for the same key some to the same worker without having to do a GroupByKey with windowing?

input_pcoll = p | beam.ReadFromXYZ(...)

rekeyed_pcoll = (input_pcoll
                 | beam.FlatMap(some_operation)
                 | beam.Map(lambda x: (compute_new_key(x), x['value'])))

After this, I would like to have elements of the same key go to the same worker without having to run a GroupByKey that uses windowing or triggering.

Body:
There are two ways to accomplish this.

The first one is by doing a GroupByKey, and having a trigger that triggers after every single element. Something like so:

keys_together_pcoll = (rekeyed_pcoll
                       | beam.WindowInto(window.GlobalWindows()
                                         trigger=AfterCount(1))
                       | beam.GroupByKey()
                       | beam.FlatMap(lambda x: x[1]))

result_pcoll = (keys_together_pcoll
                | beam.ParDo(DoFnWithElementsInCorrespondingWorkers()))

Granted, this is a little awkward.

Another way to do this is to make your DoFn stateful. This will force the runner to shuffle the elements into their corresponding workers by key. Something like this:

class DoFnWithElementsInCorrespondingWorkers(beam.DoFn):
  UNUSED_STATE = BagStateSpec('unused', VarIntCoder())

  def process(self,
              element,
              unused=beam.DoFn.StateParam(UNUSED_STATE)):
    # .. My processing

result_pcoll = (rekeyed_pcoll
                | beam.ParDo(DoFnWithElementsInCorrespondingWorkers()))

Why does this happen?

Remember that in Beam (and Flink, and similar systems), state is organized by key, so if you insert a stateful DoFn, Beam will recognize that elements need to be shuffled into the correct workers according to their keys.


问:
Imprecise raycast with orthographic camera in three.js
I'm developing a 2d viewer of CAD drawings using the three.js library and for this project I need to be able to click the objects in the scene to do some operations.

Using orthographic camera the three.js raycasting is not precise as I expect.

Here the code and a fiddle that shows exactly what I mean
https://jsfiddle.net/toriphes/a0o7td1u/

```<code>var camera, scene, renderer, square, raycaster;
init();
animate();

function init() {

  output = document.getElementById('output');

  raycaster = new THREE.Raycaster();
  // Renderer.
  renderer = new THREE.WebGLRenderer();
  //renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  // Add renderer to page
  document.body.appendChild(renderer.domElement);

  // Create camera.
  var aspect = window.innerWidth / window.innerHeight;
  var d = 20;
  camera = new THREE.OrthographicCamera(-window.innerWidth / 2, window.innerWidth / 2, window.innerHeight / 2, -window.innerHeight / 2, 1, 1000);
  camera.position.z = 10;
  camera.position.x = 25;
  camera.position.y = 25;
  camera.zoom = 10
  camera.updateProjectionMatrix()

  controls = new THREE.OrbitControls(camera, renderer.domElement);
  controls.enableRotate = false
  controls.target.x = camera.position.x;
  controls.target.y = camera.position.y;

  controls.update();

  // Create scene.
  scene = new THREE.Scene();

  var points = [
    new THREE.Vector2(10, 10),
    new THREE.Vector2(40, 10),
    new THREE.Vector2(40, 40),
    new THREE.Vector2(10, 40),
    new THREE.Vector2(10, 10)
  ]

  var shape = new THREE.Shape(points);

  var geometry = new THREE.Geometry().setFromPoints(points);

  var square = new THREE.Line(geometry, new THREE.LineBasicMaterial({
    color: 0xFF0000
  }));
  scene.add(square)

  document.addEventListener('mousemove', findIntersections, false);
}

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}

function updateMousePosition(event) {
  return new THREE.Vector3(
    (event.clientX - renderer.domElement.offsetLeft) /
    renderer.domElement.clientWidth *
    2 -
    1,
    -(
      (event.clientY - renderer.domElement.offsetTop) /
      renderer.domElement.clientHeight
    ) *
    2 +
    1,
    0
  );
}

function findIntersections(e) {
  var mouseposition = updateMousePosition(e);
  raycaster.setFromCamera(mouseposition, camera);
  const intersects = raycaster.intersectObjects(scene.children);
  output.innerHTML = intersects.length > 0 ?
    'Intersect: TRUE' :
    'Intersect: FALSE';
}
</code>```

If you pass the mouse near the red square you can see that the intersection trigger before hovering the edge.

What am I doing wrong?

答:
The intersection detection of lines depends on the .linePrecision property of the Raycaster.

e.g.

raycaster.linePrecision = 0.1;
const intersects = raycaster.intersectObjects(scene.children);
```

The parameter has to be set dependent on the scale of the scene. The value of 0.1 is an empirical value, which gives good results for your example. Sadly there is not further information provided in the documentation (perhaps I've overlooked something, but I didn't find one).

Body:
I'm developing a 2d viewer of CAD drawings using the three.js library and for this project I need to be able to click the objects in the scene to do some operations.

Using orthographic camera the three.js raycasting is not precise as I expect.

Here the code and a fiddle that shows exactly what I mean
https://jsfiddle.net/toriphes/a0o7td1u/

var camera, scene, renderer, square, raycaster;
init();
animate();

function init() {

  output = document.getElementById('output');

  raycaster = new THREE.Raycaster();
  // Renderer.
  renderer = new THREE.WebGLRenderer();
  //renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  // Add renderer to page
  document.body.appendChild(renderer.domElement);

  // Create camera.
  var aspect = window.innerWidth / window.innerHeight;
  var d = 20;
  camera = new THREE.OrthographicCamera(-window.innerWidth / 2, window.innerWidth / 2, window.innerHeight / 2, -window.innerHeight / 2, 1, 1000);
  camera.position.z = 10;
  camera.position.x = 25;
  camera.position.y = 25;
  camera.zoom = 10
  camera.updateProjectionMatrix()

  controls = new THREE.OrbitControls(camera, renderer.domElement);
  controls.enableRotate = false
  controls.target.x = camera.position.x;
  controls.target.y = camera.position.y;

  controls.update();

  // Create scene.
  scene = new THREE.Scene();

  var points = [
    new THREE.Vector2(10, 10),
    new THREE.Vector2(40, 10),
    new THREE.Vector2(40, 40),
    new THREE.Vector2(10, 40),
    new THREE.Vector2(10, 10)
  ]

  var shape = new THREE.Shape(points);

  var geometry = new THREE.Geometry().setFromPoints(points);

  var square = new THREE.Line(geometry, new THREE.LineBasicMaterial({
    color: 0xFF0000
  }));
  scene.add(square)

  document.addEventListener('mousemove', findIntersections, false);
}

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}

function updateMousePosition(event) {
  return new THREE.Vector3(
    (event.clientX - renderer.domElement.offsetLeft) /
    renderer.domElement.clientWidth *
    2 -
    1,
    -(
      (event.clientY - renderer.domElement.offsetTop) /
      renderer.domElement.clientHeight
    ) *
    2 +
    1,
    0
  );
}

function findIntersections(e) {
  var mouseposition = updateMousePosition(e);
  raycaster.setFromCamera(mouseposition, camera);
  const intersects = raycaster.intersectObjects(scene.children);
  output.innerHTML = intersects.length > 0 ?
    'Intersect: TRUE' :
    'Intersect: FALSE';
}

If you pass the mouse near the red square you can see that the intersection trigger before hovering the edge.

What am I doing wrong?

Body:
The intersection detection of lines depends on the .linePrecision property of the Raycaster.

e.g.

raycaster.linePrecision = 0.1;
const intersects = raycaster.intersectObjects(scene.children);

The parameter has to be set dependent on the scale of the scene. The value of 0.1 is an empirical value, which gives good results for your example. Sadly there is not further information provided in the documentation (perhaps I've overlooked something, but I didn't find one).


问:
How can I paginate get_context_data choosing from among multiple context objects?
I am trying to paginate get_context_data from views.py, by selecting from among multiple context objects.  Only two choices are shown in the code example conditional statements, but I have several more choices which basically cover all choices from the form submission.  Only one context is returned, in the end however, passing the context to the template view for pagination.

I tried also setting pagination globally in settings.py, but it is not working.

I have viewed the article below, previously, as a guide to pagination on get-context-objects.

How to perform pagination for context object in django?

From views.py:

```<code>from django.shortcuts import render
import django.views.generic
from django.http import HttpResponse
from django.template import loader
from django.template import RequestContext
from ephemera.models import *
from ephemera.serializers import ItemSerializer
from rest_framework import generics
from ephemera.forms import SearchForm, AdvSearchForm
from itertools import chain
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger

class SearchResultsAdvancedView(django.views.generic.ListView):
    template_name = 'ephemera/searchresults_advanced.html'
    form = AdvSearchForm()
    paginate_by = 10
    model = Item

    def get_context_data(self, **kwargs):
        context = super(SearchResultsAdvancedView, self).get_context_data(**kwargs)

        choose_collection = self.request.GET.get('choose_collection')
        user_input = self.request.GET.get('user_input')
        choose_item = self.request.GET.get('choose_item')

        bookpage = False
        imagepage = False

        if choose_collection == 'All' and user_input == '' and choose_item == 'book':
            context['book_qs'] = Item.objects.raw('SELECT  * FROM   ephemera_item WHERE ephemera_item.material_type LIKE %s', ['book']);
            bookpage = True
        elif choose_collection == 'All' and user_input == '' and choose_item == 'image':
            context['image_qs'] = Item.objects.raw('SELECT  * FROM   ephemera_item WHERE ephemera_item.material_type LIKE %s', ['image']);
            imagepage = True

        if bookpage:
            paginator = Paginator(context, self.paginate_by)
            page = self.request.GET.get('page')
            try:
                book_qs = paginator.page(page)
            except PageNotAnInteger:
                book_qs = paginator.page(1)
            except EmptyPage:
                book_qs = paginator.page(paginator.num_pages)
            context['book_qs'] = book_qs

        elif imagepage:
            paginator = Paginator(context, self.paginate_by)
            page = self.request.GET.get('page')
            try:
                image_qs = paginator.page(page)
            except PageNotAnInteger:
                image_qs = paginator.page(1)
            except EmptyPage:
                image_qs = paginator.page(paginator.num_pages)
            context['image_qs'] = image_qs

        return context
</code>```

Errors returned include:

Exception Value:    unhashable type: 'slice'

Exception Location:     c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\django\core\paginator.py in page, line 70

答:
There is no need to use get_context_data [Django-doc] here, you can override get_queryset [Django-doc] and get_context_object_name [Django-doc] to determine the name of the list in your template:

```<code>class SearchResultsAdvancedView(django.views.generic.ListView):
    template_name = 'ephemera/searchresults_advanced.html'
    form = AdvSearchForm()
    paginate_by = 10
    model = Item

    def item_type(self):
        choose_collection = self.request.GET.get('choose_collection')
        if choose_collection != 'All' or not self.request.GET.get('user_input'):
            return None
        choose_item = self.request.GET.get('choose_item')
        if choose_item in ('book', 'image'):
            return choose_item
        return None

    def <b>get_queryset</b>(self, *args, **kwargs):
        item_type = self.get_item_type()
        qs = super.get_queryset(*args, **kwargs)
        if item_type is not None:
            return qs.filter(material_type__iexact=item_type)
        return qs.none()

    def <b>get_context_object_name</b>(self, object_list):
        item_type = self.get_item_type()
        if item_type is not None:
            return '{}_qs'.format(item_type)
        return super().get_context_object_name(object_list)</code>```

Django's logic will paginate the QuerySet itself, you thus do not need to worry about that. This is due to the get_context_data [Django-doc] implementation of the MultipleObjectMixin [Django-doc]:

```<code>def get_context_data(self, *, object_list=None, **kwargs):
    """Get the context for this view."""
    queryset = object_list if object_list is not None else self.object_list
    page_size = self.get_paginate_by(queryset)
    context_object_name = self.get_context_object_name(queryset)
    if page_size:
        <b>paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)</b>
        context = {
            'paginator': paginator,
            'page_obj': page,
            'is_paginated': is_paginated,
            'object_list': queryset
        }
    else:
        context = {
            'paginator': None,
            'page_obj': None,
            'is_paginated': False,
            'object_list': queryset
        }
    if context_object_name is not None:
        context[context_object_name] = queryset
    context.update(kwargs)
    return super().get_context_data(**context)</code>```

That being said, I have the impression that the modeling is not done very well. If you have types of items, it makes sence to define an ItemType model. Furthermore you better use Django's ORM to generate queries instead of raw queries.

Body:
I am trying to paginate get_context_data from views.py, by selecting from among multiple context objects.  Only two choices are shown in the code example conditional statements, but I have several more choices which basically cover all choices from the form submission.  Only one context is returned, in the end however, passing the context to the template view for pagination.

I tried also setting pagination globally in settings.py, but it is not working.

I have viewed the article below, previously, as a guide to pagination on get-context-objects.

How to perform pagination for context object in django?

From views.py:

from django.shortcuts import render
import django.views.generic
from django.http import HttpResponse
from django.template import loader
from django.template import RequestContext
from ephemera.models import *
from ephemera.serializers import ItemSerializer
from rest_framework import generics
from ephemera.forms import SearchForm, AdvSearchForm
from itertools import chain
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger

class SearchResultsAdvancedView(django.views.generic.ListView):
    template_name = 'ephemera/searchresults_advanced.html'
    form = AdvSearchForm()
    paginate_by = 10
    model = Item

    def get_context_data(self, **kwargs):
        context = super(SearchResultsAdvancedView, self).get_context_data(**kwargs)

        choose_collection = self.request.GET.get('choose_collection')
        user_input = self.request.GET.get('user_input')
        choose_item = self.request.GET.get('choose_item')

        bookpage = False
        imagepage = False

        if choose_collection == 'All' and user_input == '' and choose_item == 'book':
            context['book_qs'] = Item.objects.raw('SELECT  * FROM   ephemera_item WHERE ephemera_item.material_type LIKE %s', ['book']);
            bookpage = True
        elif choose_collection == 'All' and user_input == '' and choose_item == 'image':
            context['image_qs'] = Item.objects.raw('SELECT  * FROM   ephemera_item WHERE ephemera_item.material_type LIKE %s', ['image']);
            imagepage = True

        if bookpage:
            paginator = Paginator(context, self.paginate_by)
            page = self.request.GET.get('page')
            try:
                book_qs = paginator.page(page)
            except PageNotAnInteger:
                book_qs = paginator.page(1)
            except EmptyPage:
                book_qs = paginator.page(paginator.num_pages)
            context['book_qs'] = book_qs

        elif imagepage:
            paginator = Paginator(context, self.paginate_by)
            page = self.request.GET.get('page')
            try:
                image_qs = paginator.page(page)
            except PageNotAnInteger:
                image_qs = paginator.page(1)
            except EmptyPage:
                image_qs = paginator.page(paginator.num_pages)
            context['image_qs'] = image_qs

        return context

Errors returned include:

Exception Value:    unhashable type: 'slice'

Exception Location:     c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\django\core\paginator.py in page, line 70

Body:
There is no need to use get_context_data [Django-doc] here, you can override get_queryset [Django-doc] and get_context_object_name [Django-doc] to determine the name of the list in your template:

class SearchResultsAdvancedView(django.views.generic.ListView):
    template_name = 'ephemera/searchresults_advanced.html'
    form = AdvSearchForm()
    paginate_by = 10
    model = Item

    def item_type(self):
        choose_collection = self.request.GET.get('choose_collection')
        if choose_collection != 'All' or not self.request.GET.get('user_input'):
            return None
        choose_item = self.request.GET.get('choose_item')
        if choose_item in ('book', 'image'):
            return choose_item
        return None

    def get_queryset(self, *args, **kwargs):
        item_type = self.get_item_type()
        qs = super.get_queryset(*args, **kwargs)
        if item_type is not None:
            return qs.filter(material_type__iexact=item_type)
        return qs.none()

    def get_context_object_name(self, object_list):
        item_type = self.get_item_type()
        if item_type is not None:
            return '{}_qs'.format(item_type)
        return super().get_context_object_name(object_list)

Django's logic will paginate the QuerySet itself, you thus do not need to worry about that. This is due to the get_context_data [Django-doc] implementation of the MultipleObjectMixin [Django-doc]:

def get_context_data(self, *, object_list=None, **kwargs):
    """Get the context for this view."""
    queryset = object_list if object_list is not None else self.object_list
    page_size = self.get_paginate_by(queryset)
    context_object_name = self.get_context_object_name(queryset)
    if page_size:
        paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
        context = {
            'paginator': paginator,
            'page_obj': page,
            'is_paginated': is_paginated,
            'object_list': queryset
        }
    else:
        context = {
            'paginator': None,
            'page_obj': None,
            'is_paginated': False,
            'object_list': queryset
        }
    if context_object_name is not None:
        context[context_object_name] = queryset
    context.update(kwargs)
    return super().get_context_data(**context)

That being said, I have the impression that the modeling is not done very well. If you have types of items, it makes sence to define an ItemType model. Furthermore you better use Django's ORM to generate queries instead of raw queries.


问:
Unable to cast object of type 'MyType' to type 'Castle.Proxies.MyType'
In which situation following error occurs?

Unable to cast object of type 'MyType' to type 'Castle.Proxies.MyType'.

UPDATE:

I got this error message while binding MyType.FindAllByProperty("col1", "foo"); to a GridView (exactly a Telerik's one: RadGrid). This error is not occuring every time, just sometimes. Here is markup of my grid:

```<code><telerik:RadGrid ID="grdList" runat="server" AutoGenerateColumns="false" OnNeedDataSource="grdList_NeedDataSource"
    OnUpdateCommand="grdList_UpdateCommand" AllowAutomaticUpdates="True" OnItemUpdated="grdList_ItemUpdated"
    AllowMultiRowEdit="true">
    <MasterTableView EditMode="InPlace" DataKeyNames="PageInRole_id" AllowAutomaticUpdates="true">
        <Columns>
            <telerik:GridBoundColumn DataField="ContainerPage.PageTitle" HeaderText="Title" UniqueName="ContainerPage.PageTitle"
                ReadOnly="true" />
        </Columns>
    </MasterTableView>
</telerik:RadGrid>
</code>```

UPDATE2

Here is all exception message and stack trace:

```<code>Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidCastException: Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.]
   Telerik.Web.UI.GetEnumerator>d__0.MoveNext() +175
   Telerik.Web.UI.GridDataTableFromEnumerable.FillDataTableFromEnumerable(IQueryable enumerable) +1285
   Telerik.Web.UI.GridDataTableFromEnumerable.FillData35() +3390
   Telerik.Web.UI.GridDataTableFromEnumerable.FillData() +824
   Telerik.Web.UI.GridResolveEnumerable.EnsureInitialized() +28
   Telerik.Web.UI.GridEnumerableFromDataView..ctor(GridTableView owner, IEnumerable enumerable, Boolean CaseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +242
   Telerik.Web.UI.GridDataSourceHelper.CreateGridEnumerable(GridTableView owner, IEnumerable enumerable, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +223
   Telerik.Web.UI.GridDataSourceHelper.GetResolvedDataSource(GridTableView owner, Object dataSource, String dataMember, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +595
   Telerik.Web.UI.GridTableView.get_ResolvedDataSource() +243
   Telerik.Web.UI.GridTableView.CreateChildControls(IEnumerable dataSource, Boolean useDataSource) +42
   System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +72
   System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +147
   System.Web.UI.WebControls.DataBoundControl.PerformSelect() +261
   Telerik.Web.UI.GridTableView.PerformSelect() +23
   Telerik.Web.UI.GridTableView.DataBind() +363
   Telerik.Web.UI.GridTableView.Rebind() +101
   Telerik.Web.UI.GridCommandEventArgs.ExecuteCommand(Object source) +1174
   Telerik.Web.UI.RadGrid.OnBubbleEvent(Object source, EventArgs e) +185
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70
   Telerik.Web.UI.GridItem.OnBubbleEvent(Object source, EventArgs e) +142
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927
</code>```

答:
This exception probably comes from the code trying to re-attach a proxied/lazy-loading entity to a session. The most likely API call to throw this exception with a newer NHibernate (I don't have problem with 2.1 but I do have problems with latest) is Session.Lock(obj, LockMode.None).

If the programmer of this component first evicts the entity from the ISession and then re-loads it (perhaps cached?) into another one by id, or performs ISession.Update this problem should go away until the NHibernate team has figured out the underlying problem.

Body:
In which situation following error occurs?

Unable to cast object of type 'MyType' to type 'Castle.Proxies.MyType'.

UPDATE:

I got this error message while binding MyType.FindAllByProperty("col1", "foo"); to a GridView (exactly a Telerik's one: RadGrid). This error is not occuring every time, just sometimes. Here is markup of my grid:

<telerik:RadGrid ID="grdList" runat="server" AutoGenerateColumns="false" OnNeedDataSource="grdList_NeedDataSource"
    OnUpdateCommand="grdList_UpdateCommand" AllowAutomaticUpdates="True" OnItemUpdated="grdList_ItemUpdated"
    AllowMultiRowEdit="true">
    <MasterTableView EditMode="InPlace" DataKeyNames="PageInRole_id" AllowAutomaticUpdates="true">
        <Columns>
            <telerik:GridBoundColumn DataField="ContainerPage.PageTitle" HeaderText="Title" UniqueName="ContainerPage.PageTitle"
                ReadOnly="true" />
        </Columns>
    </MasterTableView>
</telerik:RadGrid>

UPDATE2

Here is all exception message and stack trace:

Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidCastException: Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.]
   Telerik.Web.UI.GetEnumerator>d__0.MoveNext() +175
   Telerik.Web.UI.GridDataTableFromEnumerable.FillDataTableFromEnumerable(IQueryable enumerable) +1285
   Telerik.Web.UI.GridDataTableFromEnumerable.FillData35() +3390
   Telerik.Web.UI.GridDataTableFromEnumerable.FillData() +824
   Telerik.Web.UI.GridResolveEnumerable.EnsureInitialized() +28
   Telerik.Web.UI.GridEnumerableFromDataView..ctor(GridTableView owner, IEnumerable enumerable, Boolean CaseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +242
   Telerik.Web.UI.GridDataSourceHelper.CreateGridEnumerable(GridTableView owner, IEnumerable enumerable, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +223
   Telerik.Web.UI.GridDataSourceHelper.GetResolvedDataSource(GridTableView owner, Object dataSource, String dataMember, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +595
   Telerik.Web.UI.GridTableView.get_ResolvedDataSource() +243
   Telerik.Web.UI.GridTableView.CreateChildControls(IEnumerable dataSource, Boolean useDataSource) +42
   System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +72
   System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +147
   System.Web.UI.WebControls.DataBoundControl.PerformSelect() +261
   Telerik.Web.UI.GridTableView.PerformSelect() +23
   Telerik.Web.UI.GridTableView.DataBind() +363
   Telerik.Web.UI.GridTableView.Rebind() +101
   Telerik.Web.UI.GridCommandEventArgs.ExecuteCommand(Object source) +1174
   Telerik.Web.UI.RadGrid.OnBubbleEvent(Object source, EventArgs e) +185
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70
   Telerik.Web.UI.GridItem.OnBubbleEvent(Object source, EventArgs e) +142
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927


问:
How do i fill the session_id from BotTelemetryClient.TrackEvent() Microsoft.Bot.Builder
When tracking events in a bot i use application insights to do transcript logging and logging in general.
However i don't get a session_id/conversation id when tracking events.

According to this information i should always get a session_id and userId.

Session_id empty in customEvent https://imgur.com/mesxtLw
I have based my project on the virtual assistent template for logging.
For logging i use the telemetryloggermiddleware and transcriptloggermiddleware

I expect there would be a session_id and userid, but instead i receive an empty userid and session_id

These are my package references:

"Microsoft.ApplicationInsights" Version="2.9.1"

"Microsoft.ApplicationInsights.AspNetCore" Version="2.6.1"

"Microsoft.Bot.Builder.ApplicationInsights" Version="4.4.4"

"Microsoft.Bot.Builder.Integration.ApplicationInsights.Core"
Version="4.4.4"

"Microsoft.Bot.Builder.Integration.AspNet.Core" Version="4.4.4"

答:
If auto-collection does not populate the necessary property, you can add the value of the required property via Telemetry Initializer:</p>

```<code>  public class MyTelemetryInitializer : ITelemetryInitializer
  {
    public void Initialize(ITelemetry telemetry)
    {
        telemetry.Context.Session.Id = "ConversationIdYouObtainedFromSomeAPI";
    }
  }
</code>```

Body:
If auto-collection does not populate the necessary property, you can add the value of the required property via Telemetry Initializer:

  public class MyTelemetryInitializer : ITelemetryInitializer
  {
    public void Initialize(ITelemetry telemetry)
    {
        telemetry.Context.Session.Id = "ConversationIdYouObtainedFromSomeAPI";
    }
  }


问:
How to get data from 'AudioSource.time' in Unity script?
I am making a Music Player app for Android in Unity3d. For show_currentPlayTime() function, I want to get AS.time value to show current playTime. For seek() function, I want to set AS.time value to get to that specific point of AudioClip. But, the problem is that AS.time is giving me 0.

I have tried setting AudioClip in AudioSource. It works that way, but the audio becomes distorted and shows abnormal behavior.

Variable Declaration:

```<code>public AudioSource AS;
[Range(0.0f, 1.0f)]

public Slider Volume;
public Slider slider;
bool isPlaying;

public List<AudioClip> AC = new List<AudioClip>();
int currentSong = 0;
</code>```

Play Function:

```<code>public void Play()
{
    AS.Stop();
    AS.PlayOneShot(AC[currentSong]);

    //AS.clip = AC[currentSong]; ---
    //AS.Play(); ---
    //AS.clip = AC[currentSong]; ---
    //AS.PlayOneShot(AS.clip); ---

    clipInfo.text = AC[currentSong].name;
    Debug.Log(AC[currentSong].name);

    CancelInvoke();
    Invoke("Next", AC[currentSong].length);
    isPlaying = true;
}
</code>```

The program runs with using --- lines, in above code, but with that, the audio becomes distorted.

Music Seek function:

```<code>public void MusicSlider()
{
    AS.time = AC[currentSong].length * slider.value;
    slider.value = AS.time / AC[currentSong].length;
    Debug.Log(AS.time);
}
</code>```

AS.time gives me value = 0.

答:
The AudioSource.Stop function stops the currently set Audio clip from playing

so you shouldn't be using PlayOneShot since this doesn't assign the clip value and  isn't stopped but played parallel. It is usually more used for playing soundeffects which may occure at the same time.

From AudioSource

You can play a single audio clip using Play, Pause and Stop You can also adjust its volume while playing using the volume property, or seek using time. Multiple sounds can be played on one AudioSource using PlayOneShot.

AudioSource.time from the examples also only seems to work using Play instead of PlayOneShot for the same reason.

In the commented code you are also mixing both Play and PlayOneShot. I guess what you called distorted is actually the clip playing twice at the same time. Your code should rather simply be

```<code>public void Play()
{
    AS.Stop();

    AS.clip = AC[currentSong];
    AS.Play();

    clipInfo.text = AC[currentSong].name;
    Debug.Log(AC[currentSong].name);

    // Don't know ofcourse what those methods do...
    CancelInvoke();
    Invoke("Next", AC[currentSong].length);
    isPlaying = true;
}
</code>```

Body:
I am making a Music Player app for Android in Unity3d. For show_currentPlayTime() function, I want to get AS.time value to show current playTime. For seek() function, I want to set AS.time value to get to that specific point of AudioClip. But, the problem is that AS.time is giving me 0.

I have tried setting AudioClip in AudioSource. It works that way, but the audio becomes distorted and shows abnormal behavior.

Variable Declaration:

public AudioSource AS;
[Range(0.0f, 1.0f)]

public Slider Volume;
public Slider slider;
bool isPlaying;

public List<AudioClip> AC = new List<AudioClip>();
int currentSong = 0;

Play Function:

public void Play()
{
    AS.Stop();
    AS.PlayOneShot(AC[currentSong]);

    //AS.clip = AC[currentSong]; ---
    //AS.Play(); ---
    //AS.clip = AC[currentSong]; ---
    //AS.PlayOneShot(AS.clip); ---

    clipInfo.text = AC[currentSong].name;
    Debug.Log(AC[currentSong].name);

    CancelInvoke();
    Invoke("Next", AC[currentSong].length);
    isPlaying = true;
}

The program runs with using --- lines, in above code, but with that, the audio becomes distorted.

Music Seek function:

public void MusicSlider()
{
    AS.time = AC[currentSong].length * slider.value;
    slider.value = AS.time / AC[currentSong].length;
    Debug.Log(AS.time);
}

AS.time gives me value = 0.

Body:
The AudioSource.Stop function stops the currently set Audio clip from playing

so you shouldn't be using PlayOneShot since this doesn't assign the clip value and  isn't stopped but played parallel. It is usually more used for playing soundeffects which may occure at the same time.

From AudioSource

You can play a single audio clip using Play, Pause and Stop You can also adjust its volume while playing using the volume property, or seek using time. Multiple sounds can be played on one AudioSource using PlayOneShot.

AudioSource.time from the examples also only seems to work using Play instead of PlayOneShot for the same reason.

In the commented code you are also mixing both Play and PlayOneShot. I guess what you called distorted is actually the clip playing twice at the same time. Your code should rather simply be

public void Play()
{
    AS.Stop();

    AS.clip = AC[currentSong];
    AS.Play();

    clipInfo.text = AC[currentSong].name;
    Debug.Log(AC[currentSong].name);

    // Don't know ofcourse what those methods do...
    CancelInvoke();
    Invoke("Next", AC[currentSong].length);
    isPlaying = true;
}