问:
Progress Bar findviewbyid returns null
Help me please it's getting frustrating!

i'm doing a chat application where i'm adding views to a linear layout programmatically each time a user press the send button the code is below:

```<code>public  void appendToMessageHistory(String id,String uname, String messa,String messageType, final String filepath, String DownloadStatus,boolean internet,int type) {

    //TextView tv=new TextView(Messaging.this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(Width, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(0, 10, 0, 0);

    View v = getLayoutInflater().inflate(R.layout.message_entity, null);

    TextView mess;
    TextView time;
    final ImageView iv;
    final ProgressBar progressBar;
    ImageView statusiv;
    if (friend.userName.equals(uname)) {
        v = getLayoutInflater().inflate(R.layout.message_entity, null);
        v.setId(Integer.parseInt(id));
        mess = (TextView) v.findViewById(R.id.message_entity_message);
        time = (TextView) v.findViewById(R.id.message_entity_time);
        iv = (ImageView) v.findViewById(R.id.message_entity_imageview);
        statusiv = (ImageView) v.findViewById(R.id.imageView);
        progressBar = (ProgressBar) v.findViewById(R.id.message_entity_progressbar);
    } else {
        v = getLayoutInflater().inflate(R.layout.message_entity_right, null);
        lp.gravity = Gravity.RIGHT;
        v.setId(Integer.parseInt(id));
        mess = (TextView) v.findViewById(R.id.message_entity_right_message);
        time = (TextView) v.findViewById(R.id.message_entity_right_time);
        iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
        statusiv = (ImageView)v.findViewById(R.id.imageViewleft);
        progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar);
    }

    try {
        progressBar.setId(Integer.parseInt(id));

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

    if (messageType != null) {
        if (messageType.equals(MessageInfo.MESSAGE_TYPE_PIC)) {
            iv.setImageBitmap(ImageHandlet.GetBitmapFromPath(filepath));
            progressBar.setVisibility(View.GONE);
            iv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse("file://" + filepath), "image/png");
                    startActivity(intent);
                    Log.d("FIlePAth", filepath);
                }
            });

        } else if (messageType.equals(MessageInfo.MESSAGE_TYPE_VIDEO)) {
            if (DownloadStatus.equals(LocalStorageHandler.DOWNLOADED)) {
                if(!(friend.userName.equals(uname))) {
                    if (type != 3) {
                        Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MINI_KIND);
                        iv.setImageBitmap(bitTh);
                        progressBar.setVisibility(View.GONE);
                        iv.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filepath));
                                intent.setDataAndType(Uri.parse(filepath), "video/mp4");
                                startActivity(intent);

                            }
                        });
                    } else {
                        Log.w("Zipping","Progress Bar");
                        progressBar.setVisibility(View.VISIBLE);
                    }
                } else {
                    Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MINI_KIND);
                    iv.setImageBitmap(bitTh);
                    progressBar.setVisibility(View.GONE);
                    iv.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filepath));
                            intent.setDataAndType(Uri.parse(filepath), "video/mp4");
                            startActivity(intent);

                        }
                    });
                }
            } else if (DownloadStatus.equals(LocalStorageHandler.NotDOWNLOADED)) {
                iv.setTag(id);
                iv.setImageResource(R.drawable.download);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        progressBar.setVisibility(View.VISIBLE);
                        Cursor c = localstoragehandler.getIDnfo(iv.getTag().toString());
                        String filepath = "";
                        //Toast.makeText(getApplication(),iv.getTag().toString()+" iD " +iv.getId(),Toast.LENGTH_SHORT).show();

                        while (c.moveToNext()) {
                            String msg0 = c.getString(0);
                            String msg2 = c.getString(2);
                            String msg3 = c.getString(3);
                            String msg4 = c.getString(4);
                            String msg5 = c.getString(5);
                            String msg6 = c.getString(6);

                            filepath = msg5;

                            Log.d("-----------Vedio-----", "------------------");
                            Log.d("DATABASE---------", msg0);
                            Log.d("DATABASE-------", msg2);
                            Log.d("DATABASE---------", msg3);
                            Log.d("DATABASE-----", msg4 + "");
                            Log.d("DATABASE-------", msg5 + "");
                            Log.d("DATABASE----------", msg6 + "");
                            Log.d("--------END-------", "-------END-----------");

                        }

                        Toast.makeText(getApplicationContext(), filepath.toString() + iv.getTag().toString(), Toast.LENGTH_SHORT).show();

                        DownloadFileFromURL downloadFileFromURL = new DownloadFileFromURL(filepath, iv.getTag().toString());
                        downloadFileFromURL.execute("");
                    }
                });
            }
        } else {
            iv.setVisibility(View.GONE);
            progressBar.setVisibility(View.GONE);
        }
    }
    if(!(messageType.equals(MessageInfo.MESSAGE_TYPE_VIDEO))) {
        if (!internet) {
            statusiv.setImageResource(R.drawable.noconnectionl);
        }
    }
    mess.setText(messa);
    //time.setText(sendt);
    v.setLayoutParams(lp);
    final View lastview = v;
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mEssageBox.addView(lastview);

        }
    });
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(View.FOCUS_DOWN);
            messageText.requestFocus();
        }
    });
}
</code>```

and here is the XML of the dialogbox:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layoutDirection="ltr">

<ImageView
    android:id="@+id/imageViewleft"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/chaticion" />

<RelativeLayout
    android:id="@+id/tests"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#83e3ed"
    android:layoutDirection="rtl"
    android:padding="5dp"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/imageViewleft"
    android:layout_toStartOf="@+id/imageViewleft">

    <TextView
        android:id="@+id/message_entity_right_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="19dp"
        android:layout_marginRight="19dp"
        android:text="Large ffText"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textIsSelectable="true" />

    <TextView
        android:id="@+id/message_entity_right_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/message_entity_right_message"
        android:paddingRight="10dp"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/message_entity_right_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_below="@+id/message_entity_right_time"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"

        android:src="@drawable/ic_launcher" />

    <ProgressBar
        android:id="@+id/message_entity_Right_progressbar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_below="@+id/message_entity_right_time"

        android:indeterminate="false"
        android:visibility="invisible" />

</RelativeLayout>
</code>```

And here is the code to send the video message:

```<code>final String message = messageText.getText().toString();
    final Long rowid = localstoragehandler.insert(imService.getUsername(), friend.userName, message, MessageInfo.MESSAGE_TYPE_VIDEO, ZippedVideoPath, LocalStorageHandler.DOWNLOADED); //insert data into db and get to chat_id
    appendToMessageHistory(rowid + "", imService.getUsername(), message, MessageInfo.MESSAGE_TYPE_VIDEO, ZippedVideoPath, LocalStorageHandler.DOWNLOADED, internet,3);// append the video with type 3 to just display the progress
    messageText.setText("Video");
    String newstr = null;
    // intialize the asynctask to upload the video
    class UploadVideo extends AsyncTask<Void, Void, String> {
        ProgressDialog uploading;
        View V;
        UploadVideo(View v){
            V = v;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //          uploading = ProgressDialog.show(Messaging.this, "Uploading File", "Please wait...", false, false);
        }

        @Override
        protected String doInBackground(Void... params) {
            return imService.sendVideoMessage(imService.getUsername(), friend.userName, message, MessageInfo.MESSAGE_TYPE_VIDEO, "", ZippedVideoPath);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
         //   RelativeLayout v = (RelativeLayout) V.findViewById(rowid.intValue());
        //    Log.w("Zipping",v.toString());
     //       ProgressBar progressBar1 = (ProgressBar) V.findViewById(R.id.message_entity_Right_progressbar);
      //      Log.w("Zipping",progressBar1.toString());
            //          ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
       //     progressBar1.setVisibility(View.GONE);
        //  Log.d("POST Execute", s + "");

            //textViewResponse.setText(Html.fromHtml("<b>Uploaded at <a href='" + s + "'>" + s + "</a></b>"));
            //textViewResponse.setMovementMethod(LinkMovementMethod.getInstance());
    // here i am preparing the path so when the compress is done to save into.
        }
    }
    if (null != absolute && absolute.length() > 0) {
        int endIndex = absolute.lastIndexOf("/");
        if (endIndex != -1) {
            newstr = absolute.substring(endIndex, absolute.length()); // not forgot to put check if(endIndex != -1)
        }
    }
    Log.w("Zipping", newstr);
    final File videosdir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/videos/");
    if (!videosdir.exists()) {
        videosdir.mkdirs();
    }
    ZippedVideoPath = videosdir.getAbsolutePath() + "/" + newstr;
    Log.w("Zipping", ZippedVideoPath);
    // here i got the ffmpeg library from the net to compress the video and i'm preparing the commands
    String[] complexCommand = {"-y", "-i", absolute, "-strict", "experimental", "-r", "25", "-vcodec", "mpeg4", "-b:a", "150k", "-ab", "48000", "-ac", "2", "-ar", "22050", ZippedVideoPath};
    FFmpeg ffmpeg = FFmpeg.getInstance(getBaseContext());
    try {
        // to execute "ffmpeg -version" command you just need to pass "-version"
        ffmpeg.execute(complexCommand, new ExecuteBinaryResponseHandler() {

            @Override
            public void onStart() {
                Log.w("Zipping", "started");
            }

            @Override
            public void onProgress(String message) {
            }

            @Override
            public void onFailure(String message) {
                Log.w("Zipping", message);
            }

            @Override
            public void onSuccess(String message1) {
                Log.w("Zipping","Success");
                RelativeLayout v = (RelativeLayout) mEssageBox.findViewById(rowid.intValue());
                Log.w("VideoView",v.toString());
                ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar);
                ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
            //  progressBar.setVisibility(View.GONE);
                Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(ZippedVideoPath, MediaStore.Images.Thumbnails.MINI_KIND);
                iv.setImageBitmap(bitTh);
                progressBar.setVisibility(View.GONE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ZippedVideoPath));
                        intent.setDataAndType(Uri.parse(ZippedVideoPath), "video/mp4");
                        startActivity(intent);

                    }
                });
                UploadVideo uv = new UploadVideo(v);
                uv.execute();
            }

            @Override
            public void onFinish() {
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        Log.w("Zipping", e.toString());
    }
}
</code>```

okay now to the problem when i call the findviewbyid for the progress bar in sendvideomessage ffmpeg onsuccess callback it returns null even though the findviewbyid for the the imageview which is in the same layout it returns the view! so please tell me what is the problem

```<code>public void onSuccess(String message1) {
                Log.w("Zipping","Success");
                RelativeLayout v = (RelativeLayout) mEssageBox.findViewById(rowid.intValue()); ;
                ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar); // this keeps returning null!
                ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview); // returns the view
            //  progressBar.setVisibility(View.GONE);
                Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(ZippedVideoPath, MediaStore.Images.Thumbnails.MINI_KIND);
                iv.setImageBitmap(bitTh);
                progressBar.setVisibility(View.GONE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ZippedVideoPath));
                        intent.setDataAndType(Uri.parse(ZippedVideoPath), "video/mp4");
                        startActivity(intent);

                    }
                });
                UploadVideo uv = new UploadVideo(v);
                uv.execute();
            }
</code>```

Thank you!

答: Hello Based on JHH Answer, i tried what he suggested to set a tag for the layout and call it from there it didn't work so i tried to set the tag for the progress bar and and findviewbytag for the progress bar and it worked! strange behavior, anyway thanks for the help!</p>

Title: Progress Bar findviewbyid returns null

Body:
Help me please it's getting frustrating!

i'm doing a chat application where i'm adding views to a linear layout programmatically each time a user press the send button the code is below:

public  void appendToMessageHistory(String id,String uname, String messa,String messageType, final String filepath, String DownloadStatus,boolean internet,int type) {

    //TextView tv=new TextView(Messaging.this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(Width, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(0, 10, 0, 0);

    View v = getLayoutInflater().inflate(R.layout.message_entity, null);

    TextView mess;
    TextView time;
    final ImageView iv;
    final ProgressBar progressBar;
    ImageView statusiv;
    if (friend.userName.equals(uname)) {
        v = getLayoutInflater().inflate(R.layout.message_entity, null);
        v.setId(Integer.parseInt(id));
        mess = (TextView) v.findViewById(R.id.message_entity_message);
        time = (TextView) v.findViewById(R.id.message_entity_time);
        iv = (ImageView) v.findViewById(R.id.message_entity_imageview);
        statusiv = (ImageView) v.findViewById(R.id.imageView);
        progressBar = (ProgressBar) v.findViewById(R.id.message_entity_progressbar);
    } else {
        v = getLayoutInflater().inflate(R.layout.message_entity_right, null);
        lp.gravity = Gravity.RIGHT;
        v.setId(Integer.parseInt(id));
        mess = (TextView) v.findViewById(R.id.message_entity_right_message);
        time = (TextView) v.findViewById(R.id.message_entity_right_time);
        iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
        statusiv = (ImageView)v.findViewById(R.id.imageViewleft);
        progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar);
    }

    try {
        progressBar.setId(Integer.parseInt(id));

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

    if (messageType != null) {
        if (messageType.equals(MessageInfo.MESSAGE_TYPE_PIC)) {
            iv.setImageBitmap(ImageHandlet.GetBitmapFromPath(filepath));
            progressBar.setVisibility(View.GONE);
            iv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse("file://" + filepath), "image/png");
                    startActivity(intent);
                    Log.d("FIlePAth", filepath);
                }
            });

        } else if (messageType.equals(MessageInfo.MESSAGE_TYPE_VIDEO)) {
            if (DownloadStatus.equals(LocalStorageHandler.DOWNLOADED)) {
                if(!(friend.userName.equals(uname))) {
                    if (type != 3) {
                        Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MINI_KIND);
                        iv.setImageBitmap(bitTh);
                        progressBar.setVisibility(View.GONE);
                        iv.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filepath));
                                intent.setDataAndType(Uri.parse(filepath), "video/mp4");
                                startActivity(intent);

                            }
                        });
                    } else {
                        Log.w("Zipping","Progress Bar");
                        progressBar.setVisibility(View.VISIBLE);
                    }
                } else {
                    Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MINI_KIND);
                    iv.setImageBitmap(bitTh);
                    progressBar.setVisibility(View.GONE);
                    iv.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filepath));
                            intent.setDataAndType(Uri.parse(filepath), "video/mp4");
                            startActivity(intent);

                        }
                    });
                }
            } else if (DownloadStatus.equals(LocalStorageHandler.NotDOWNLOADED)) {
                iv.setTag(id);
                iv.setImageResource(R.drawable.download);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        progressBar.setVisibility(View.VISIBLE);
                        Cursor c = localstoragehandler.getIDnfo(iv.getTag().toString());
                        String filepath = "";
                        //Toast.makeText(getApplication(),iv.getTag().toString()+" iD " +iv.getId(),Toast.LENGTH_SHORT).show();

                        while (c.moveToNext()) {
                            String msg0 = c.getString(0);
                            String msg2 = c.getString(2);
                            String msg3 = c.getString(3);
                            String msg4 = c.getString(4);
                            String msg5 = c.getString(5);
                            String msg6 = c.getString(6);

                            filepath = msg5;

                            Log.d("-----------Vedio-----", "------------------");
                            Log.d("DATABASE---------", msg0);
                            Log.d("DATABASE-------", msg2);
                            Log.d("DATABASE---------", msg3);
                            Log.d("DATABASE-----", msg4 + "");
                            Log.d("DATABASE-------", msg5 + "");
                            Log.d("DATABASE----------", msg6 + "");
                            Log.d("--------END-------", "-------END-----------");

                        }

                        Toast.makeText(getApplicationContext(), filepath.toString() + iv.getTag().toString(), Toast.LENGTH_SHORT).show();

                        DownloadFileFromURL downloadFileFromURL = new DownloadFileFromURL(filepath, iv.getTag().toString());
                        downloadFileFromURL.execute("");
                    }
                });
            }
        } else {
            iv.setVisibility(View.GONE);
            progressBar.setVisibility(View.GONE);
        }
    }
    if(!(messageType.equals(MessageInfo.MESSAGE_TYPE_VIDEO))) {
        if (!internet) {
            statusiv.setImageResource(R.drawable.noconnectionl);
        }
    }
    mess.setText(messa);
    //time.setText(sendt);
    v.setLayoutParams(lp);
    final View lastview = v;
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mEssageBox.addView(lastview);

        }
    });
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(View.FOCUS_DOWN);
            messageText.requestFocus();
        }
    });
}

and here is the XML of the dialogbox:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layoutDirection="ltr">

<ImageView
    android:id="@+id/imageViewleft"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/chaticion" />

<RelativeLayout
    android:id="@+id/tests"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#83e3ed"
    android:layoutDirection="rtl"
    android:padding="5dp"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/imageViewleft"
    android:layout_toStartOf="@+id/imageViewleft">

    <TextView
        android:id="@+id/message_entity_right_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="19dp"
        android:layout_marginRight="19dp"
        android:text="Large ffText"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textIsSelectable="true" />

    <TextView
        android:id="@+id/message_entity_right_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/message_entity_right_message"
        android:paddingRight="10dp"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/message_entity_right_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_below="@+id/message_entity_right_time"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"

        android:src="@drawable/ic_launcher" />

    <ProgressBar
        android:id="@+id/message_entity_Right_progressbar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_below="@+id/message_entity_right_time"

        android:indeterminate="false"
        android:visibility="invisible" />

</RelativeLayout>

And here is the code to send the video message:

final String message = messageText.getText().toString();
    final Long rowid = localstoragehandler.insert(imService.getUsername(), friend.userName, message, MessageInfo.MESSAGE_TYPE_VIDEO, ZippedVideoPath, LocalStorageHandler.DOWNLOADED); //insert data into db and get to chat_id
    appendToMessageHistory(rowid + "", imService.getUsername(), message, MessageInfo.MESSAGE_TYPE_VIDEO, ZippedVideoPath, LocalStorageHandler.DOWNLOADED, internet,3);// append the video with type 3 to just display the progress
    messageText.setText("Video");
    String newstr = null;
    // intialize the asynctask to upload the video
    class UploadVideo extends AsyncTask<Void, Void, String> {
        ProgressDialog uploading;
        View V;
        UploadVideo(View v){
            V = v;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //          uploading = ProgressDialog.show(Messaging.this, "Uploading File", "Please wait...", false, false);
        }

        @Override
        protected String doInBackground(Void... params) {
            return imService.sendVideoMessage(imService.getUsername(), friend.userName, message, MessageInfo.MESSAGE_TYPE_VIDEO, "", ZippedVideoPath);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
         //   RelativeLayout v = (RelativeLayout) V.findViewById(rowid.intValue());
        //    Log.w("Zipping",v.toString());
     //       ProgressBar progressBar1 = (ProgressBar) V.findViewById(R.id.message_entity_Right_progressbar);
      //      Log.w("Zipping",progressBar1.toString());
            //          ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
       //     progressBar1.setVisibility(View.GONE);
        //  Log.d("POST Execute", s + "");

            //textViewResponse.setText(Html.fromHtml("Uploaded at " + s + ""));
            //textViewResponse.setMovementMethod(LinkMovementMethod.getInstance());
    // here i am preparing the path so when the compress is done to save into.
        }
    }
    if (null != absolute && absolute.length() > 0) {
        int endIndex = absolute.lastIndexOf("/");
        if (endIndex != -1) {
            newstr = absolute.substring(endIndex, absolute.length()); // not forgot to put check if(endIndex != -1)
        }
    }
    Log.w("Zipping", newstr);
    final File videosdir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/videos/");
    if (!videosdir.exists()) {
        videosdir.mkdirs();
    }
    ZippedVideoPath = videosdir.getAbsolutePath() + "/" + newstr;
    Log.w("Zipping", ZippedVideoPath);
    // here i got the ffmpeg library from the net to compress the video and i'm preparing the commands
    String[] complexCommand = {"-y", "-i", absolute, "-strict", "experimental", "-r", "25", "-vcodec", "mpeg4", "-b:a", "150k", "-ab", "48000", "-ac", "2", "-ar", "22050", ZippedVideoPath};
    FFmpeg ffmpeg = FFmpeg.getInstance(getBaseContext());
    try {
        // to execute "ffmpeg -version" command you just need to pass "-version"
        ffmpeg.execute(complexCommand, new ExecuteBinaryResponseHandler() {

            @Override
            public void onStart() {
                Log.w("Zipping", "started");
            }

            @Override
            public void onProgress(String message) {
            }

            @Override
            public void onFailure(String message) {
                Log.w("Zipping", message);
            }

            @Override
            public void onSuccess(String message1) {
                Log.w("Zipping","Success");
                RelativeLayout v = (RelativeLayout) mEssageBox.findViewById(rowid.intValue());
                Log.w("VideoView",v.toString());
                ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar);
                ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
            //  progressBar.setVisibility(View.GONE);
                Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(ZippedVideoPath, MediaStore.Images.Thumbnails.MINI_KIND);
                iv.setImageBitmap(bitTh);
                progressBar.setVisibility(View.GONE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ZippedVideoPath));
                        intent.setDataAndType(Uri.parse(ZippedVideoPath), "video/mp4");
                        startActivity(intent);

                    }
                });
                UploadVideo uv = new UploadVideo(v);
                uv.execute();
            }

            @Override
            public void onFinish() {
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        Log.w("Zipping", e.toString());
    }
}

okay now to the problem when i call the findviewbyid for the progress bar in sendvideomessage ffmpeg onsuccess callback it returns null even though the findviewbyid for the the imageview which is in the same layout it returns the view! so please tell me what is the problem

public void onSuccess(String message1) {
                Log.w("Zipping","Success");
                RelativeLayout v = (RelativeLayout) mEssageBox.findViewById(rowid.intValue()); ;
                ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar); // this keeps returning null!
                ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview); // returns the view
            //  progressBar.setVisibility(View.GONE);
                Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(ZippedVideoPath, MediaStore.Images.Thumbnails.MINI_KIND);
                iv.setImageBitmap(bitTh);
                progressBar.setVisibility(View.GONE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ZippedVideoPath));
                        intent.setDataAndType(Uri.parse(ZippedVideoPath), "video/mp4");
                        startActivity(intent);

                    }
                });
                UploadVideo uv = new UploadVideo(v);
                uv.execute();
            }

Thank you!


来源: stackexchange

问:
Rendering in Layout and table like alignment without table tag using div only in MVC
_layout.cshtml

```<code><body>
    <div>
        <ul id="accordion" class="accordion">
            <li>
                <div class="link">Web Design</div>
                <ul class="submenu">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
            </li>
            <li>
                <div class="link">Coding</div>
                <ul class="submenu">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
            </li>
         </ul>
    </div>
</code>```

css file

```<code>.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing:border-box;
  position: absolute;
}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*Submenu*/

.submenu {
   padding:0px;
  display: none;
  font-size: 14px;
}

.submenu li { border-bottom: 1px solid #4b4a5e; }

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color:#c9c7d5;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}
</code>```

JS file

```<code>$(document).ready(function () {

    $(function () {
        var Accordion = function (el, multiple) {
            this.el = el || {};
            this.multiple = multiple || false;

            var links = this.el.find('.link');

            links.on('click', { el: this.el, multiple: this.multiple }, this.dropdown)
        }

        Accordion.prototype.dropdown = function (e) {
            var $el = e.data.el;
            $this = $(this),
            $next = $this.next();

            $next.slideToggle();
            $this.parent().toggleClass('open');

            if (!e.data.multiple) {
                $el.find('.submenu').not($next).slideUp().parent().removeClass('open');
            };
        }

        var accordion = new Accordion($('#accordion'), false);
    });
});
</code>```

The Objectives

1. the alignment is not coming correct  ,  currently its like ---  https://ibb.co/fiUOrF
            it should be like ---- https://ibb.co/e5hbBF --- cant use table tag -- divider(the line) between sidebar and the content is important - it should appear --- this is completed

2 . in the accordian menu - when a submenu is clicked it should stay  selected  , as you see its getting closed after the page loads

Please help me with detailed reply

cant use bootstrap - only css3, jquery and razor syntax

答:
In order to keep the selected accordion submenu open, you should set the 'multiple' option to true. Change the last line of your javascript to:

```<code>    var accordion = new Accordion($('#accordion'), true);
</code>```

Update:
If you want one of the submenu to be opened on page load, you should add display: block to the ul submenu tag you wanted to be open. For example:

Check the JSFiddle.

ContentLicense: CC BY-SA 3.0

Body:
_layout.cshtml

Web Design

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("About", "About", "Home")

@Html.ActionLink("Contact", "Contact", "Home")

Coding

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("About", "About", "Home")

@Html.ActionLink("Contact", "Contact", "Home")

css file

.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing:border-box;
  position: absolute;
}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*Submenu*/

.submenu {
   padding:0px;
  display: none;
  font-size: 14px;
}

.submenu li { border-bottom: 1px solid #4b4a5e; }

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color:#c9c7d5;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}

JS file

$(document).ready(function () {

    $(function () {
        var Accordion = function (el, multiple) {
            this.el = el || {};
            this.multiple = multiple || false;

            var links = this.el.find('.link');

            links.on('click', { el: this.el, multiple: this.multiple }, this.dropdown)
        }

        Accordion.prototype.dropdown = function (e) {
            var $el = e.data.el;
            $this = $(this),
            $next = $this.next();

            $next.slideToggle();
            $this.parent().toggleClass('open');

            if (!e.data.multiple) {
                $el.find('.submenu').not($next).slideUp().parent().removeClass('open');
            };
        }

        var accordion = new Accordion($('#accordion'), false);
    });
});

The Objectives

1. the alignment is not coming correct  ,  currently its like ---  https://ibb.co/fiUOrF
            it should be like ---- https://ibb.co/e5hbBF --- cant use table tag -- divider(the line) between sidebar and the content is important - it should appear --- this is completed

2 . in the accordian menu - when a submenu is clicked it should stay  selected  , as you see its getting closed after the page loads

Please help me with detailed reply

cant use bootstrap - only css3, jquery and razor syntax

Body:
In order to keep the selected accordion submenu open, you should set the 'multiple' option to true. Change the last line of your javascript to:

    var accordion = new Accordion($('#accordion'), true);

Update:
If you want one of the submenu to be opened on page load, you should add display: block to the ul submenu tag you wanted to be open. For example: <ul class="submenu" style="display: block;">

Check the JSFiddle.


问:
print multiple YAML lists in a dictionary
I am new to python programming. The input X.yaml file contains a list of list of dictionaries. I am trying to print the list and it's sub-list items.

Input:X.Yaml

```<code>    entities:
        - level: undefined
          name: a
          refs:
              - b
          reqs: []
        - level: undefined
          name: c
          refs:
              - b
          reqs: []
</code>```

Code:

```<code>data = yaml.load(yamlfile)
for entity in data["entities"]:
     #Needed help here.
</code>```

Desired output:

```<code>-name: a
 refs:
     - b
 reqs: []
-name: c
 refs:
    - b
 reqs: []
</code>```

答:
Use yaml.dump() with default_flow_style=False:

```<code>>>> print yaml.dump(data['entities'], default_flow_style=False)
- level: undefined
  name: a
  refs:
  - b
  reqs: []
- level: undefined
  name: c
  refs:
  - b
  reqs: []
</code>```

And if you don't want the 'level', then first remove that from the entities:

```<code>>>> new_entities = [{key: value for key, value in entity.items() if key != 'level'}
...                 for entity in data['entities']]
>>>
>>> print yaml.dump(new_entities, default_flow_style=False)
- name: a
  refs:
  - b
  reqs: []
- name: c
  refs:
  - b
  reqs: []

>>>
</code>```

Edit: If the list and dictionary comprehensions are confusing, this is the long (and lower performance) way to write it:

```<code>>>> new_entities = []
>>> for entity in data['entities']:
...     new_ent = {}
...     for key, value in entity.items():
...         if key != 'level':
...             new_ent[key] = value
...     new_entities.append(new_ent)
...
>>> # then dump `new_entities`
</code>```

Body:
I am new to python programming. The input X.yaml file contains a list of list of dictionaries. I am trying to print the list and it's sub-list items.

Input:X.Yaml

    entities:
        - level: undefined
          name: a
          refs:
              - b
          reqs: []
        - level: undefined
          name: c
          refs:
              - b
          reqs: []

Code:

data = yaml.load(yamlfile)
for entity in data["entities"]:
     #Needed help here.

Desired output:

-name: a
 refs:
     - b
 reqs: []
-name: c
 refs:
    - b
 reqs: []

Body:
Use yaml.dump() with default_flow_style=False:

>>> print yaml.dump(data['entities'], default_flow_style=False)
- level: undefined
  name: a
  refs:
  - b
  reqs: []
- level: undefined
  name: c
  refs:
  - b
  reqs: []

And if you don't want the 'level', then first remove that from the entities:

>>> new_entities = [{key: value for key, value in entity.items() if key != 'level'}
...                 for entity in data['entities']]
>>>
>>> print yaml.dump(new_entities, default_flow_style=False)
- name: a
  refs:
  - b
  reqs: []
- name: c
  refs:
  - b
  reqs: []

>>>

Edit: If the list and dictionary comprehensions are confusing, this is the long (and lower performance) way to write it:

>>> new_entities = []
>>> for entity in data['entities']:
...     new_ent = {}
...     for key, value in entity.items():
...         if key != 'level':
...             new_ent[key] = value
...     new_entities.append(new_ent)
...
>>> # then dump `new_entities`


问:
Passing data between child components
I am struggling for this to work. I need to access the selected value in the ChooseLangComponent from the FormComponent. Is there any direct way to do this or we have to pass it from the parent component (act like middle man)? I already tried with $emit on ChooseLangComponent and v-on:.. on FormComponent but didn't work.

ChooseLangComponent:

```<code><template lang="html">
    <div class="choose-lang">
        <select v-model="selected">
            <option v-for="lang in langs" v-bind:value="lang.value">{{lang.text}}</option>
        </select>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                selected: 'en',
                langs: [
                    { text: 'English', value: 'en' },
                    { text: 'German', value: 'ge' },
                ]
            }
        }
    }
</script>
</code>```

FormComponent:

```<code><template lang="html">
    <div class="form-name">
        <div class="inputs">
            <input type="text" v-model="nameText" v-on:keyup.enter="send_name">
        </div>
    </div>
</template>

export default {
    data() {
        return {
            nameText: '',
        }
    },
    methods: {
        send_name() {
              // I need the selected language here
        }
    }
}
</code>```

The parent component:

```<code><div id="app">
    <choose-lang></choose-lang>
    ...
    <form-comp></form-comp>
</div>

...
Vue.component('choose-lang', require('./components/ChooseLangComponent.vue'));
Vue.component('form-comp', require('./components/FormComponent.vue'));

const app = new Vue({
el: '#app',
data: {
    ...
});
</code>```

答:
Okay there are 2 easy ways and one more which involves the Vuex, if your app is large scale.

First way is creating the Event Bus - idea is emitting Events in one hub and then catching them where It's needed.

```<code>const Bus = new Vue({})

Vue.component('lang', {
       template: '#lang-tmp',
       data() {
            return {
                selected: 'en',
                langs: [
                    { text: 'English', value: 'en' },
                    { text: 'German', value: 'ge' },
                ]
            }
        },
        created() {
          this.changeLang()
        },
        methods: {
          changeLang() {
            Bus.$emit('langChanged', this.selected)
          }
        }
})

Vue.component('frm', {
  template: '#frm-tmp',
  data() {
    return {
      selectedItem: 'en'
    }
  },
  created() {
    Bus.$on('langChanged', (selected) => {
      this.selectedItem = selected
    })
  }
})

const app = new Vue({

  el: '#app'

})
</code>```

http://jsbin.com/siyipuboki/edit?html,js,output

Second way is creating sort of store - plain object that would hold the state of selected item

```<code>const store = {
  data: {
    selected: null
  }
}

Vue.component('lang', {
       template: '#lang-tmp',
       data() {
            return {
                selected: 'en',
                langs: [
                    { text: 'English', value: 'en' },
                    { text: 'German', value: 'ge' },
                ]
            }
        },
        created() {
          this.changeLang()
        },
        methods: {
          changeLang() {
            store.data.selected = this.selected
          }
        }
})

Vue.component('frm', {
  template: '#frm-tmp',
  data() {
    return {
      storeSelected: store.data
    }
  }
})

const app = new Vue({

  el: '#app'

})
</code>```

http://jsbin.com/qagahabile/edit?html,js,output

Also please check this VueJS access child component's data from parent

Title: Passing data between child components

Body:
I am struggling for this to work. I need to access the selected value in the ChooseLangComponent from the FormComponent. Is there any direct way to do this or we have to pass it from the parent component (act like middle man)? I already tried with $emit on ChooseLangComponent and v-on:.. on FormComponent but didn't work.

ChooseLangComponent:

<template lang="html">

        <select v-model="selected">
            <option v-for="lang in langs" v-bind:value="lang.value">{{lang.text}}</option>
        </select>

</template>

FormComponent:

<template lang="html">

            <input type="text" v-model="nameText" v-on:keyup.enter="send_name">

</template>

export default {
    data() {
        return {
            nameText: '',
        }
    },
    methods: {
        send_name() {
              // I need the selected language here
        }
    }
}

The parent component:

    <choose-lang></choose-lang>
    ...
    <form-comp></form-comp>

...
Vue.component('choose-lang', require('./components/ChooseLangComponent.vue'));
Vue.component('form-comp', require('./components/FormComponent.vue'));

const app = new Vue({
el: '#app',
data: {
    ...
});

Body:
Okay there are 2 easy ways and one more which involves the Vuex, if your app is large scale.

First way is creating the Event Bus - idea is emitting Events in one hub and then catching them where It's needed.

const Bus = new Vue({})

Vue.component('lang', {
       template: '#lang-tmp',
       data() {
            return {
                selected: 'en',
                langs: [
                    { text: 'English', value: 'en' },
                    { text: 'German', value: 'ge' },
                ]
            }
        },
        created() {
          this.changeLang()
        },
        methods: {
          changeLang() {
            Bus.$emit('langChanged', this.selected)
          }
        }
})

Vue.component('frm', {
  template: '#frm-tmp',
  data() {
    return {
      selectedItem: 'en'
    }
  },
  created() {
    Bus.$on('langChanged', (selected) => {
      this.selectedItem = selected
    })
  }
})

const app = new Vue({

  el: '#app'

})

http://jsbin.com/siyipuboki/edit?html,js,output

Second way is creating sort of store - plain object that would hold the state of selected item

const store = {
  data: {
    selected: null
  }
}

Vue.component('lang', {
       template: '#lang-tmp',
       data() {
            return {
                selected: 'en',
                langs: [
                    { text: 'English', value: 'en' },
                    { text: 'German', value: 'ge' },
                ]
            }
        },
        created() {
          this.changeLang()
        },
        methods: {
          changeLang() {
            store.data.selected = this.selected
          }
        }
})

Vue.component('frm', {
  template: '#frm-tmp',
  data() {
    return {
      storeSelected: store.data
    }
  }
})

const app = new Vue({

  el: '#app'

})

http://jsbin.com/qagahabile/edit?html,js,output

Also please check this VueJS access child component's data from parent


问:
Normal Priority Builds Will Not Build in TFS 2010
I have two build processes setup in TFS 2010. One build starts when any developer checks code into TFS. The second build runs every night at 12:30am. I can see the builds have a priority of Normal in the queue. However no queued build ever is run until I change the priority to high. They will sit in the queue forever until the priority is changed.

It appears there is a normal priority build in the queue that is stuck. However I cannot find it. I can select Any Build Definition, Any Status, and Any Build Controller and not see anything but these builds queued up. I can run them all and the next day I have queued builds again. I say this because I see the Build Service is configured for port 9192, which leads me to believe there is or was another Build Service on port 9191.

Any idea how to resolve this issue?

答:
I had a similar issue with builds not... building!  Had to restart the controller/build agent which seemed to fix it.

While you're in there, the Build Configuration checks the Event Log for errors, anything showing up?

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
C# MVC Handling nulls in ApplicationDbContext Constructor parameters
I have been using Session Value in the ApplicationDbContext Constructor. But in my big application somewhere i have used Threading which runs in background. And when that Threading method hits the ApplicationDbContext Constructor it doesn't get the Session Value as request is already completed. I get null reference exception, so the Application crashes.

Following is ApplicationDbContext Constructor Code :-

```<code>public ApplicationDbContext(string schemaname, string connString = "")
            : base(connString)
        {
            SchemaName = schemaname;
            ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
        }

        public ApplicationDbContext(string schemaname)
            : this(schemaname, System.Web.HttpContext.Current.Session["ConnStringName"].ToString())
        {
        }
</code>```

How to handle null sessions in the above constructor?

答:
That is a poor abstraction, do not put anything related to the http context in the constructor of the DbContext especially the HttpContext.Current if you are using mvc/web api.

What you should be doing is using an IoC (DI) framework like AutoFac. Create an execution context type (with matching interface) that has the HttpContextBase injected into the constructor and then extract the connection string you want to use from the Session. Register your DbContext type to have your Execution type injected into its constructor and initialize the connection string from it. That will give you nice SoC (seperation of concerns), code is no longer dependent on the executing thread context, and allow for easier unit testing.

There are many tutorials out there on how to setup IoC with MVC and many IoC frameworks to choose from.

Body:
I have been using Session Value in the ApplicationDbContext Constructor. But in my big application somewhere i have used Threading which runs in background. And when that Threading method hits the ApplicationDbContext Constructor it doesn't get the Session Value as request is already completed. I get null reference exception, so the Application crashes.

Following is ApplicationDbContext Constructor Code :-

public ApplicationDbContext(string schemaname, string connString = "")
            : base(connString)
        {
            SchemaName = schemaname;
            ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
        }

        public ApplicationDbContext(string schemaname)
            : this(schemaname, System.Web.HttpContext.Current.Session["ConnStringName"].ToString())
        {
        }

How to handle null sessions in the above constructor?


问:
React Native ListView onEndReached doesn't called
I want to implement infinite scroll so I do this in my ListView tag

```<code>renderRow(data){
    return (
        <CardSection>
            <Text>
                {data.id}
            </Text>
        </CardSection>
    );
}

<ListView
    dataSource={this.dataSource}
    renderRow={this.renderRow}
    onEndReached = {this.loadMoreNews.bind(this)}
    pageSize = {5}
/>
</code>```

I get 5 data every fetch action that I call in loadMoreNews() and componentWillMount. Because the first 5 data doesn't fill the entire screen I expected that onEndReached to be called automatically since it already in the end of the ListView, but it doesn't.

I tried to style the Text tag in renderRow into this

```<code>renderRow(data){
    return (
        <CardSection>
            <Text style={{height:100}}>
                {data.id}
            </Text>
        </CardSection>
    );
}
</code>```

and it works as i want. I'm afraid that my renderRow won't fill the entire screen if my aplication is running in the wide screen device.

Is it the behavior of ListView or I missed something? What is the solution? I don't really want to force my component to be very big so it always fill the entire screen.

答:
onEndReached?: function

Called when all rows have been rendered and the list has been scrolled
  to within onEndReachedThreshold of the bottom. The native scroll event
  is provided.

It won't be automatically called unless user swipes the listview (wide screen scenario).

You may set a threshold to trigger onEndReached without reaching the bottom end of the screen.

onEndReachedThreshold: number

Threshold in pixels (virtual, not physical) for calling onEndReached.

Alternatively, you can manually call loadMoreNews() when your screen isn't fully covered by rows. To do so, just measure the height of the CardSection component, and divide Dimensions.get('window').height to that, which gives you number CardSection components that can fit into the current screen.

If your rows don't have a fixed height that you can know, you may use onLayout function.

Body:
I want to implement infinite scroll so I do this in my ListView tag

renderRow(data){
    return (
        <CardSection>
            <Text>
                {data.id}
            </Text>
        </CardSection>
    );
}

<ListView
    dataSource={this.dataSource}
    renderRow={this.renderRow}
    onEndReached = {this.loadMoreNews.bind(this)}
    pageSize = {5}
/>

I get 5 data every fetch action that I call in loadMoreNews() and componentWillMount. Because the first 5 data doesn't fill the entire screen I expected that onEndReached to be called automatically since it already in the end of the ListView, but it doesn't.

I tried to style the Text tag in renderRow into this

renderRow(data){
    return (
        <CardSection>
            <Text style={{height:100}}>
                {data.id}
            </Text>
        </CardSection>
    );
}

and it works as i want. I'm afraid that my renderRow won't fill the entire screen if my aplication is running in the wide screen device.

Is it the behavior of ListView or I missed something? What is the solution? I don't really want to force my component to be very big so it always fill the entire screen.


问:
is doing (ptr && *ptr) good way to check whether any value assigned to the ptr? mine just keep crashing
Im not really sure that use of ptr&&(*ptr)

At first, I was not sure about is this for checking NULL ptr or existence of assigned value.

But now after running the code below I found that in both way it just doesnt work: runtime error occurred!

Can somebody explain what nasty thing inside is happening?

GCC 5.3.0

```<code>#include <stdio.h>
int main(void){
    int* ptr=NULL;
//    ptr=NULL;
    int res = (ptr && *ptr);

//assigning NULL to *ptr or ptr address results in runtime error. What's happening?
//compiled with gcc.exe (GCC) 5.3.0 on windows

    printf("address: %d \n val: %d \n",ptr,*ptr);
    printf("isNullptr? ptr&& *ptr %d",res);
    return;
}
</code>```

答:
Doing

```<code>int * ptr = NULL

...

  printf("address: %d \n val: %d \n",ptr,*ptr);
</code>```

results in:

First ptr is initialised using the null-pointer constant. For this the C standard guarantees that ptr is not pointing to any valid object. (*1)

C11 Standard (draft) 6.3.2.3/3:

If a null pointer constant is converted to a
  pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

Then in the second statement with doing *ptr gets dereferenced, that is it is tried to access what it's pointing to, which is nothing valid (see 1. above), resulting in Undefined Behaviour, from then on anything can happen, including a crash of the program.

C11 Standard (draft) 6.5.3.2/4:

If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

Body:
Im not really sure that use of ptr&&(*ptr)

At first, I was not sure about is this for checking NULL ptr or existence of assigned value.

But now after running the code below I found that in both way it just doesnt work: runtime error occurred!

Can somebody explain what nasty thing inside is happening?

GCC 5.3.0

#include <stdio.h>
int main(void){
    int* ptr=NULL;
//    ptr=NULL;
    int res = (ptr && *ptr);

//assigning NULL to *ptr or ptr address results in runtime error. What's happening?
//compiled with gcc.exe (GCC) 5.3.0 on windows

    printf("address: %d \n val: %d \n",ptr,*ptr);
    printf("isNullptr? ptr&& *ptr %d",res);
    return;
}

Body:
Doing

int * ptr = NULL

...

  printf("address: %d \n val: %d \n",ptr,*ptr);

results in:

First ptr is initialised using the null-pointer constant. For this the C standard guarantees that ptr is not pointing to any valid object. (*1)

C11 Standard (draft) 6.3.2.3/3:

If a null pointer constant is converted to a
  pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

Then in the second statement with doing *ptr gets dereferenced, that is it is tried to access what it's pointing to, which is nothing valid (see 1. above), resulting in Undefined Behaviour, from then on anything can happen, including a crash of the program.

C11 Standard (draft) 6.5.3.2/4:

If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.


问:
Reliabily unload dll in java
I am trying to unload a dll in java. I have read this and this but it seems that you can not guarantee that the dll will actually be unloaded at a certain time. This is because System.gc() simply "asks kindly" for the garbage collector to run.

So here is a break down of the situation. I have a dll that provides some functionality via JNI. Lets call this dll MainDll. MainDll is loaded from a call to System.load("MainDll"). I need to be able to unload and load this dll on the fly.

Is it possible to create another dll that's sole purpose is to load and unload MainDll. Lets call this dll LoaderDll. I could then simple call System.load("LoaderDll") and have some native functions to load and unload MainDll. The reason for doing this, is I have access to functions on the native system that can load and unload the dll on the fly. The tricky part with this is, will I have still be able to access the native functions I have written in MainDll if it loaded from inside LoaderDll.

Sorry if this is a confusing question. It seems its a little difficult to explain.

Thanks

答:
Add a level of indirection.

Make your native methods call forwarding routines in LoaderDLL.  The forwarding routines can use C facilities to forward the calls to code in mainDLL.

Title: Reliabily unload dll in java


问:
Is there a way in haskell to compactly and efficiently compare by multiple parameters and in different orders
Suppose we have a list of tuples and we need to find maximum on some criterion. The criterion is the following - most important is the first element of the tuple (more is better) less important is second element (less is better).

I know two ways of expressing this in Haskell.

First one is to create a function that would make all the comparisons and return (EQ, LT, GT)

```<code>compareSol (s1, w1) (s2, w2) = if weightComp == EQ then sizeComp else weightComp where
    weightComp = compare w1 w2
    sizeComp = compare (Map.foldl' (+) 0  s2) (Map.foldl' (+) 0  s1)
</code>```

The second one is to use comparing from Data.Ord and give it a function that would return a score \ (x, y) -> (x, 1 / y) Which is I think more declarative, but would require more computations (1 / y)

Is there a way of expressing this in both declarative and efficient way, like is sql?

答:
You can use comparing and Down from Data.Ord with <> from Data.Monoid:

```<code>compareSol = comparing snd <> comparing (Down . sum . fst)
</code>```

In this case you can also use the simpler flip instead of Down:

```<code>compareSol = comparing snd <> flip (comparing (sum . fst))
</code>```

This is a combination of a few features.

Data.Ord.comparing compares two values based on a function of those values—comparing f is equivalent to compare `on` f using Data.Function.on.

```<code>comparing :: Ord a => (b -> a) -> b -> b -> Ordering
</code>```

The Monoid instance for Ordering gives you lexicographical ordering.

```<code>LT <> x = LT
GT <> x = GT
EQ <> x = x
</code>```

The Monoid instance for functions lets you compose comparison functions of type a -> Ordering, or in this case a -> a -> Ordering.

```<code>instance Monoid b => Monoid (a -> b)
-- instance Monoid c => Monoid (a -> b -> c)
-- instance Monoid Ordering
-- instance Monoid (a -> b -> Ordering)
-- instance Monoid (a -> a -> Ordering)  given  a ~ b
</code>```

And finally, the Down newtype inverts the ordering of the type it wraps, giving you reversed comparison for free:

```<code>     0 <       1  ==  True
Down 0 <  Down 1  ==  False
     0 >       1  ==  False
Down 0 >  Down 1  ==  True
</code>```

Body:
Suppose we have a list of tuples and we need to find maximum on some criterion. The criterion is the following - most important is the first element of the tuple (more is better) less important is second element (less is better).

I know two ways of expressing this in Haskell.

First one is to create a function that would make all the comparisons and return (EQ, LT, GT)

compareSol (s1, w1) (s2, w2) = if weightComp == EQ then sizeComp else weightComp where
    weightComp = compare w1 w2
    sizeComp = compare (Map.foldl' (+) 0  s2) (Map.foldl' (+) 0  s1)

The second one is to use comparing from Data.Ord and give it a function that would return a score \ (x, y) -> (x, 1 / y) Which is I think more declarative, but would require more computations (1 / y)

Is there a way of expressing this in both declarative and efficient way, like is sql?

Body:
You can use comparing and Down from Data.Ord with <> from Data.Monoid:

compareSol = comparing snd <> comparing (Down . sum . fst)

In this case you can also use the simpler flip instead of Down:

compareSol = comparing snd <> flip (comparing (sum . fst))

This is a combination of a few features.

Data.Ord.comparing compares two values based on a function of those values—comparing f is equivalent to compare `on` f using Data.Function.on.

comparing :: Ord a => (b -> a) -> b -> b -> Ordering

The Monoid instance for Ordering gives you lexicographical ordering.

LT <> x = LT
GT <> x = GT
EQ <> x = x

The Monoid instance for functions lets you compose comparison functions of type a -> Ordering, or in this case a -> a -> Ordering.

instance Monoid b => Monoid (a -> b)
-- instance Monoid c => Monoid (a -> b -> c)
-- instance Monoid Ordering
-- instance Monoid (a -> b -> Ordering)
-- instance Monoid (a -> a -> Ordering)  given  a ~ b

And finally, the Down newtype inverts the ordering of the type it wraps, giving you reversed comparison for free:

     0 <       1  ==  True
Down 0 <  Down 1  ==  False
     0 >       1  ==  False
Down 0 >  Down 1  ==  True


问:
Python a, b = b, a +b
This is my first question and I started to learn Python.
Is there a difference between:

```<code>a, b = b, a + b
</code>```

and

```<code>a = b
b = a + b
</code>```

When you write it in below example it shows different results.

```<code>def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a + b
    print()
fib(1000)
</code>```

and

```<code>def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a = b
        b = a + b
    print()
fib(1000)
</code>```

答: a, b = b, a + b is similar to a, b = 0, 1 assigning values to both variables a, b at same time. First assign a = b and then b = a + b.

Title: Python a, b = b, a +b

Body:
This is my first question and I started to learn Python.
Is there a difference between:

a, b = b, a + b

and

a = b
b = a + b

When you write it in below example it shows different results.

def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a + b
    print()
fib(1000)

and

def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a = b
        b = a + b
    print()
fib(1000)


问:
change photos in cardboard VR-360 SDK
I am a beginner android programmer and developing a VR app by cardboard SDK and have used a switch-case and button for switch between photos but I know some apps use a central point and "focus on an icon" method to change view of a 360 photo to another photo. for example by 3second looking to that icon call an event to do a function.enter image description here

```<code>public void onClick(View v) {

    if (v.getId()==R.id.button1) {
        i = i + 1;
        switch (i) {
            case 2:
                panoImageName = "p1.jpg";
                loadPanoImage();
                mediaPlayer.start();
                panoWidgetView.addFocusables(Imgs[0],1,2);
                break;
            case 3:
               onPause();
                panoImageName = "logo.jpg";
                //loadPanoImage();
               // onResume();
                break;
            case 4:
                panoImageName = "p2.jpg";
                loadPanoImage();
                break;
            case 5:
                panoImageName = "logo.jpg";
                loadPanoImage();
                break;
             }
    }
}
</code>```

do you have any idea for it?

Sample image of a VR app screen:

答:
I'm new to Unity and working to create a VR photo viewer with UI buttons to change the photo. I am able to complete it through multiple resources as described here:

I downloaded a unity project from the dropbox link given in this youtube video: https://www.youtube.com/watch?v=hYXj77CSDks&t=65s

The above project can change the photos but by clicking the buttons.

To control the next and previous buttons with focus (Gaze) I followed this post:how to add gaze input timer to trigger an action after gazing for 3secs?

This worked for me so far.

Title: change photos in cardboard VR-360 SDK

Body:
I am a beginner android programmer and developing a VR app by cardboard SDK and have used a switch-case and button for switch between photos but I know some apps use a central point and "focus on an icon" method to change view of a 360 photo to another photo. for example by 3second looking to that icon call an event to do a function.enter image description here

public void onClick(View v) {

    if (v.getId()==R.id.button1) {
        i = i + 1;
        switch (i) {
            case 2:
                panoImageName = "p1.jpg";
                loadPanoImage();
                mediaPlayer.start();
                panoWidgetView.addFocusables(Imgs[0],1,2);
                break;
            case 3:
               onPause();
                panoImageName = "logo.jpg";
                //loadPanoImage();
               // onResume();
                break;
            case 4:
                panoImageName = "p2.jpg";
                loadPanoImage();
                break;
            case 5:
                panoImageName = "logo.jpg";
                loadPanoImage();
                break;
             }
    }
}

do you have any idea for it?

Sample image of a VR app screen:


问:
Pass dynamic number to loader
I have a simple question. How to pass dynamic number to loader manager? Thanks!</p>

```<code>var manager = new THREE.LoadingManager();
var loader = new THREE.TextureLoader();

for(var i=0; i<3; i++){
    loader.load(url[i], function ( texture ) {
        console.log(i)
        textures[i] = texture;
    });
}

// console.log(i)  ->  3, 3, 3
// i need          ->  0, 1, 2
</code>```

答:
If using ecmascript 2015 is an option, just ùse the keyword let instead of var in the for loop:

```<code>for(let i=0; i<3; i++){
    ...
}
</code>```

This will allow the variable i to be block scoped instead of function scoped.

Explanation to ths behaviour can be found in this answer

Title: Pass dynamic number to loader

Body:
I have a simple question. How to pass dynamic number to loader manager? Thanks!

var manager = new THREE.LoadingManager();
var loader = new THREE.TextureLoader();

for(var i=0; i<3; i++){
    loader.load(url[i], function ( texture ) {
        console.log(i)
        textures[i] = texture;
    });
}

// console.log(i)  ->  3, 3, 3
// i need          ->  0, 1, 2

Body:
If using ecmascript 2015 is an option, just ùse the keyword let instead of var in the for loop:

for(let i=0; i<3; i++){
    ...
}

This will allow the variable i to be block scoped instead of function scoped.

Explanation to ths behaviour can be found in this answer


问:
Asking multiple permissions one at a time
The code just shows dialog box for the first permission and not for the other two permissions.How can I handle multiple requests in a much easier way other than this , in which the app prompts for each permission one at a time .

The code for requesting permission is as follows :

```<code>package com.example.hp.requesting_permissions;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        if (ContextCompat.checkSelfPermission(MainActivity.this,   Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)     {
             if  (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,  Manifest.permission.ACCESS_FINE_LOCATION)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                 ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
             }

         } else {
             Toast.makeText(MainActivity.this, "Denied",   Toast.LENGTH_SHORT).show();
         }

         if (ContextCompat.checkSelfPermission(MainActivity.this,   Manifest.permission.ACCESS_COARSE_LOCATION) !=   PackageManager.PERMISSION_GRANTED) {
            if   (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,   Manifest.permission.ACCESS_COARSE_LOCATION)) {
                ActivityCompat.requestPermissions(MainActivity.this, new   String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            Toast.makeText(MainActivity.this, "denied",   Toast.LENGTH_SHORT).show();
        }

        if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            if   (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,      Manifest.permission.INTERNET)) {
                ActivityCompat.requestPermissions(MainActivity.this, new     String[]{Manifest.permission.INTERNET}, 3);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new     String[]{Manifest.permission.INTERNET}, 3);
            }
        } else {
            Toast.makeText(MainActivity.this, "denied",  Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]     permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)     {
                        Toast.makeText(MainActivity.this, "Granted", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Denied",     Toast.LENGTH_SHORT).show();
                    }

                }
            }
            break;
            case 2: {
                 if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,      Manifest.permission.ACCESS_COARSE_LOCATION) ==      PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MainActivity.this, "Granted",     Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Granted",      Toast.LENGTH_SHORT).show();
                    }
                }
            }
             break;
            case 3: {
                if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MainActivity.this, "Granted",     Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Denied",     Toast.LENGTH_SHORT).show();
                    }
                }
            }
            break;
        }
    }
}
</code>```

答:
Like this</p>

```<code> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(SelectUserActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.CALL_PHONE,
                            Manifest.permission.CAMERA,
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.READ_CONTACTS,
                            Manifest.permission.READ_SMS
                    },
                    10);
            return;
        }
    }
</code>```

Body:
The code just shows dialog box for the first permission and not for the other two permissions.How can I handle multiple requests in a much easier way other than this , in which the app prompts for each permission one at a time .

The code for requesting permission is as follows :

package com.example.hp.requesting_permissions;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        if (ContextCompat.checkSelfPermission(MainActivity.this,   Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)     {
             if  (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,  Manifest.permission.ACCESS_FINE_LOCATION)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                 ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
             }

         } else {
             Toast.makeText(MainActivity.this, "Denied",   Toast.LENGTH_SHORT).show();
         }

         if (ContextCompat.checkSelfPermission(MainActivity.this,   Manifest.permission.ACCESS_COARSE_LOCATION) !=   PackageManager.PERMISSION_GRANTED) {
            if   (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,   Manifest.permission.ACCESS_COARSE_LOCATION)) {
                ActivityCompat.requestPermissions(MainActivity.this, new   String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            Toast.makeText(MainActivity.this, "denied",   Toast.LENGTH_SHORT).show();
        }

        if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            if   (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,      Manifest.permission.INTERNET)) {
                ActivityCompat.requestPermissions(MainActivity.this, new     String[]{Manifest.permission.INTERNET}, 3);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new     String[]{Manifest.permission.INTERNET}, 3);
            }
        } else {
            Toast.makeText(MainActivity.this, "denied",  Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]     permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)     {
                        Toast.makeText(MainActivity.this, "Granted", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Denied",     Toast.LENGTH_SHORT).show();
                    }

                }
            }
            break;
            case 2: {
                 if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,      Manifest.permission.ACCESS_COARSE_LOCATION) ==      PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MainActivity.this, "Granted",     Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Granted",      Toast.LENGTH_SHORT).show();
                    }
                }
            }
             break;
            case 3: {
                if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MainActivity.this, "Granted",     Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Denied",     Toast.LENGTH_SHORT).show();
                    }
                }
            }
            break;
        }
    }
}

Body:
Like this

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(SelectUserActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.CALL_PHONE,
                            Manifest.permission.CAMERA,
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.READ_CONTACTS,
                            Manifest.permission.READ_SMS
                    },
                    10);
            return;
        }
    }


问:
How to export every table to csv in a kdb+ database?
Assume my kdb+ database has a few tables. How can I export all tables to csv files where the name of each csv is same as the table name? </p>

答:
There may be a number of ways to approach this, one solution could be:

```<code> q)t1:([]a:1 2 3;b:1 2 3)
 q)t2:([]a:1 2 3;b:1 2 3;c:1 2 3)
 q){save `$(string x),".csv"} each tables[]
   `:t1.csv`:t2.csv
</code>```

ref: http://code.kx.com/q/ref/filewords/#save

If you wish to specify the directory of the file being saved down then you could enhance the function like so:

```<code>q){[dir;tSym] save ` sv dir,(`$ raze string tSym,`.csv)}[`:C:/Users/dhughes1/Documents;] each tables[]
  `:C:/Users/dhughes1/Documents/t1.csv`:C:/Users/dhughes1/Documents/t2.csv
</code>```

Body:
There may be a number of ways to approach this, one solution could be:

 q)t1:([]a:1 2 3;b:1 2 3)
 q)t2:([]a:1 2 3;b:1 2 3;c:1 2 3)
 q){save `$(string x),".csv"} each tables[]
   `:t1.csv`:t2.csv

ref: http://code.kx.com/q/ref/filewords/#save

If you wish to specify the directory of the file being saved down then you could enhance the function like so:

q){[dir;tSym] save ` sv dir,(`$ raze string tSym,`.csv)}[`:C:/Users/dhughes1/Documents;] each tables[]
  `:C:/Users/dhughes1/Documents/t1.csv`:C:/Users/dhughes1/Documents/t2.csv


问:
Swift collectionViewCells are not showing
I have got this Swift code
`

```<code>let cellId="cellId"

class FeedController: UICollectionViewController{
override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Centill"

    collectionView?.reloadData()
    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
    collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath);
    cell.backgroundColor = .yellow
    return cell
}

}

class FeedCell: UICollectionViewCell {

override init(frame: CGRect){
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
func setupViews(){
    backgroundColor = .yellow
}
}
</code>```

`
But unfortunately my cells are not showing.It only shows navigation bar and background color.what may be the problem with my code?

答:
Try This code:</p>

```<code>    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
    layout.itemSize = CGSize(width: 60, height: 60)

    let myCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    myCollectionView.dataSource = self
    myCollectionView.delegate = self
    myCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
    myCollectionView.backgroundColor = UIColor.whiteColor()
    self.view.addSubview(myCollectionView)
</code>```

Body:
I have got this Swift code
`

let cellId="cellId"

class FeedController: UICollectionViewController{
override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Centill"

    collectionView?.reloadData()
    collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
    collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath);
    cell.backgroundColor = .yellow
    return cell
}

}

class FeedCell: UICollectionViewCell {

override init(frame: CGRect){
    super.init(frame: frame)

    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
func setupViews(){
    backgroundColor = .yellow
}
}

`
But unfortunately my cells are not showing.It only shows navigation bar and background color.what may be the problem with my code?

Body:
Try This code:

    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
    layout.itemSize = CGSize(width: 60, height: 60)

    let myCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    myCollectionView.dataSource = self
    myCollectionView.delegate = self
    myCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
    myCollectionView.backgroundColor = UIColor.whiteColor()
    self.view.addSubview(myCollectionView)


问:
ChildNode of custom type is returning Nil on Swift Playground
I have a class with name (Player.swift). then in my (Scene.swift) class, I declared my object like this.

```<code>var player: Player?
</code>```

then in my initializeGame function, I am doing like this

```<code>private func initializeGame() {

    player = childNode(withName: "Player") as? Player!;
    //print NIL
    print(player?.name);
    // initializePlayer()is declared in Player.swift
    player?.initializePlayer();
    print(player?.name);
    //Print NIL
    scoreLabel = childNode(withName: "ScoreLabel") as? SKLabelNode!;
    scoreLabel?.text = "0";
}
</code>```

I made my ios project in Xcode,  and its working fine,  then i create a Playground project and import all the xcode files in this project, My playground is running properly except the player is not functioning properly. The problem is in associating the Player Node with custom class in .sks file. The name of my Xcode project is "Game play" so  I  write Game Play in module  and Player in custom class, and using that same sks file in Playground causing problem, the name of my playground project is  "MyPlayground", so the module name should be same as project name, so i edit the module field to Myplayground, still not working. So guide me how to change that properly.

答:
The method childNode(withName:) returns an existing child node that has been added to the node hierarchy. If no node is found with that name, then it returns nil.

Do you have code that adds a node with the name "Player"? Is it a node of type Player? Is it being called?

Body:
I have a class with name (Player.swift). then in my (Scene.swift) class, I declared my object like this.

var player: Player?

then in my initializeGame function, I am doing like this

private func initializeGame() {

    player = childNode(withName: "Player") as? Player!;
    //print NIL
    print(player?.name);
    // initializePlayer()is declared in Player.swift
    player?.initializePlayer();
    print(player?.name);
    //Print NIL
    scoreLabel = childNode(withName: "ScoreLabel") as? SKLabelNode!;
    scoreLabel?.text = "0";
}

I made my ios project in Xcode,  and its working fine,  then i create a Playground project and import all the xcode files in this project, My playground is running properly except the player is not functioning properly. The problem is in associating the Player Node with custom class in .sks file. The name of my Xcode project is "Game play" so  I  write Game Play in module  and Player in custom class, and using that same sks file in Playground causing problem, the name of my playground project is  "MyPlayground", so the module name should be same as project name, so i edit the module field to Myplayground, still not working. So guide me how to change that properly.


问:
NSMetaDataQuery does not complete
I’m trying to explore the files available to my app in iCloud using NSMetaDataQuery.  I’m able to start the query, but it never finishes.  Here’s my code.

```<code>func report1() {
    let filemgr = FileManager.default
    let url = filemgr.url(forUbiquityContainerIdentifier: nil)
    guard url != nil else {
        print("url is nil")
        return
    }
    let metaDataQuery = NSMetadataQuery()
    metaDataQuery.predicate =
        NSPredicate(format: "%K like '*'", NSMetadataItemFSNameKey)
    metaDataQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(didFinish),
                                           name: NSNotification.Name.NSMetadataQueryDidFinishGathering,
                                           object: nil)
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(didStart),
                                           name: NSNotification.Name.NSMetadataQueryDidStartGathering,
                                           object: nil)
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(didUpdate),
                                           name: NSNotification.Name.NSMetadataQueryDidUpdate,
                                           object: nil)
    let result = metaDataQuery.start()
    print("metaDataQuery.start() returned \(result)")
}

@objc func didStart(notification: NSNotification) {
    let query: NSMetadataQuery = notification.object as! NSMetadataQuery
    print("didStart found \(query.results.count) items")
}

@objc func didFinish(notification: NSNotification) {
    print("didFinish")
}

@objc func didUpdate(notification: NSNotification) {
    print("didUpdate")
}
</code>```

This prints the following:

```<code>didStart found 0 items
metaDataQuery.start() returned true
</code>```

didStart is getting called, but didFinish and didUpdate are never called.  I get the same results if I substitute == or ==[cd] for like in the predicate.  Changing NSMetadataQueryUbiquitousDocumentsScope to NSMetadataQueryUbiquitousDataScope has no effect. What am I missing?

The same issue seems to have been posed several times on this forum, but I'm not finding any satisfactory answers.

答:
Change </p>

```<code>    NSPredicate(format: "%K like '*'", NSMetadataItemFSNameKey)
</code>```

<p>to </p>

```<code>    NSPredicate(format: "%K like '*.*'", NSMetadataItemFSNameKey)
</code>```

Title: NSMetaDataQuery does not complete

Body:
I’m trying to explore the files available to my app in iCloud using NSMetaDataQuery.  I’m able to start the query, but it never finishes.  Here’s my code.

func report1() {
    let filemgr = FileManager.default
    let url = filemgr.url(forUbiquityContainerIdentifier: nil)
    guard url != nil else {
        print("url is nil")
        return
    }
    let metaDataQuery = NSMetadataQuery()
    metaDataQuery.predicate =
        NSPredicate(format: "%K like '*'", NSMetadataItemFSNameKey)
    metaDataQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(didFinish),
                                           name: NSNotification.Name.NSMetadataQueryDidFinishGathering,
                                           object: nil)
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(didStart),
                                           name: NSNotification.Name.NSMetadataQueryDidStartGathering,
                                           object: nil)
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(didUpdate),
                                           name: NSNotification.Name.NSMetadataQueryDidUpdate,
                                           object: nil)
    let result = metaDataQuery.start()
    print("metaDataQuery.start() returned \(result)")
}

@objc func didStart(notification: NSNotification) {
    let query: NSMetadataQuery = notification.object as! NSMetadataQuery
    print("didStart found \(query.results.count) items")
}

@objc func didFinish(notification: NSNotification) {
    print("didFinish")
}

@objc func didUpdate(notification: NSNotification) {
    print("didUpdate")
}

This prints the following:

didStart found 0 items
metaDataQuery.start() returned true

didStart is getting called, but didFinish and didUpdate are never called.  I get the same results if I substitute == or ==[cd] for like in the predicate.  Changing NSMetadataQueryUbiquitousDocumentsScope to NSMetadataQueryUbiquitousDataScope has no effect. What am I missing?

The same issue seems to have been posed several times on this forum, but I'm not finding any satisfactory answers.

Body:
Change

    NSPredicate(format: "%K like '*'", NSMetadataItemFSNameKey)

to

    NSPredicate(format: "%K like '*.*'", NSMetadataItemFSNameKey)


答:
Create a wrapper DLL that does the loading/unloading.  Also have wrapper methods in the DLL that turn around and delegate the calls to the loaded MainDll DLL.  This way your Java JNI code only knows about a single DLL.  It can still request the unload [LoaderDll::unload()] which internally unloads the MainDll.

This should work as long as the methods/functions in LoaderDll can trigger a load of MainDll when they are called when MainDll is not currently loaded, assuming that is the desired behavior instead of throwing an exception/error.

One issue with this would be that LoaderDll would always be loaded.

Title: Reliabily unload dll in java

Body:
I am trying to unload a dll in java. I have read this and this but it seems that you can not guarantee that the dll will actually be unloaded at a certain time. This is because System.gc() simply "asks kindly" for the garbage collector to run.

So here is a break down of the situation. I have a dll that provides some functionality via JNI. Lets call this dll MainDll. MainDll is loaded from a call to System.load("MainDll"). I need to be able to unload and load this dll on the fly.

Is it possible to create another dll that's sole purpose is to load and unload MainDll. Lets call this dll LoaderDll. I could then simple call System.load("LoaderDll") and have some native functions to load and unload MainDll. The reason for doing this, is I have access to functions on the native system that can load and unload the dll on the fly. The tricky part with this is, will I have still be able to access the native functions I have written in MainDll if it loaded from inside LoaderDll.

Sorry if this is a confusing question. It seems its a little difficult to explain.

Thanks