问:
Getting Max URL length exceeded c# MVC
```<code>  function GetUserEditProfileDetails() {
    var res = {};

    res.ID = parseInt($("#User_ID_EditProfile").val());
    res.FirstName = $("#FirstName").val();
    res.LastName = $("#LastName").val();

    res.EmailId = $("#EmailId").val();
    res.Mobile = $("#Mobile").val();
    res.ProfilePic = $(".ProfilePic").attr("src");

    return res;
}

 $.ajax({
        url: "Profile/UpdateUser",
        async: false,
        type: "POST",
        data: GetUserEditProfileDetails(),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        error: function (jqXHR, textStatus, errorThrown) {
            alert(JSON.stringify(jqXHR) + "-" + textStatus + "-" + errorThrown);
        }
    })
</code>```

By using above code, I am trying to save the details of a user. But when the profile pic is too long then the controller method is not calling and it shows internal server error.

答:
Hi Please check below solution :

You need to change maxAllowedContentLength in Web.Config File :

In system.web :

<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
```

<p><strong>And in system.webServer</strong></p>

<pre class="lang-html prettyprint-override"><code><security>
    <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" />
    </requestFiltering>
</security>
</code>```

Cheers !!

Title: Getting Max URL length exceeded c# MVC

Body:
  function GetUserEditProfileDetails() {
    var res = {};

    res.ID = parseInt($("#User_ID_EditProfile").val());
    res.FirstName = $("#FirstName").val();
    res.LastName = $("#LastName").val();

    res.EmailId = $("#EmailId").val();
    res.Mobile = $("#Mobile").val();
    res.ProfilePic = $(".ProfilePic").attr("src");

    return res;
}

 $.ajax({
        url: "Profile/UpdateUser",
        async: false,
        type: "POST",
        data: GetUserEditProfileDetails(),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        error: function (jqXHR, textStatus, errorThrown) {
            alert(JSON.stringify(jqXHR) + "-" + textStatus + "-" + errorThrown);
        }
    })

By using above code, I am trying to save the details of a user. But when the profile pic is too long then the controller method is not calling and it shows internal server error.

Body:
Hi Please check below solution :

You need to change maxAllowedContentLength in Web.Config File :

In system.web :

<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />

And in system.webServer

<security>
    <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" />
    </requestFiltering>
</security>

Cheers !!


来源: stackexchange

问:
A varriable stored only one value, how can I stored more than one value?
I made a program in c by using Binary Search Tree but in my program one function name bill not given me the appropriate result
In my main function I call a function bill like

```<code>  bill();
  printf("Total Bill= %d",total);
</code>```

and actual def of this function is

```<code>int bill()
{
        if(root==NULL)
    {
  printf("No data found");
}
else
 {
  char q[10];
  char a[]="yes";
  int sum=0;

    struct node *temp=root;

  int no;
   printf("Enter Id of work: ");
   scanf("%d",&no);

     if(no>temp->id)
     {
             while(temp!=NULL)
        {
             if(temp->id==no)
             {
            printf("Id: %d\n",temp->id);
            printf("work: %s\n",temp->work);
            printf("Charges: %d\n",temp->charge);
            sum=+temp->charge;
            }
            temp=temp->right;
  }

      }
      else
      {
             while(temp!=NULL)
        {
             if(temp->id==no)
             {
            printf("Id: %d\n",temp->id);
            printf("work: %s\n",temp->work);
            printf("Charges: %d\n",temp->charge);
            sum=+temp->charge;
            }
            temp=temp->left;
  }
     }

   printf("Another Work? \t Yes Or NO?\n");
   scanf("%s",q);

   if(*q=='y')
   {
        bill();

    }

     total=+sum;
   return total;
}

 }
</code>```

in this last if condition when recursive function call another sum came and I want these two sum should stored in total and then return total but
 this total stored only one sum and return this.
so please any one help me to solve it.

答: You can return array in C. And in C++ you can return pair.

ContentLicense: CC BY-SA 3.0

Body:
I made a program in c by using Binary Search Tree but in my program one function name bill not given me the appropriate result
In my main function I call a function bill like

  bill();
  printf("Total Bill= %d",total);

and actual def of this function is

int bill()
{
        if(root==NULL)
    {
  printf("No data found");
}
else
 {
  char q[10];
  char a[]="yes";
  int sum=0;

    struct node *temp=root;

  int no;
   printf("Enter Id of work: ");
   scanf("%d",&no);

     if(no>temp->id)
     {
             while(temp!=NULL)
        {
             if(temp->id==no)
             {
            printf("Id: %d\n",temp->id);
            printf("work: %s\n",temp->work);
            printf("Charges: %d\n",temp->charge);
            sum=+temp->charge;
            }
            temp=temp->right;
  }

      }
      else
      {
             while(temp!=NULL)
        {
             if(temp->id==no)
             {
            printf("Id: %d\n",temp->id);
            printf("work: %s\n",temp->work);
            printf("Charges: %d\n",temp->charge);
            sum=+temp->charge;
            }
            temp=temp->left;
  }
     }

   printf("Another Work? \t Yes Or NO?\n");
   scanf("%s",q);

   if(*q=='y')
   {
        bill();

    }

     total=+sum;
   return total;
}

 }

in this last if condition when recursive function call another sum came and I want these two sum should stored in total and then return total but
 this total stored only one sum and return this.
so please any one help me to solve it.


问:
Android deprecated camera issue
My app uses android.hardware.camera class. The class was deprecated, and even when the app works fine on Android 5.0+ when the client installs it on Android 7.0 the app crash.

I find similar questions (Use of camera2 versus deprecated Camera - what is best practice?), but there is no answer to my specific question.

Since the app is already finished and the camera is not the essential feature. Is there a way to avoid this crash and keep the old camera class?

Crash:

```<code>java.lang.RuntimeException:
  at android.hardware.Camera.<init>(Camera.java:519)
  at android.hardware.Camera.open(Camera.java:379)
  at info.blacktrail.catedral.Camaracap.onResume(Camaracap.java:216)
  at android.support.v4.app.Fragment.performResume(Fragment.java:2235)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1346)
  at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
  at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
  at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
  at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
  at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
  at android.os.Handler.handleCallback(Handler.java:751)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:154)
  at android.app.ActivityThread.main(ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

Fragment:

```<code>public class Cameracap extends Fragment implements View.OnClickListener {

ProgressDialog mProgressDialog;
private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
private FrameLayout camera_preview;

ImageView image, captured_image,image_frame,imageshare,imagetakepic;
Bitmap bmp;
static Bitmap mutableBitmap;
File imageFileName = null;

private MediaScannerConnection msConn;
ProgressDialog dialog;

FragmentManager mFragmentManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.cameraselfie, container, false);

   ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.CAMERA);

    image = (ImageView) rootView.findViewById(R.id.image);

    imageshare= (ImageView) rootView.findViewById(R.id.imageshare);
    imagetakepic= (ImageView) rootView.findViewById(R.id.imagetakepic);

    image_frame = (ImageView) rootView.findViewById(R.id.imageView18);

    captured_image = (ImageView) rootView.findViewById(R.id.captured_image);
    preview = (SurfaceView) rootView.findViewById(R.id.surface_cam);
    camera_preview = (FrameLayout) rootView.findViewById(R.id.camera_preview);

    previewHolder = preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    previewHolder.setFixedSize(getActivity().getWindow().getWindowManager()
            .getDefaultDisplay().getWidth(), getActivity().getWindow().getWindowManager()
            .getDefaultDisplay().getHeight());

    final Button captureButton = (Button) rootView.findViewById(R.id.foto);
    final Button share_image = (Button) rootView.findViewById(R.id.shareface);
    captureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            imageshare.setVisibility(View.VISIBLE);
            share_image.setVisibility(View.VISIBLE);
            imagetakepic.setVisibility(View.GONE);
            captureButton.setVisibility(View.GONE);

            capture();
        }
    });

    share_image.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            imageshare.setVisibility(View.GONE);
            share_image.setVisibility(View.GONE);
            imagetakepic.setVisibility(View.VISIBLE);
            captureButton.setVisibility(View.VISIBLE);

            new Title().execute();

        }
    });

    Button button_back=(Button)rootView.findViewById(R.id.button_back);

    button_back.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mFragmentManager = getActivity().getSupportFragmentManager();

            android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contenedor_principal,new FragmentoInicio()).commit();
        }
    });

    Button emergencia=(Button)rootView.findViewById(R.id.button_sos);
    emergencia.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mFragmentManager = getActivity().getSupportFragmentManager();

            android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contenedor_principal,new Emergencia()).commit();

        }
    });

    Button buttoncam=(Button)rootView.findViewById(R.id.buttoncam);
    buttoncam.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mFragmentManager = getActivity().getSupportFragmentManager();

            android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contenedor_principal,new Camera2BasicFragment()).commit();

        }
    });

    Button configbut=(Button)rootView.findViewById(R.id.button_config);
    configbut.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    });

    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    camera = Camera.open();
}

@Override
public void onPause() {
    if (inPreview) {
        camera.stopPreview();
    }

    camera.release();
    camera = null;
    inPreview = false;
    super.onPause();
}

private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
    Camera.Size result = null;
    for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
        if (size.width <= width && size.height <= height) {
            if (result == null) {
                result = size;
            } else {
                int resultArea = result.width * result.height;
                int newArea = size.width * size.height;
                if (newArea > resultArea) {
                    result = size;
                }
            }
        }
    }
    return (result);
}

SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            camera.setPreviewDisplay(previewHolder);
        } catch (Throwable t) {

            Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }
    }

    public void surfaceChanged(SurfaceHolder holder,
                               int format, int width,
                               int height) {
        Camera.Parameters parameters = camera.getParameters();
        Camera.Size size = getBestPreviewSize(width, height,
                parameters);

        if (size != null) {
            parameters.setPreviewSize(size.width, size.height);
            camera.setParameters(parameters);
            camera.setDisplayOrientation(90);
            camera.startPreview();
            inPreview = true;
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // no-op
    }
};

Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
    public void onPictureTaken(final byte[] data, final Camera camera) {
        dialog = ProgressDialog.show(getActivity(), "", "Guardando foto");
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (Exception ex) {
                }
                onPictureTake(data, camera);
            }
        }.start();
    }
};

public void onPictureTake(byte[] data, Camera camera) {

    bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
    mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
    savePhoto(mutableBitmap);

    dialog.dismiss();

}

public void savePhoto(Bitmap bmp) {

    FileOutputStream out = null;

    try {
        out = new FileOutputStream("/sdcard/"
                + "catedralselfie"
                + ".jpg");
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
        scanPhoto(imageFileName.toString());
        out = null;
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void scanPhoto(final String imageFileName) {
    msConn = new MediaScannerConnection(getActivity(), new MediaScannerConnection.MediaScannerConnectionClient() {
        public void onMediaScannerConnected() {
            msConn.scanFile(imageFileName, null);

        }

        public void onScanCompleted(String path, Uri uri) {
            msConn.disconnect();

        }
    });
    msConn.connect();
}

public void capture() {
    Log.e("onBack :", "yes");
    camera.takePicture(null, null, photoCallback);
    inPreview = false;
}

@Override
public void onClick(View v) {

}

// Title AsyncTask
private class Title extends AsyncTask<Void, Void, Void> {

    Drawable drawable;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setTitle("Cerro Catedral");
        mProgressDialog.setMessage("cargando datos...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        Elements elements, elements1, elements2;

        File imgFile = new File("/sdcard/catedralselfie.jpg");

        if (imgFile.exists()) {

            Bitmap myBitmap2 = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

            Matrix matrix = new Matrix();
            matrix.postRotate(90);
            Bitmap rotatedBitmap = Bitmap.createBitmap(myBitmap2 , 0, 0, myBitmap2.getWidth(), myBitmap2.getHeight(), matrix, true);
            drawable = new BitmapDrawable(getResources(), rotatedBitmap);

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        image_frame.setBackground(drawable);

        shareintento();
        mProgressDialog.dismiss();

    }

}

protected void shareintento() {

    camera_preview.setDrawingCacheEnabled(true);

    camera_preview.buildDrawingCache();

    Bitmap bitmap = camera_preview.getDrawingCache();

    try {
        FileOutputStream out = new FileOutputStream("/sdcard/"
                + "catedralselfie2"
                + ".jpg");
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
    } catch (Exception e) {
        e.printStackTrace();
    }

    File file = new File("/sdcard/catedralselfie2.jpg");

    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    String _text = "#CatedralSelfie #MiSelfieEnCatedral #CatedralInvierno #Bariloche @CerroCatedralok";

    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(String.valueOf(file))));  //optional//use this when you want to send an image

    shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.putExtra(Intent.EXTRA_TEXT, (CharSequence) _text);
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/sdcard/catedralselfie2.jpg")));  //optional//use this when you want to send an image
    shareIntent.setType("image/jpeg");
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(Intent.createChooser(shareIntent, "send"));

    mFragmentManager = getActivity().getSupportFragmentManager();

    android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.contenedor_principal,new FragmentoInicio()).commit();

}
</code>```

}

答:
Use this code for capturing image...

static final int REQUEST_IMAGE_CAPTURE1 = 80;

```<code> Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE1);

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent intent1) {
    super.onActivityResult(requestCode, resultCode, intent1);

    if (requestCode == REQUEST_IMAGE_CAPTURE1) {
        // Handle scan intent

        System.out.println("requestCode " + requestCode);
        System.out.println("resultCode " + resultCode);
        // System.out.println("intent "+intent1.getExtras());

        try {
            Bitmap thumbnail = (Bitmap) intent1.getExtras().get("data");
            //3
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            //4
            String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            final File file = new File(Environment.getExternalStorageDirectory()+File.separator +"1"+ "_" + "2"+"_"+"3"+"_" + timeStamp +".jpg");
            try {
                file.createNewFile();
                FileOutputStream fo = new FileOutputStream(file);
                //5
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (resultCode == RESULT_OK) {

                System.out.println("photoFile" + file);
                }
            }
        }
        catch (Exception e)
        {

        }
    }
     }
</code>```

Title: Android deprecated camera issue

Body:
My app uses android.hardware.camera class. The class was deprecated, and even when the app works fine on Android 5.0+ when the client installs it on Android 7.0 the app crash.

I find similar questions (Use of camera2 versus deprecated Camera - what is best practice?), but there is no answer to my specific question.

Since the app is already finished and the camera is not the essential feature. Is there a way to avoid this crash and keep the old camera class?

Crash:

java.lang.RuntimeException:
  at android.hardware.Camera.<init>(Camera.java:519)
  at android.hardware.Camera.open(Camera.java:379)
  at info.blacktrail.catedral.Camaracap.onResume(Camaracap.java:216)
  at android.support.v4.app.Fragment.performResume(Fragment.java:2235)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1346)
  at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
  at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
  at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
  at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
  at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
  at android.os.Handler.handleCallback(Handler.java:751)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:154)
  at android.app.ActivityThread.main(ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

Fragment:

public class Cameracap extends Fragment implements View.OnClickListener {

ProgressDialog mProgressDialog;
private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
private FrameLayout camera_preview;

ImageView image, captured_image,image_frame,imageshare,imagetakepic;
Bitmap bmp;
static Bitmap mutableBitmap;
File imageFileName = null;

private MediaScannerConnection msConn;
ProgressDialog dialog;

FragmentManager mFragmentManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.cameraselfie, container, false);

   ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.CAMERA);

    image = (ImageView) rootView.findViewById(R.id.image);

    imageshare= (ImageView) rootView.findViewById(R.id.imageshare);
    imagetakepic= (ImageView) rootView.findViewById(R.id.imagetakepic);

    image_frame = (ImageView) rootView.findViewById(R.id.imageView18);

    captured_image = (ImageView) rootView.findViewById(R.id.captured_image);
    preview = (SurfaceView) rootView.findViewById(R.id.surface_cam);
    camera_preview = (FrameLayout) rootView.findViewById(R.id.camera_preview);

    previewHolder = preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    previewHolder.setFixedSize(getActivity().getWindow().getWindowManager()
            .getDefaultDisplay().getWidth(), getActivity().getWindow().getWindowManager()
            .getDefaultDisplay().getHeight());

    final Button captureButton = (Button) rootView.findViewById(R.id.foto);
    final Button share_image = (Button) rootView.findViewById(R.id.shareface);
    captureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            imageshare.setVisibility(View.VISIBLE);
            share_image.setVisibility(View.VISIBLE);
            imagetakepic.setVisibility(View.GONE);
            captureButton.setVisibility(View.GONE);

            capture();
        }
    });

    share_image.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            imageshare.setVisibility(View.GONE);
            share_image.setVisibility(View.GONE);
            imagetakepic.setVisibility(View.VISIBLE);
            captureButton.setVisibility(View.VISIBLE);

            new Title().execute();

        }
    });

    Button button_back=(Button)rootView.findViewById(R.id.button_back);

    button_back.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mFragmentManager = getActivity().getSupportFragmentManager();

            android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contenedor_principal,new FragmentoInicio()).commit();
        }
    });

    Button emergencia=(Button)rootView.findViewById(R.id.button_sos);
    emergencia.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mFragmentManager = getActivity().getSupportFragmentManager();

            android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contenedor_principal,new Emergencia()).commit();

        }
    });

    Button buttoncam=(Button)rootView.findViewById(R.id.buttoncam);
    buttoncam.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mFragmentManager = getActivity().getSupportFragmentManager();

            android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contenedor_principal,new Camera2BasicFragment()).commit();

        }
    });

    Button configbut=(Button)rootView.findViewById(R.id.button_config);
    configbut.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    });

    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    camera = Camera.open();
}

@Override
public void onPause() {
    if (inPreview) {
        camera.stopPreview();
    }

    camera.release();
    camera = null;
    inPreview = false;
    super.onPause();
}

private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
    Camera.Size result = null;
    for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
        if (size.width <= width && size.height <= height) {
            if (result == null) {
                result = size;
            } else {
                int resultArea = result.width * result.height;
                int newArea = size.width * size.height;
                if (newArea > resultArea) {
                    result = size;
                }
            }
        }
    }
    return (result);
}

SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            camera.setPreviewDisplay(previewHolder);
        } catch (Throwable t) {

            Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }
    }

    public void surfaceChanged(SurfaceHolder holder,
                               int format, int width,
                               int height) {
        Camera.Parameters parameters = camera.getParameters();
        Camera.Size size = getBestPreviewSize(width, height,
                parameters);

        if (size != null) {
            parameters.setPreviewSize(size.width, size.height);
            camera.setParameters(parameters);
            camera.setDisplayOrientation(90);
            camera.startPreview();
            inPreview = true;
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // no-op
    }
};

Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
    public void onPictureTaken(final byte[] data, final Camera camera) {
        dialog = ProgressDialog.show(getActivity(), "", "Guardando foto");
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (Exception ex) {
                }
                onPictureTake(data, camera);
            }
        }.start();
    }
};

public void onPictureTake(byte[] data, Camera camera) {

    bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
    mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
    savePhoto(mutableBitmap);

    dialog.dismiss();

}

public void savePhoto(Bitmap bmp) {

    FileOutputStream out = null;

    try {
        out = new FileOutputStream("/sdcard/"
                + "catedralselfie"
                + ".jpg");
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
        scanPhoto(imageFileName.toString());
        out = null;
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void scanPhoto(final String imageFileName) {
    msConn = new MediaScannerConnection(getActivity(), new MediaScannerConnection.MediaScannerConnectionClient() {
        public void onMediaScannerConnected() {
            msConn.scanFile(imageFileName, null);

        }

        public void onScanCompleted(String path, Uri uri) {
            msConn.disconnect();

        }
    });
    msConn.connect();
}

public void capture() {
    Log.e("onBack :", "yes");
    camera.takePicture(null, null, photoCallback);
    inPreview = false;
}

@Override
public void onClick(View v) {

}

// Title AsyncTask
private class Title extends AsyncTask<Void, Void, Void> {

    Drawable drawable;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setTitle("Cerro Catedral");
        mProgressDialog.setMessage("cargando datos...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        Elements elements, elements1, elements2;

        File imgFile = new File("/sdcard/catedralselfie.jpg");

        if (imgFile.exists()) {

            Bitmap myBitmap2 = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

            Matrix matrix = new Matrix();
            matrix.postRotate(90);
            Bitmap rotatedBitmap = Bitmap.createBitmap(myBitmap2 , 0, 0, myBitmap2.getWidth(), myBitmap2.getHeight(), matrix, true);
            drawable = new BitmapDrawable(getResources(), rotatedBitmap);

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        image_frame.setBackground(drawable);

        shareintento();
        mProgressDialog.dismiss();

    }

}

protected void shareintento() {

    camera_preview.setDrawingCacheEnabled(true);

    camera_preview.buildDrawingCache();

    Bitmap bitmap = camera_preview.getDrawingCache();

    try {
        FileOutputStream out = new FileOutputStream("/sdcard/"
                + "catedralselfie2"
                + ".jpg");
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
    } catch (Exception e) {
        e.printStackTrace();
    }

    File file = new File("/sdcard/catedralselfie2.jpg");

    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    String _text = "#CatedralSelfie #MiSelfieEnCatedral #CatedralInvierno #Bariloche @CerroCatedralok";

    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(String.valueOf(file))));  //optional//use this when you want to send an image

    shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.putExtra(Intent.EXTRA_TEXT, (CharSequence) _text);
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/sdcard/catedralselfie2.jpg")));  //optional//use this when you want to send an image
    shareIntent.setType("image/jpeg");
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(Intent.createChooser(shareIntent, "send"));

    mFragmentManager = getActivity().getSupportFragmentManager();

    android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.contenedor_principal,new FragmentoInicio()).commit();

}

}

Body:
Use this code for capturing image...

static final int REQUEST_IMAGE_CAPTURE1 = 80;

 Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE1);

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent intent1) {
    super.onActivityResult(requestCode, resultCode, intent1);

    if (requestCode == REQUEST_IMAGE_CAPTURE1) {
        // Handle scan intent

        System.out.println("requestCode " + requestCode);
        System.out.println("resultCode " + resultCode);
        // System.out.println("intent "+intent1.getExtras());

        try {
            Bitmap thumbnail = (Bitmap) intent1.getExtras().get("data");
            //3
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            //4
            String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            final File file = new File(Environment.getExternalStorageDirectory()+File.separator +"1"+ "_" + "2"+"_"+"3"+"_" + timeStamp +".jpg");
            try {
                file.createNewFile();
                FileOutputStream fo = new FileOutputStream(file);
                //5
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (resultCode == RESULT_OK) {

                System.out.println("photoFile" + file);
                }
            }
        }
        catch (Exception e)
        {

        }
    }
     }


问:
SQLSTATE[IMSSP]: Tried to bind parameter number 2101. SQL Server supports a maximum of 2100 parameters
I am trying to run this query

```<code>$claims = Claim::wherein('policy_id', $userPolicyIds)->where('claim_settlement_status', 'Accepted')->wherebetween('intimation_date', [$startDate, $endDate])->get();
</code>```

Here, $userPolicyIds can have thousands of policy ids. Is there any way I can increase the maximum number of parameters in SQL server? If not, could anyone help me find a way to solve this issue?

答:
The wherein method creates an SQL fragment of the form WHERE policy_id IN (userPolicyIds[0], userPolicyIds[1], userPolicyIds[2]..., userPolicyIds[MAX]).  In other words, the entire collection is unwrapped into the SQL statement.  The result is a HUGE SQL statement that SQL Server refuses to execute.

This is a well known limitation of Microsoft SQL Server.  And it is a hard limit, because there appears to be no option for changing it.  But SQL Server can hardly be blamed for having this limit, because trying to execute a query with as many as 2000 parameters is an unhealthy situation that you should not have put yourself into in the first place.

So, even if there was a way to change the limit, it would still be advisable to leave the limit as it is, and restructure your code instead, so that this unhealthy situation does not arise.

You have at least a couple of options:

Break your query down to batches of, say, 2000 items each.

Add your fields into a temporary table and make your query join that table.

Personally, I would go with the second option, since it will perform much better than anything else, and it is arbitrarily scalable.

Body:
I am trying to run this query

$claims = Claim::wherein('policy_id', $userPolicyIds)->where('claim_settlement_status', 'Accepted')->wherebetween('intimation_date', [$startDate, $endDate])->get();

Here, $userPolicyIds can have thousands of policy ids. Is there any way I can increase the maximum number of parameters in SQL server? If not, could anyone help me find a way to solve this issue?


问:
python script to assign id based on dataframe fields
I'm trying to write an iterative script in python that would see assign an id to a customer based on whether they've met conditions in my lookup table. Normally, I would accomplish this with a sql join, but I need a procedural script that would see whether they've met the conditions that exist in the lookup, then assign them that id. Some attributes are not required or available, so a sql join would not work, since the join would require that all conditions be met. See the example, below:

customers table

```<code>customer attr1 attr2 attr3
jerry    a     r     g
tom      q     e     h
cindy    c     f     j
</code>```

id_lookup table

```<code>id attr1   attr2   attr3
1  a       (null)  g
2  (null)  e       h
3  c       f       (null)
</code>```

final output

```<code>customer  id
jerry     1
tom       2
cindy     3
</code>```

Note that jerry had a match on attr1 and attr3, so met the conditions, thus was assigned 1. The script moves on to the next customer to assign an id procedurally, starting at 1 and moving on in ascending order.

in sql, I would write

```<code>select a.customer
   , b.id
from customers a
join id_lookup b
   on ( a.attr1 = b.attr1
   and a.attr2 = b.attr2
   and a.attr3 = b.attr2 )
</code>```

However, some attributes are not available and since a customer might match many ids, may not be assigned the right once, since the customer should be assigned the id with the lowest value that they qualify for.

Is there a script in python that can accomplish this?

答:
You can do that in SQL.

```<code>select a.name
     , min(b.id)
from customers a
join id_lookup b
    on ( (a.attr1 = b.attr1 or b.attr1 is null)
    and (a.attr2 = b.attr2 or b.attr2 is null)
    and (a.attr3= b.attr3 or b.attr3 is null) )
group by a.name;
</code>```

I'm sure you could also solve the problem in Python, but that would either require writing the equivalent in an ORM (and hence any solution would depend on what ORM you are using) or loading the entire tables into Python and processing them there, which would be impractical if your tables were of significant size.

Body:
I'm trying to write an iterative script in python that would see assign an id to a customer based on whether they've met conditions in my lookup table. Normally, I would accomplish this with a sql join, but I need a procedural script that would see whether they've met the conditions that exist in the lookup, then assign them that id. Some attributes are not required or available, so a sql join would not work, since the join would require that all conditions be met. See the example, below:

customers table

customer attr1 attr2 attr3
jerry    a     r     g
tom      q     e     h
cindy    c     f     j

id_lookup table

id attr1   attr2   attr3
1  a       (null)  g
2  (null)  e       h
3  c       f       (null)

final output

customer  id
jerry     1
tom       2
cindy     3

Note that jerry had a match on attr1 and attr3, so met the conditions, thus was assigned 1. The script moves on to the next customer to assign an id procedurally, starting at 1 and moving on in ascending order.

in sql, I would write

select a.customer
   , b.id
from customers a
join id_lookup b
   on ( a.attr1 = b.attr1
   and a.attr2 = b.attr2
   and a.attr3 = b.attr2 )

However, some attributes are not available and since a customer might match many ids, may not be assigned the right once, since the customer should be assigned the id with the lowest value that they qualify for.

Is there a script in python that can accomplish this?

Body:
You can do that in SQL.

select a.name
     , min(b.id)
from customers a
join id_lookup b
    on ( (a.attr1 = b.attr1 or b.attr1 is null)
    and (a.attr2 = b.attr2 or b.attr2 is null)
    and (a.attr3= b.attr3 or b.attr3 is null) )
group by a.name;

I'm sure you could also solve the problem in Python, but that would either require writing the equivalent in an ORM (and hence any solution would depend on what ORM you are using) or loading the entire tables into Python and processing them there, which would be impractical if your tables were of significant size.


问:
While loading page in mozilla, First DIV code is not loaded
While loading page in mozilla, First DIV code is not loaded
tried to load html using inside

```<code><div id="mainContent"></div>
</code>```

with below call

```<code>if (destinationURL != null) {
$.get(destinationURL, function(data)
{
  $("#mainContent").attr("innerHTML",data);
});
}
</code>```

destinationURL refers below sample html

```<code><div id="A1">
<div id="B1">
    <div id="c1">
        <span>hi</span>
    </div>
    <div id="c2"></div>
</div>
    <div id="B2">
    <div id="D1">
        <span>hi2</span>
    </div>
    <div id="D2"></div>
</div>
<div id="B3">
    <div id="E1"></div>
    <div id="E2"></div>
</div>
<div id="B4">
    <div id="F1"></div>
    <div id="F2"></div>
</div>
</div>
</code>```

but, when html loads

```<code>$("#c1") refers null object
</code>```

if i see

```<code>$("#D1") contains html.
</code>```

if i give alert message on onLoad, i can able to get Html. Its happening only in mozilla

答:
It is a good practice to stick to javascript instead of going for Libraries unless required, the code in javascript for same would be

```<code>if (destinationURL != null) {
$.get(destinationURL, function(data)
{
  document.getElementById("mainContent").innerHTML = data;
});
}
</code>```

on another note, I would suggest you to build the entire structure in a string first and then insert it in DOM. Modifying DOM again and again should be avoided.

ContentLicense: CC BY-SA 2.5

Body:
While loading page in mozilla, First DIV code is not loaded
tried to load html using inside

with below call

if (destinationURL != null) {
$.get(destinationURL, function(data)
{
  $("#mainContent").attr("innerHTML",data);
});
}

destinationURL refers below sample html

        hi

        hi2

but, when html loads

$("#c1") refers null object

if i see

$("#D1") contains html.

if i give alert message on onLoad, i can able to get Html. Its happening only in mozilla

Body:
It is a good practice to stick to javascript instead of going for Libraries unless required, the code in javascript for same would be

if (destinationURL != null) {
$.get(destinationURL, function(data)
{
  document.getElementById("mainContent").innerHTML = data;
});
}

on another note, I would suggest you to build the entire structure in a string first and then insert it in DOM. Modifying DOM again and again should be avoided.


问:
How to keep focus after validation when use tab key
I have input text fields in jsp, and I use onChange="validation(this);" to check if null input and so on, but when I use tab key, cursor will be move to next field, how can keep cursor on validation field?</p>

```<code>function validation(id) {
    var obj = document.getElementById(id);
    obj.value = obj.value.toUpperCase();

    if(value == "") {
        obj.focus();
        obj.select();
    }
 }
</code>```

答:
Adding the validation with button instead onchange event in input box .And if(value == "") value is a undefined so change the if condition with !Obj.value.trim() its catch the false condition .trim() used for remove unwanted space

Updated

use with blur
event instead of onchange .Its only allow to next input only present input was filled.

function validation(obj) {
    obj.value = obj.value.toUpperCase();

    if(!obj.value.trim()) {
        obj.focus();
        //obj.select();
    }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="input" type="text" onblur="validation(this,event)">
<input id="input" type="text" onblur="validation(this,event)"></code>```

Body:
I have input text fields in jsp, and I use onChange="validation(this);" to check if null input and so on, but when I use tab key, cursor will be move to next field, how can keep cursor on validation field?

function validation(id) {
    var obj = document.getElementById(id);
    obj.value = obj.value.toUpperCase();

    if(value == "") {
        obj.focus();
        obj.select();
    }
 }

Body:
Adding the validation with button instead onchange event in input box .And if(value == "") value is a undefined so change the if condition with !Obj.value.trim() its catch the false condition .trim() used for remove unwanted space

Updated

use with blur
event instead of onchange .Its only allow to next input only present input was filled.

function validation(obj) {
    obj.value = obj.value.toUpperCase();

    if(!obj.value.trim()) {
        obj.focus();
        //obj.select();
    }
 }

<input id="input" type="text" onblur="validation(this,event)">
<input id="input" type="text" onblur="validation(this,event)">


问:
Stripe Balance Transactions for connect accounts
Hi I'm working on a project where I have to retrieve a users stripe balance transaction history using the stripe connect api. So I have my users access_token, but I'm having trouble working out how to use that with the Stripe::BalanceTransaction request.

For example if I want to retrieve the balance I can do:

```<code>Stripe::Balance.retrieve({:stripe_account => access_token})
</code>```

However The same thing doesn't work for BalanceTransaction

```<code>Stripe::BalanceTransaction.all({:stripe_account => access_token})
</code>```

Obviously I'm missing something, but after looking through the API documentation, I'm not sure what that is.

答:
```<code>Stripe::BalanceTransaction.all({/*insert params*/},{:stripe_account => access_token})
</code>```

Body:
Hi I'm working on a project where I have to retrieve a users stripe balance transaction history using the stripe connect api. So I have my users access_token, but I'm having trouble working out how to use that with the Stripe::BalanceTransaction request.

For example if I want to retrieve the balance I can do:

Stripe::Balance.retrieve({:stripe_account => access_token})

However The same thing doesn't work for BalanceTransaction

Stripe::BalanceTransaction.all({:stripe_account => access_token})

Obviously I'm missing something, but after looking through the API documentation, I'm not sure what that is.


问:
R Correlation Plots number instead of Text
When i plot the correlation, the column names are not displayed instead number gets displayed.

Why does this happen and how to rectify the same?

Below is the code

```<code>espAlltmNum <- espAlltm[, sapply(espAlltm, is.numeric)]
#above dataset is created as correlation needs only numeric columns
M <- cor(espAlltmNum,use = "pairwise", method = "pearson")
corrplot(M, method = "circle",tl.pos = "d",  tl.cex = 0.5, tl.col = 'black',
         order = "hclust", diag = TRUE,title = "Correlation Plot"
         , mar=c(1,1,1,1))
</code>```

the output is:

答:
i see some issue with corrplot and GGally packages. If the correlation matrix is called before the GGally package/library, the matrix contains the column names(in text).

If the correlation matrix is called after the GGally package/library, matrix contains the index number of the column name. The plot too would give the index number as attached before...

Body:
When i plot the correlation, the column names are not displayed instead number gets displayed.

Why does this happen and how to rectify the same?

Below is the code

espAlltmNum <- espAlltm[, sapply(espAlltm, is.numeric)]
#above dataset is created as correlation needs only numeric columns
M <- cor(espAlltmNum,use = "pairwise", method = "pearson")
corrplot(M, method = "circle",tl.pos = "d",  tl.cex = 0.5, tl.col = 'black',
         order = "hclust", diag = TRUE,title = "Correlation Plot"
         , mar=c(1,1,1,1))

the output is:


问:
<identifier> expected in HackerRank code
I have been trying this code on hackerRank, and I get the following error.

```<code>Solution.java:36: error: <identifier> expected
  System.out.print(ans);
                  ^
Solution.java:36: error: <identifier> expected
  System.out.print(ans);
                      ^
2 errors
</code>```

code:

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
  int n = scan.nextInt();
  scan.close();
  String ans="";

  // if 'n' is NOT evenly divisible by 2 (i.e.: n is odd)
  if(n%2==1){
     ans = "Weird";
  }

   else if (n%2==0)//even no
       {
       if(n>2 && n<=5)
      ans="Not Wierd";
       }

        if(n>6 && n<20)
            {
               ans="Wierd";
             }
        else
        {
     ans="Not Wierd";
           }

  }
  System.out.print(ans);
}
</code>```

What is my mistake?

答:
move your System.out.print(ans); up a line so that it is before }:

```<code>  System.out.print(ans);
}
</code>```

As it stand right now, your System.out code is outside of main().

Body:
I have been trying this code on hackerRank, and I get the following error.

Solution.java:36: error: <identifier> expected
  System.out.print(ans);
                  ^
Solution.java:36: error: <identifier> expected
  System.out.print(ans);
                      ^
2 errors

code:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
  int n = scan.nextInt();
  scan.close();
  String ans="";

  // if 'n' is NOT evenly divisible by 2 (i.e.: n is odd)
  if(n%2==1){
     ans = "Weird";
  }

   else if (n%2==0)//even no
       {
       if(n>2 && n<=5)
      ans="Not Wierd";
       }

        if(n>6 && n<20)
            {
               ans="Wierd";
             }
        else
        {
     ans="Not Wierd";
           }

  }
  System.out.print(ans);
}

What is my mistake?

Body:
move your System.out.print(ans); up a line so that it is before }:

  System.out.print(ans);
}

As it stand right now, your System.out code is outside of main().


答:
Change

```<code> }
  System.out.print(ans);
</code>```

to

```<code>   System.out.print(ans);
}
</code>```

If you correct your indentation it might be easier to spot

Title: <identifier> expected in HackerRank code

Body:
Change

 }
  System.out.print(ans);

to

   System.out.print(ans);
}

If you correct your indentation it might be easier to spot


问:
Fetch IP Address
I want to get ip address of client machine Like I opened website on my machine which is hosted on any server So i need IP address of my machine not hosted server IP.</p>

答:
```<code>HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]
</code>```

use above syntax in C# otherwise you will get error like
Non-invocable member 'System.Web.HttpRequest.ServerVariables' cannot be used like a method.

Title: Fetch IP Address

Body:
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]

use above syntax in C# otherwise you will get error like
Non-invocable member 'System.Web.HttpRequest.ServerVariables' cannot be used like a method.


问:
mysql error 150 from referencing same foreign key column in two tables
I have looked through quite a few posts but havent found the solution for my problem. My suspicion is the error stems from me trying to use a single column to reference the same primary key column in two different tables. Specifically the bid table has the foreign key simulation_id that is also present in the bidder and item_round_status tables. the bid table references the foreign keys of both of these tables but I would like to use only one simulation_id column in the table. Is this the source of the Error 150 problem?

```<code>-- -----------------------------------------------------
-- Table `kffg_simulations`.`item_round_status`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`item_round_status` (
  `simulation_id` INT NOT NULL ,
  `round` INT NOT NULL ,
  `clock_item_id` INT NOT NULL ,
  `posted_price` BIGINT NOT NULL ,
  `clock_price` BIGINT NOT NULL ,
  PRIMARY KEY (`simulation_id`, `round`, `clock_item_id`)  ,
  INDEX `fk_item_round_status_clock_item1_idx` (`clock_item_id` ASC)  ,
  INDEX `fk_item_round_status_simulation1_idx` (`simulation_id` ASC)  ,
  CONSTRAINT `fk_item_round_status_clock_item1`
    FOREIGN KEY (`clock_item_id`)
    REFERENCES `kffg_simulations`.`clock_item` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_item_round_status_simulation1`
    FOREIGN KEY (`simulation_id`)
    REFERENCES `kffg_simulations`.`simulation` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `kffg_simulations`.`bidder`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`bidder` (
  `simulation_id` INT NOT NULL ,
  `idx` INT NOT NULL ,
  `bidder_strategy_id` INT NOT NULL ,
  `budget` BIGINT NOT NULL ,
  PRIMARY KEY (`simulation_id`, `idx`)  ,
  INDEX `fk_bidder_simulation1_idx` (`simulation_id` ASC)  ,
  INDEX `fk_bidder_bidder_strategy1_idx` (`bidder_strategy_id` ASC)  ,
  CONSTRAINT `fk_bidder_simulation1`
    FOREIGN KEY (`simulation_id`)
    REFERENCES `kffg_simulations`.`simulation` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bidder_bidder_strategy1`
    FOREIGN KEY (`bidder_strategy_id`)
    REFERENCES `kffg_simulations`.`bidder_strategy` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `kffg_simulations`.`bid_type`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`bid_type` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(45) NOT NULL ,
  PRIMARY KEY (`id`)  )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `kffg_simulations`.`bid_status`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`bid_status` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `description` VARCHAR(45) NOT NULL ,
  PRIMARY KEY (`id`)  )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `kffg_simulations`.`bid`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`bid` (
  `simulation_id` INT NOT NULL ,
  `item_round_status_round` INT NOT NULL ,
  `clock_item_id` INT NOT NULL ,
  `bidder_idx` INT NOT NULL ,
  `quantity` INT NOT NULL ,
  `price` INT NOT NULL ,
  `bid_type_id` INT NOT NULL ,
  `switch_to_pea_category_id` INT NOT NULL ,
  `backstop` BIGINT NULL ,
  `bid_status_id` INT NOT NULL ,
  `processed_demand` INT NOT NULL ,
  PRIMARY KEY (`simulation_id`, `item_round_status_round`, `clock_item_id`, `bidder_idx`, `quantity`)  ,
  INDEX `fk_bid_item_round_status1_idx` (`simulation_id` ASC, `item_round_status_round` ASC, `clock_item_id` ASC)  ,
  INDEX `fk_bid_bidder1_idx` (`simulation_id` ASC, `bidder_idx` ASC)  ,
  INDEX `fk_bid_bid_type1_idx` (`bid_type_id` ASC)  ,
  INDEX `fk_bid_pea_category1_idx` (`switch_to_pea_category_id` ASC)  ,
  INDEX `fk_bid_bid_status1_idx` (`bid_status_id` ASC)  ,
  CONSTRAINT `fk_bid_item_round_status1`
    FOREIGN KEY (`simulation_id` , `item_round_status_round` , `clock_item_id`)
    REFERENCES `kffg_simulations`.`item_round_status` (`simulation_id` , `round` , `clock_item_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_bidder1`
    FOREIGN KEY (`bidder_idx` , `simulation_id`)
    REFERENCES `kffg_simulations`.`bidder` (`idx` , `simulation_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_bid_type1`
    FOREIGN KEY (`bid_type_id`)
    REFERENCES `kffg_simulations`.`bid_type` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_pea_category1`
    FOREIGN KEY (`switch_to_pea_category_id`)
    REFERENCES `kffg_simulations`.`pea_category` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_bid_status1`
    FOREIGN KEY (`bid_status_id`)
    REFERENCES `kffg_simulations`.`bid_status` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;
</code>```

Updated to show error message:

```<code>------------------------
LATEST FOREIGN KEY ERROR
------------------------
170604 21:52:27 Error in foreign key constraint of table kffg_simulations/bid:

    FOREIGN KEY (`simulation_id` , `item_round_status_round` , `clock_item_id`)
    REFERENCES `kffg_simulations`.`item_round_status` (`simulation_id` , `round` , `clock_item_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_bidder1`
    FOREIGN KEY (`bidder_idx` , `simulation_id`)
    REFERENCES `kffg_simulations`.`bidder` (`idx` , `simulation_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_bid_type1`
    FOREIGN KEY (`bid_type_id`)
    REFERENCES `kffg_simulations`.`bid_type` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_pea_category1`
    FOREIGN KEY (`switch_to_pea_category_id`)
    REFERENCES `kffg_simulations`.`pea_category` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_bid_status1`
    FOREIGN KEY (`bid_status_id`)
    REFERENCES `kffg_simulations`.`bid_status` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
</code>```

Also updated with uml diagram:

答:
Philipxy thank you for your help on this problem. You were correct in the comment that the foreign key for bidder was wrong. For some reason mysql workbench generated the columns in the code in the wrong order. The code provided by mysqlworkbench is below:

```<code>  CONSTRAINT `fk_bid_bidder1`
    FOREIGN KEY (`bidder_idx` , `simulation_id`)
    REFERENCES `kffg_simulations`.`bidder` (`idx` , `simulation_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
</code>```

And the following code works properly:

```<code>  CONSTRAINT `fk_assignment_bidder1`
    FOREIGN KEY (`bidder_simulation_id` , `bidder_idx`)
    REFERENCES `kffg_simulations`.`bidder` (`simulation_id` , `idx`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
</code>```

As far as I can tell I had the indexing setup properly but the code was generate in the wrong order.

(I used mysql workbench forward engineer to generate the sql script. I used the gui to create the relationships between the bid table, bidder, and item_round_status. Since both of those tables have simulationid as pk it duplicated that column. When I manually adjusted the foreign key for bidder to reference the simulationid column generated for item_round_status it changed the indices related to that foreign key. I manually changed them to the proper indices but it seems to ignore my changes when generating the script causing the error.)

Body:
I have looked through quite a few posts but havent found the solution for my problem. My suspicion is the error stems from me trying to use a single column to reference the same primary key column in two different tables. Specifically the bid table has the foreign key simulation_id that is also present in the bidder and item_round_status tables. the bid table references the foreign keys of both of these tables but I would like to use only one simulation_id column in the table. Is this the source of the Error 150 problem?

-- -----------------------------------------------------
-- Table `kffg_simulations`.`item_round_status`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`item_round_status` (
  `simulation_id` INT NOT NULL ,
  `round` INT NOT NULL ,
  `clock_item_id` INT NOT NULL ,
  `posted_price` BIGINT NOT NULL ,
  `clock_price` BIGINT NOT NULL ,
  PRIMARY KEY (`simulation_id`, `round`, `clock_item_id`)  ,
  INDEX `fk_item_round_status_clock_item1_idx` (`clock_item_id` ASC)  ,
  INDEX `fk_item_round_status_simulation1_idx` (`simulation_id` ASC)  ,
  CONSTRAINT `fk_item_round_status_clock_item1`
    FOREIGN KEY (`clock_item_id`)
    REFERENCES `kffg_simulations`.`clock_item` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_item_round_status_simulation1`
    FOREIGN KEY (`simulation_id`)
    REFERENCES `kffg_simulations`.`simulation` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `kffg_simulations`.`bidder`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`bidder` (
  `simulation_id` INT NOT NULL ,
  `idx` INT NOT NULL ,
  `bidder_strategy_id` INT NOT NULL ,
  `budget` BIGINT NOT NULL ,
  PRIMARY KEY (`simulation_id`, `idx`)  ,
  INDEX `fk_bidder_simulation1_idx` (`simulation_id` ASC)  ,
  INDEX `fk_bidder_bidder_strategy1_idx` (`bidder_strategy_id` ASC)  ,
  CONSTRAINT `fk_bidder_simulation1`
    FOREIGN KEY (`simulation_id`)
    REFERENCES `kffg_simulations`.`simulation` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bidder_bidder_strategy1`
    FOREIGN KEY (`bidder_strategy_id`)
    REFERENCES `kffg_simulations`.`bidder_strategy` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `kffg_simulations`.`bid_type`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`bid_type` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(45) NOT NULL ,
  PRIMARY KEY (`id`)  )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `kffg_simulations`.`bid_status`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`bid_status` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `description` VARCHAR(45) NOT NULL ,
  PRIMARY KEY (`id`)  )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `kffg_simulations`.`bid`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `kffg_simulations`.`bid` (
  `simulation_id` INT NOT NULL ,
  `item_round_status_round` INT NOT NULL ,
  `clock_item_id` INT NOT NULL ,
  `bidder_idx` INT NOT NULL ,
  `quantity` INT NOT NULL ,
  `price` INT NOT NULL ,
  `bid_type_id` INT NOT NULL ,
  `switch_to_pea_category_id` INT NOT NULL ,
  `backstop` BIGINT NULL ,
  `bid_status_id` INT NOT NULL ,
  `processed_demand` INT NOT NULL ,
  PRIMARY KEY (`simulation_id`, `item_round_status_round`, `clock_item_id`, `bidder_idx`, `quantity`)  ,
  INDEX `fk_bid_item_round_status1_idx` (`simulation_id` ASC, `item_round_status_round` ASC, `clock_item_id` ASC)  ,
  INDEX `fk_bid_bidder1_idx` (`simulation_id` ASC, `bidder_idx` ASC)  ,
  INDEX `fk_bid_bid_type1_idx` (`bid_type_id` ASC)  ,
  INDEX `fk_bid_pea_category1_idx` (`switch_to_pea_category_id` ASC)  ,
  INDEX `fk_bid_bid_status1_idx` (`bid_status_id` ASC)  ,
  CONSTRAINT `fk_bid_item_round_status1`
    FOREIGN KEY (`simulation_id` , `item_round_status_round` , `clock_item_id`)
    REFERENCES `kffg_simulations`.`item_round_status` (`simulation_id` , `round` , `clock_item_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_bidder1`
    FOREIGN KEY (`bidder_idx` , `simulation_id`)
    REFERENCES `kffg_simulations`.`bidder` (`idx` , `simulation_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_bid_type1`
    FOREIGN KEY (`bid_type_id`)
    REFERENCES `kffg_simulations`.`bid_type` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_pea_category1`
    FOREIGN KEY (`switch_to_pea_category_id`)
    REFERENCES `kffg_simulations`.`pea_category` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_bid_status1`
    FOREIGN KEY (`bid_status_id`)
    REFERENCES `kffg_simulations`.`bid_status` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

Updated to show error message:

------------------------
LATEST FOREIGN KEY ERROR
------------------------
170604 21:52:27 Error in foreign key constraint of table kffg_simulations/bid:

    FOREIGN KEY (`simulation_id` , `item_round_status_round` , `clock_item_id`)
    REFERENCES `kffg_simulations`.`item_round_status` (`simulation_id` , `round` , `clock_item_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_bidder1`
    FOREIGN KEY (`bidder_idx` , `simulation_id`)
    REFERENCES `kffg_simulations`.`bidder` (`idx` , `simulation_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_bid_type1`
    FOREIGN KEY (`bid_type_id`)
    REFERENCES `kffg_simulations`.`bid_type` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_pea_category1`
    FOREIGN KEY (`switch_to_pea_category_id`)
    REFERENCES `kffg_simulations`.`pea_category` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_bid_bid_status1`
    FOREIGN KEY (`bid_status_id`)
    REFERENCES `kffg_simulations`.`bid_status` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.

Also updated with uml diagram:

Body:
Philipxy thank you for your help on this problem. You were correct in the comment that the foreign key for bidder was wrong. For some reason mysql workbench generated the columns in the code in the wrong order. The code provided by mysqlworkbench is below:

  CONSTRAINT `fk_bid_bidder1`
    FOREIGN KEY (`bidder_idx` , `simulation_id`)
    REFERENCES `kffg_simulations`.`bidder` (`idx` , `simulation_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,

And the following code works properly:

  CONSTRAINT `fk_assignment_bidder1`
    FOREIGN KEY (`bidder_simulation_id` , `bidder_idx`)
    REFERENCES `kffg_simulations`.`bidder` (`simulation_id` , `idx`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,

As far as I can tell I had the indexing setup properly but the code was generate in the wrong order.

(I used mysql workbench forward engineer to generate the sql script. I used the gui to create the relationships between the bid table, bidder, and item_round_status. Since both of those tables have simulationid as pk it duplicated that column. When I manually adjusted the foreign key for bidder to reference the simulationid column generated for item_round_status it changed the indices related to that foreign key. I manually changed them to the proper indices but it seems to ignore my changes when generating the script causing the error.)


问:
limited access to a login user that should not be see more then 5 user profile fuelphp framwork
I want to give limited access to a login user that shouldn't be see more then 5 user profiles on that site. If user login in franchiseindia data in php.</p>

答:
Create column history in user table (you will save json_encoded profile_ids and date when he viewed it)

Every time user goes to profile check count of profile_ids in history column by current day.

If less than 5 you update the column with updated json_encoded array, which will include only unique profile_ids visited today.

Else - abort (error him in face)


问:
Select query for filtering data from particular range of year and month
I want to display data from user selected year of March to next year of April(ex:if user selected 2017, then  need to select data from from 2017 march to april 2018 ). What is the best query for filtering it. It should be order by from selected year.</p>

```<code>SELECT DATEPART(mm,submitted_date),SUM(total_count),YEAR(submitted_date)
FROM store_details
WHERE YEAR(submitted_date) = '2017'
AND  MONTH(submitted_date) >=3
Group By YEAR(submitted_date),DATEPART(mm,submitted_date)
Order By YEAR(submitted_date),DATEPART(mm,submitted_date)
</code>```

答:
If you already have the starting month and date in hand, then I don't see why you can't just add an upper bound to the date in your WHERE clause:

```<code>SELECT
    DATEPART(mm, submitted_date),
    SUM(total_count),
    YEAR(submitted_date)
FROM store_details
WHERE
    (YEAR(submitted_date) = '2017' AND MONTH(submitted_date) >= 3) AND
    (YEAR(submitted_date) = '2018' AND MONTH(submitted_date) < 4)
GROUP BY
    YEAR(submitted_date),
    DATEPART(mm, submitted_date)
ORDER BY
    YEAR(submitted_date),
    DATEPART(mm, submitted_date)
</code>```

Body:
I want to display data from user selected year of March to next year of April(ex:if user selected 2017, then  need to select data from from 2017 march to april 2018 ). What is the best query for filtering it. It should be order by from selected year.

SELECT DATEPART(mm,submitted_date),SUM(total_count),YEAR(submitted_date)
FROM store_details
WHERE YEAR(submitted_date) = '2017'
AND  MONTH(submitted_date) >=3
Group By YEAR(submitted_date),DATEPART(mm,submitted_date)
Order By YEAR(submitted_date),DATEPART(mm,submitted_date)

Body:
If you already have the starting month and date in hand, then I don't see why you can't just add an upper bound to the date in your WHERE clause:

SELECT
    DATEPART(mm, submitted_date),
    SUM(total_count),
    YEAR(submitted_date)
FROM store_details
WHERE
    (YEAR(submitted_date) = '2017' AND MONTH(submitted_date) >= 3) AND
    (YEAR(submitted_date) = '2018' AND MONTH(submitted_date) < 4)
GROUP BY
    YEAR(submitted_date),
    DATEPART(mm, submitted_date)
ORDER BY
    YEAR(submitted_date),
    DATEPART(mm, submitted_date)


问:
composer.lock: how does it work?
I'm trying to understand this part: http://getcomposer.org/doc/02-libraries.md#lock-file

this lock file will not have any effect on other projects that depend on it. It only has an effect on the main project"

Does that mean that if project P depends on library A, and library A depends on library B v1.3, project P won't care about the version of library B, and will possibly install B 1.4 instead? What's the point then?

Or does it mean the opposite, as one would expect from a dependency manager?

答: The point of the lock file is to record the exact versions that are installed so they can be re-installed. This means that if you have a version spec of 1.* and your co-worker runs composer update which installs 1.2.4, and then commits the composer.lock file, when you composer install, you will also get 1.2.4, even if 1.3.0 has been released. This ensures everybody working on the project has the same exact version.Read more here Composer: It’s All About the Lock File

Title: composer.lock: how does it work?


问:
To write a function in common lisp that will return the negation of a list
I get this error with my current code:

```<code> LET: illegal variable specification
   (COND (LISTP A (IF (NEGATE A) (NEGATE (REST L)) NIL))
    (T (SETF A (-A) (APPEND (LIST A) (REST L)) (NEGATE (REST L)) NIL)))
</code>```

my current code:

```<code>(defun negate(L)
 (setq x -1)

 (if (not (null L))

  (let ((a (fitst L))
        (cond (listp a
              (if (negate a)
                  (negate (rest L))
                nil))
        (t
         (setf a (-a) (append (list a)(rest L))
               (negate (rest L))
               nil))))
)
))
</code>```

and the test cases it needs to pass

```<code>o List is  (1 2 3 4)
o Output should be: (-1 -2 -3 -4)

o List is  (1 -2 (3 4))
o Output should be: (-1 2 (-3 -4) )
</code>```

答:
I'm not sure if you were looking for a gentle nudge to correct the code presented, or if you're soliciting other ways to do it. My first thought went to mapcar:

```<code>(defun negate-tree (tree)
  (mapcar (lambda (e)
            (cond
              ((null e) nil)
              ((listp e) (negate-tree e))
              (t (- e))))
          tree))
</code>```

You can then generalize out the negation aspect, and write map-tree instead, accepting a function to apply to the atoms in the tree:

```<code>(defun map-tree (f tree)
  (mapcar (lambda (e)
            (cond
              ((null e) nil)
              ((listp e) (map-tree f e))
              (t (funcall f e))))
          tree))
</code>```

You can call on it with, say, the unary negation function:

```<code>(map-tree #'- '(1 -2 (3 4)))
</code>```

Such a call assumes that all the leaves in the tree are either nil accommodated by the unary negation function.

Accepting nil as a possible leaf in the tree makes the visitation algorithm a little messy, and it's not clear whether the provided function f should be applied to all leaves—even those that are nil—so that the function itself can decide whether and how to treat nil.

Another deficiency with this version is how it treats cons cells that are not proper lists. Note that function listp returns true for all cons cells—even those that do not constitute proper lists—but mapcar does require that its input be a proper list. We can wind up along our "listp true" path, recursively calling on mapcar, and have mapcar fail for receiving an improper list. That means that the algorithm above either would need to test cons cells to see if they're proper lists before handing them to mapcar, perhaps treating those that aren't as leaves (I'm reluctant to say "atoms" here), or be documented that the expected tree structure is made up of proper lists of proper lists.

If you need to accept top-level "trees" that are not necessarily lists themselves, meaning that a lone atom is a valid tree, or nil is a valid tree, you can tear apart the constituent parts of the function above and write one that only uses mapcar after determining that the tree under inspection is a list.

Body:
I get this error with my current code:

 LET: illegal variable specification
   (COND (LISTP A (IF (NEGATE A) (NEGATE (REST L)) NIL))
    (T (SETF A (-A) (APPEND (LIST A) (REST L)) (NEGATE (REST L)) NIL)))

my current code:

(defun negate(L)
 (setq x -1)

 (if (not (null L))

  (let ((a (fitst L))
        (cond (listp a
              (if (negate a)
                  (negate (rest L))
                nil))
        (t
         (setf a (-a) (append (list a)(rest L))
               (negate (rest L))
               nil))))
)
))

and the test cases it needs to pass

o List is  (1 2 3 4)
o Output should be: (-1 -2 -3 -4)

o List is  (1 -2 (3 4))
o Output should be: (-1 2 (-3 -4) )

Body:
I'm not sure if you were looking for a gentle nudge to correct the code presented, or if you're soliciting other ways to do it. My first thought went to mapcar:

(defun negate-tree (tree)
  (mapcar (lambda (e)
            (cond
              ((null e) nil)
              ((listp e) (negate-tree e))
              (t (- e))))
          tree))

You can then generalize out the negation aspect, and write map-tree instead, accepting a function to apply to the atoms in the tree:

(defun map-tree (f tree)
  (mapcar (lambda (e)
            (cond
              ((null e) nil)
              ((listp e) (map-tree f e))
              (t (funcall f e))))
          tree))

You can call on it with, say, the unary negation function:

(map-tree #'- '(1 -2 (3 4)))

Such a call assumes that all the leaves in the tree are either nil accommodated by the unary negation function.

Accepting nil as a possible leaf in the tree makes the visitation algorithm a little messy, and it's not clear whether the provided function f should be applied to all leaves—even those that are nil—so that the function itself can decide whether and how to treat nil.

Another deficiency with this version is how it treats cons cells that are not proper lists. Note that function listp returns true for all cons cells—even those that do not constitute proper lists—but mapcar does require that its input be a proper list. We can wind up along our "listp true" path, recursively calling on mapcar, and have mapcar fail for receiving an improper list. That means that the algorithm above either would need to test cons cells to see if they're proper lists before handing them to mapcar, perhaps treating those that aren't as leaves (I'm reluctant to say "atoms" here), or be documented that the expected tree structure is made up of proper lists of proper lists.

If you need to accept top-level "trees" that are not necessarily lists themselves, meaning that a lone atom is a valid tree, or nil is a valid tree, you can tear apart the constituent parts of the function above and write one that only uses mapcar after determining that the tree under inspection is a list.


问:
Is it good practice to group methods into a more general method?
I have a bit of setup work that needs to be done in viewDidLoad. I have added all my helper methods into a configure method, so that in viewDidLoad, I just call configure() and everything works. Is this good practice or is it seen as a bad practice of coupling code together.  Any tip is appreciated!

```<code>//configure() called in viewDidLoad
private func configure() {

    UserProvider.sharedInstance.fetchUser(with: AuthProvider.sharedInstance.currentUserId(), completionHandler: {
        user in
        guard let user = user else { return }
        self.currentUser = user

        self.setupViews(currentUser: user)

        self.setupLocation()
    })
}

private func setupViews(currentUser: User) {
    setupCollectionView()
    updateDatasource(currentUser: currentUser)
}

private func setupCollectionView() {
    collectionView.dataSource = datasource
    collectionView.delegate = datasource
}

private func updateDatasource(currentUser: User) {
    UserProvider.sharedInstance.fetchNearbyUsers(for: currentUser, completionHandler: { nearbyUsers in
        guard nearbyUsers.isEmpty == false else { return }
        self.datasource.update(with: nearbyUsers, collectionView: self.collectionView)
    })
}
</code>```

答:
Yes it's a good practice to  modularize your code into a function.

But the naming should be more readable and understable.

How?

Suppose in your same View controller you want to configure some UI related change. like navigation bar color, navigation title, etc.

And You want to change some contraint value.As well you want to configure network like what you are doing right now. So if you put all of your code into configure function that will create some misunderstanding.In that case, you can break down more like

```<code>func configureUI(){//write ui configuration here}
 func updateConstraintsValue() {//write constraints change code here}
 func configureAuth() { //write Authentication configuration code here}
</code>```

Body:
I have a bit of setup work that needs to be done in viewDidLoad. I have added all my helper methods into a configure method, so that in viewDidLoad, I just call configure() and everything works. Is this good practice or is it seen as a bad practice of coupling code together.  Any tip is appreciated!

//configure() called in viewDidLoad
private func configure() {

    UserProvider.sharedInstance.fetchUser(with: AuthProvider.sharedInstance.currentUserId(), completionHandler: {
        user in
        guard let user = user else { return }
        self.currentUser = user

        self.setupViews(currentUser: user)

        self.setupLocation()
    })
}

private func setupViews(currentUser: User) {
    setupCollectionView()
    updateDatasource(currentUser: currentUser)
}

private func setupCollectionView() {
    collectionView.dataSource = datasource
    collectionView.delegate = datasource
}

private func updateDatasource(currentUser: User) {
    UserProvider.sharedInstance.fetchNearbyUsers(for: currentUser, completionHandler: { nearbyUsers in
        guard nearbyUsers.isEmpty == false else { return }
        self.datasource.update(with: nearbyUsers, collectionView: self.collectionView)
    })
}

Body:
Yes it's a good practice to  modularize your code into a function.

But the naming should be more readable and understable.

How?

Suppose in your same View controller you want to configure some UI related change. like navigation bar color, navigation title, etc.

And You want to change some contraint value.As well you want to configure network like what you are doing right now. So if you put all of your code into configure function that will create some misunderstanding.In that case, you can break down more like

func configureUI(){//write ui configuration here}
 func updateConstraintsValue() {//write constraints change code here}
 func configureAuth() { //write Authentication configuration code here}


问:
Django Framework: Python function in views.py unable to find the json file
I am trying to write into a json file through a python function. The python function dumps the python data structure into a json file using json.dumps funtion.
The file gets created as well as the python data structure in form of json object is present in the json file but when javascript function present inside the python function tries to open and read the object it fails.
I get the following error: Not found file_name.json
I am pretty sure that the file is indeed present.

```<code>def func(request):

arr = [[]]
message = ''
arr[0].append('Hello')
arr[0].append('There')
arr.append([])
arr[1].append('Good')
arr[1].append('Morning')
arr[1].append('!')
message = message + '<html><head><script type="text/javascript" src="outputjson.js"></script><script>function Hello(){alert(hello[1]);}</script></head>'

with open('outputjson.js', 'w') as fo:
        jsonp_structure = "hello = "+json.dumps(arr)+" "
        fo.write(jsonp_structure)
message = message + '<body><h1>This is shit and you know it</h1><input value="Click Bro" type="button" onclick="Hello();"></input></body></html>'
return HttpResponse(message)
</code>```

I get the error stating: Not found: outputjson.js

Do I need to explicitly tell Django where to look for the file ?

答:
```<code>with open('outputjson.js', 'r') as fo:
    fo.read()
</code>```

This should open the file and read it

Body:
I am trying to write into a json file through a python function. The python function dumps the python data structure into a json file using json.dumps funtion.
The file gets created as well as the python data structure in form of json object is present in the json file but when javascript function present inside the python function tries to open and read the object it fails.
I get the following error: Not found file_name.json
I am pretty sure that the file is indeed present.

def func(request):

arr = [[]]
message = ''
arr[0].append('Hello')
arr[0].append('There')
arr.append([])
arr[1].append('Good')
arr[1].append('Morning')
arr[1].append('!')
message = message + ''

with open('outputjson.js', 'w') as fo:
        jsonp_structure = "hello = "+json.dumps(arr)+" "
        fo.write(jsonp_structure)
message = message + '
This is shit and you know it
<input value="Click Bro" type="button" onclick="Hello();"></input>'
return HttpResponse(message)

I get the error stating: Not found: outputjson.js

Do I need to explicitly tell Django where to look for the file ?

Body:
with open('outputjson.js', 'r') as fo:
    fo.read()

This should open the file and read it


问:
How to add a where clause to an EF query which has a grouping
I'm trying to find the number of bookings each user has made. This code works great - it does a join onto bookings and groups them and then does a count.

```<code>var bookingsByUser = from u in _repo.Users()
  join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
  into g
  select new { UserId = u.UserId, TotalBookings = g.Count() };
</code>```

However, I now want to exclude a certain restaurant, so I try to add a where clause:

```<code>var bookingsByUser = from u in _repo.Users()
  join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
  where b.RestaurantId != 21
  into g
  select new { UserId = u.UserId, TotalBookings = g.Count() };
</code>```

However now I get an error "A query body must end with a select clause or a group clause". I can't seem to use "where" on the join table to filter the records before grouping. Is there a better way to do this?

答:
Try this:</p>

```<code>var bookingsByUser = from u in _repo.Users()
                     join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
                     where b.RestaurantId != 21
                     group b by u.UserId into sub
                     select new {
                         UserId = sub.Key,
                         TotalBookings = sub.Count()
                     };
</code>```

Body:
I'm trying to find the number of bookings each user has made. This code works great - it does a join onto bookings and groups them and then does a count.

var bookingsByUser = from u in _repo.Users()
  join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
  into g
  select new { UserId = u.UserId, TotalBookings = g.Count() };

However, I now want to exclude a certain restaurant, so I try to add a where clause:

var bookingsByUser = from u in _repo.Users()
  join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
  where b.RestaurantId != 21
  into g
  select new { UserId = u.UserId, TotalBookings = g.Count() };

However now I get an error "A query body must end with a select clause or a group clause". I can't seem to use "where" on the join table to filter the records before grouping. Is there a better way to do this?

Body:
Try this:

var bookingsByUser = from u in _repo.Users()
                     join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
                     where b.RestaurantId != 21
                     group b by u.UserId into sub
                     select new {
                         UserId = sub.Key,
                         TotalBookings = sub.Count()
                     };


问:
Which are best option(s) to append many props to child component?
Using react 15.5.4

I have a component already configured to cross props in its child.

export default class Component extends React.Component {

  render() {
    return (
      <TemplateAbout
        header={{
         title: 'WHY US',
         description: 'Our Team Member share the same Vision',
        }}
      />
    );
  }
}
```

<p>I want to change the interface of the <code>Component</code> into <code>NewComponent</code> as the example below.</p>

```export default class NewComponent extends React.Component {

  render() {
    return (
      <TemplateAbout>

      </TemplateAbout>
    );
  }
}
```

Which are best ways to do it ?

答:
You can use the object spread syntax to pass props in JSX. It will be combined with the rest of the props.</p>

```<code> render() {
    const header = {
      title: 'WHY US',
      description: 'Our Team Member share the same Vision',
    }
    return (
      <TemplateAbout>
        <Header otherProps="otherValue" {...header} />
      </TemplateAbout>
    );
  }
}
</code>```

Body:
Using react 15.5.4

I have a component already configured to cross props in its child.

export default class Component extends React.Component {

  render() {
    return (
      <TemplateAbout
        header={{
         title: 'WHY US',
         description: 'Our Team Member share the same Vision',
        }}
      />
    );
  }
}

I want to change the interface of the Component into NewComponent as the example below.

export default class NewComponent extends React.Component {

  render() {
    return (
      <TemplateAbout>

      </TemplateAbout>
    );
  }
}

Which are best ways to do it ?

Body:
You can use the object spread syntax to pass props in JSX. It will be combined with the rest of the props.

 render() {
    const header = {
      title: 'WHY US',
      description: 'Our Team Member share the same Vision',
    }
    return (
      <TemplateAbout>
        <Header otherProps="otherValue" {...header} />
      </TemplateAbout>
    );
  }
}


答:
Foreign Key Usage and Error Information gives info on FKs (foreign keys).

you can obtain a detailed explanation of the most recent InnoDB foreign key error by checking the output of SHOW ENGINE INNODB STATUS.

InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.

In bid:

```<code>FOREIGN KEY (`bidder_idx` , `simulation_id`)
REFERENCES `kffg_simulations`.`bidder` (`idx` , `simulation_id`)
</code>```

The "referenced table" here is bidder, the "referenced columns" list is (idx , simulation_id).

```<code>Cannot find an index in the referenced table where the
referenced columns appear as the first columns,
</code>```

Sure enough, in bidder the closest we find is:

```<code>PRIMARY KEY (`simulation_id`, `idx`)  ,
</code>```

which implicitly declares a default unique not null index, but like all the other indexes doesn't start with the FK's column list.

Title: mysql error 150 from referencing same foreign key column in two tables

Body:
Foreign Key Usage and Error Information gives info on FKs (foreign keys).

you can obtain a detailed explanation of the most recent InnoDB foreign key error by checking the output of SHOW ENGINE INNODB STATUS.

InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.

In bid:

FOREIGN KEY (`bidder_idx` , `simulation_id`)
REFERENCES `kffg_simulations`.`bidder` (`idx` , `simulation_id`)

The "referenced table" here is bidder, the "referenced columns" list is (idx , simulation_id).

Cannot find an index in the referenced table where the
referenced columns appear as the first columns,

Sure enough, in bidder the closest we find is:

PRIMARY KEY (`simulation_id`, `idx`)  ,

which implicitly declares a default unique not null index, but like all the other indexes doesn't start with the FK's column list.


问:
How to import module into xcode
I am trying to use socket.io in my swift app.

I am new in swift.

I'm following the instructions from https://github.com/socketio/socket.io-client-swift

but here is the problem, I don't understand how to do the following step.

(Install Manually) "Copy the Source folder into your Xcode project.
  (Make sure you add the files to your target(s))"

I don't understand how to achieve this, I have "Added the SocketIO.h and the entire folder into the project, but no matter what, the module is not found.

Am i supposed to add some binaries, if so what are the binaries? What are the extension? How can I identify it?

Here is the image of my xcode project....image of my screen in xcode

答: If you tried with cocoa pod then you have to import this module, else you have to add only two group like this screen shot, Now you can work without importing the module because of all the swift file by default imported into the whole project.

Title: How to import module into xcode


问:
How "perfect" does a database have to be?
I'm designing a website to track weight lifting and calories. I've never designed my own database before and I figured I should get is as spot on as possible before I start coding. Every time I think I'm done, I get antsy that it's not perfect. I've mostly fleshed it out in MySQL Workbench but I still have a few questions.

How important is it to make the
database "perfect" before hand? How
hard is it to re-factor a database
later?

What does the engine option do? Right
now all tables are defaulting to
InnoDB engine? Any issues with this?

Are dataypes changeable after data
entry? Maybe not going from VARCHAR
to INT, but what about VARCHAR(45) to
VARCHAR(255)?

What are basic database rules that HAVE to
be followed for a successful design?

I've also attached my ERM diagram. If anyone could point out any obvious irregularities it would be greatly appreciated.

答:
The problem with a "perfect SQL database" is that SQL lacks the power to make a "perfect database" beyond a certain trivial level.

But, listen to your teachers and make Codd proud (3NF/BCNF and all that). It's a good bit easier to add caching or temporal un-normalized data later (for performance, when it's needed), etc, than it is to try and fix a database full of bad data. Data wants love. Love it.

That being said here are some thing I'll point out:

exercise looks wrong, wrong, wrong -- secondary1, secondary2, secondaryN ... no thanks! I would not leave the schema like this!

userid is a PK (varchar) but usernumber is an int? Again, no thanks. This doesn't appear to follow the same format as the other tables (most are id) and should be a tip-off that something may not be right. Perhaps the userid (or username?) should just have a unique constraint (you can add indexes to other columns too -- PKs generally "work best" with monotonically increasing values, although DBs should have a re-index schedule as well).

Inconsistent naming (userid vs usernumber vs id). No thanks. I don't care what you choose -- but please do it consistently.

Just my quick review.
Happy developing.


问:
Unable to PUT comment to Jira with Javascript using REST API
I'm trying to update a jira with a new comment through JavaScript.  I can do this all day long with cURL but using javascript is proving more challenging.  I was able to call the Jira API for a GET request for a key so I know my headers/authentication is working.  Problem is my data.  I don't see what I'm doing wrong to format the JSON string with the comment.  Here's what I have so far:

```<code>$.ajax({
type: "PUT",
url: "https://jira.domain.com/rest/api/2/issue/TEST-113",
dataType: "json",
headers: { "Authorization": "Basic " + userCredentials, "Content-Type": "application/json", 'X-Atlassian-Token': 'nocheck' },
data: "{\"update\":{\"comment\":[{\"add\":{\"body\": \"Test comment\"}}]}}",
success: function (json) {

  console.log(json)

},
error: function (xhr, ajaxOptions, thrownError) {
  console.log(xhr.status);
  console.log(thrownError);
  console.log(ajaxOptions);
}
});
</code>```

I keep getting 400 Bad Request back.  Plus ajaxOptions just returns "error" so I don't have any indication from Jira why it's complaining.

Thanks for any guidance.

答:
The issue is propably in this line:

```<code>data: "{\"update\":{\"comment...
</code>```

Get rid of \ and change this to a javascript-object:
data: {"update": "bla bla" ...

I think you just copied over the text from curl.

Body:
I'm trying to update a jira with a new comment through JavaScript.  I can do this all day long with cURL but using javascript is proving more challenging.  I was able to call the Jira API for a GET request for a key so I know my headers/authentication is working.  Problem is my data.  I don't see what I'm doing wrong to format the JSON string with the comment.  Here's what I have so far:

$.ajax({
type: "PUT",
url: "https://jira.domain.com/rest/api/2/issue/TEST-113",
dataType: "json",
headers: { "Authorization": "Basic " + userCredentials, "Content-Type": "application/json", 'X-Atlassian-Token': 'nocheck' },
data: "{\"update\":{\"comment\":[{\"add\":{\"body\": \"Test comment\"}}]}}",
success: function (json) {

  console.log(json)

},
error: function (xhr, ajaxOptions, thrownError) {
  console.log(xhr.status);
  console.log(thrownError);
  console.log(ajaxOptions);
}
});

I keep getting 400 Bad Request back.  Plus ajaxOptions just returns "error" so I don't have any indication from Jira why it's complaining.

Thanks for any guidance.

Body:
The issue is propably in this line:

data: "{\"update\":{\"comment...

Get rid of \ and change this to a javascript-object:
data: {"update": "bla bla" ...

I think you just copied over the text from curl.