问:
Recyclerview lag on scroll due to Admob ads
I want to load ads in RecyclerView ads are loaded successfully but it is casuing so much lag while scrolling

Following is code I have written in OnBindViewHolder method of Adapter

How to fix this lag?

```<code>((DealHolder) holder).adcardView.post(new Runnable() {
                @Override
                public void run() {
                    final NativeExpressAdView adView = new NativeExpressAdView(((DealHolder) holder).itemView.getContext());
                    final int adWidth = ((DealHolder) holder).adcardView.getWidth() - ((DealHolder) holder).adcardView.getPaddingLeft()
                            - ((DealHolder) holder).adcardView.getPaddingRight();
                    final int adHeight = ((DealHolder) holder).adcardView.getHeight() - ((DealHolder) holder).adcardView.getPaddingBottom()
                            - ((DealHolder) holder).adcardView.getPaddingTop();
                    final float scale = ((DealHolder) holder).adcardView.getResources().getDisplayMetrics().density;
                    AdSize adSize = new AdSize((int) (adWidth / scale), (int) (adHeight / scale));
                    adView.setAdSize(adSize);
                    adView.setAdUnitId(((DealHolder) holder).adcardView.getContext().getString(R.string.test_adunit_id));
                    AdRequest request = new AdRequest.Builder().addTestDevice("jjhjhbjhjhjhjhjhjhjh").build();
                    adView.loadAd(request);
                    adView.setAdListener(new AdListener() {
                        @Override
                        public void onAdLoaded() {
                            super.onAdLoaded();
                        }

                        @Override
                        public void onAdFailedToLoad(int i) {
                            super.onAdFailedToLoad(i);
                        }
                    });
                    ((DealHolder) holder).adcardView.removeAllViews();
                    ((DealHolder) holder).adcardView.addView(adView);
                }
            });
</code>```

答:
Improvements :

Do not try to load your Adview when the user is trying to scroll. To do that make your adapter recylerView scroll aware and then check whether the
scroll_state==RecylerView.Scroll_IDLE, then only load your AdView.

If all your adViews have same width and height do not calculate it every time user scrolls, cache it in a variable.

Instead of dynamically adding and removing your NativeExpressAdView, use a XML version for it in your item_view. You can hide and show based on conditions. Set all the possible required attributes in XML view.

Body:
I want to load ads in RecyclerView ads are loaded successfully but it is casuing so much lag while scrolling

Following is code I have written in OnBindViewHolder method of Adapter

How to fix this lag?

((DealHolder) holder).adcardView.post(new Runnable() {
                @Override
                public void run() {
                    final NativeExpressAdView adView = new NativeExpressAdView(((DealHolder) holder).itemView.getContext());
                    final int adWidth = ((DealHolder) holder).adcardView.getWidth() - ((DealHolder) holder).adcardView.getPaddingLeft()
                            - ((DealHolder) holder).adcardView.getPaddingRight();
                    final int adHeight = ((DealHolder) holder).adcardView.getHeight() - ((DealHolder) holder).adcardView.getPaddingBottom()
                            - ((DealHolder) holder).adcardView.getPaddingTop();
                    final float scale = ((DealHolder) holder).adcardView.getResources().getDisplayMetrics().density;
                    AdSize adSize = new AdSize((int) (adWidth / scale), (int) (adHeight / scale));
                    adView.setAdSize(adSize);
                    adView.setAdUnitId(((DealHolder) holder).adcardView.getContext().getString(R.string.test_adunit_id));
                    AdRequest request = new AdRequest.Builder().addTestDevice("jjhjhbjhjhjhjhjhjhjh").build();
                    adView.loadAd(request);
                    adView.setAdListener(new AdListener() {
                        @Override
                        public void onAdLoaded() {
                            super.onAdLoaded();
                        }

                        @Override
                        public void onAdFailedToLoad(int i) {
                            super.onAdFailedToLoad(i);
                        }
                    });
                    ((DealHolder) holder).adcardView.removeAllViews();
                    ((DealHolder) holder).adcardView.addView(adView);
                }
            });


来源: stackexchange

问:
Setting the parameters of locally linear embedding (LLE) method in Scikit-learn for dimensionality-reduction
I'm using locally linear embedding (LLE) method in Scikit-learn for dimensionality reduction. The only example that I could find belong to the Scikit-learn documentation here and here, but I'm not sure how should I choose the parameters of the method. In particular, is there any relation between the dimension of data points or the number of samples and the number of neighbors (n_neighbors) and number of components (n_components)? All of the examples in Scikit-learn use n_components=2, is this always the case? Finally, is there any other parameter that is critical to tune, or I should use the default setting for the rest of parameters?

答:
Is there any relation between the dimension of data points or the number of samples and the number of neighbors (n_neighbors) and number of components (n_components)?

Generally speaking, not related. n_neighbors is often decided by the distances among samples. Especially, if you know the classes of your samples, you'd better set n_neighbors a little bit greater than the number of samples in each class. While n_components, namely the reduced dimension size, is determined by the redundancy of data in original dimension. Based on the specific data distribution and your own demands, you can choose the proper space dimension for projection.

n_components=2 is to mapping the original high-dimensional space into a 2d-space. It is a special case, actually.

Is there any other parameter that is critical to tune, or I should use the default setting for the rest of parameters?

Here are several other parameters you should take care of.

reg for weight regularization, which is not used in the original LLE paper. If you don't want to use it, just simply set it to zero. However, the default value of reg is 1e-3, which is quite small.

eigen_solver. If your data size is small, it is recommended to use dense for accuracy. You can do more research on this.

max_iter. The default value of max_iter is only 100, which often causes the results not converged. If the results are not stable, please choose a larger interger.

ContentLicense: CC BY-SA 3.0


问:
Laravel : Syntax error or access violation: 1055 Error
I want to use WhereIn and Groupby in the same query to fetch Result.

I've tried this:

```<code>$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();
</code>```

But I got this error message:

SQLSTATE[42000]: Syntax error or access violation: 1055 'sbrtpt.loading.id' isn't in GROUP BY (SQL: select * from loading where id in (14, 15, 16) group by vehicle_no)

答:
Short answer

In config\database.php --> "mysql" array

Set 'strict' => false to disable all.

....   or

You can leave 'strict' => true and add modes to "mysql" option in

```<code>'mysql' => [
       ...
       ....
       'strict' => true,
       'modes' => [
            //'ONLY_FULL_GROUP_BY', // Disable this to allow grouping by one column
            'STRICT_TRANS_TABLES',
            'NO_ZERO_IN_DATE',
            'NO_ZERO_DATE',
            'ERROR_FOR_DIVISION_BY_ZERO',
            'NO_AUTO_CREATE_USER',
            'NO_ENGINE_SUBSTITUTION'
        ],
 ]
</code>```

Detailed answer

You may not need to disable all strict options ...
Kindly have a look on this answer about this issue.

ContentLicense: CC BY-SA 4.0

Body:
I want to use WhereIn and Groupby in the same query to fetch Result.

I've tried this:

$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();

But I got this error message:

SQLSTATE[42000]: Syntax error or access violation: 1055 'sbrtpt.loading.id' isn't in GROUP BY (SQL: select * from loading where id in (14, 15, 16) group by vehicle_no)

Body:
Short answer

In config\database.php --> "mysql" array

Set 'strict' => false to disable all.

....   or

You can leave 'strict' => true and add modes to "mysql" option in

'mysql' => [
       ...
       ....
       'strict' => true,
       'modes' => [
            //'ONLY_FULL_GROUP_BY', // Disable this to allow grouping by one column
            'STRICT_TRANS_TABLES',
            'NO_ZERO_IN_DATE',
            'NO_ZERO_DATE',
            'ERROR_FOR_DIVISION_BY_ZERO',
            'NO_AUTO_CREATE_USER',
            'NO_ENGINE_SUBSTITUTION'
        ],
 ]

Detailed answer

You may not need to disable all strict options ...
Kindly have a look on this answer about this issue.


问:
Manage Queue in android with service
I have a activity with recycler-view, and each list item has a download button.inside button click event i manage make call for download-service.so how can i manage queue when user click more than one download button with custom notification update.

I have googled and tried some solutions are:

1.How to Manage Queue of Runnable Tasks in Android

2.how to handle a queue in android?? java

3.Best way to update Activity from a Queue

but doesn't find the correct way to implement queue with notification update.

Here is my DownloadService Code:

```<code>public class DownloadApkService extends Service {

    private NotificationCompat.Builder notificationBuilder;
    private NotificationManager notificationManager;

    String downloadLocation;

    String appId = null;
    String appLink = null;
    String appName = null;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Queue", "queue");

        appId = intent.getStringExtra(Constants.COM_APP_ID);
        appLink = intent.getStringExtra(Constants.COM_APP_LINK);
        appName = intent.getStringExtra(Constants.COM_APP_NAME);

        Thread thread=new Thread(new MyThread(startId));
        thread.start();

        return START_STICKY;
    }

    final class MyThread implements Runnable {

        int service_id;

        MyThread(int service_id) {
            this.service_id = service_id;
        }

        @Override
        public void run() {

            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationBuilder = new NotificationCompat.Builder(DownloadApkService.this)
                    .setSmallIcon(R.drawable.ic_list_app_icon)
                    .setContentTitle(appName).setProgress(0, 0, true)
                    .setContentText("Downloading APK")
                    .setOngoing(true)
                    .setAutoCancel(true);
            notificationManager.notify(0, notificationBuilder.build());

            downloadApk();

        }
    }

    private void downloadApk() {

        downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
        String fileName = appName + ".apk";
        downloadLocation += fileName;

        File sourceFile = new File(downloadLocation);
        if (sourceFile.exists()) {
            sourceFile.delete();
        }

        Intent intentResponse = new Intent();
        intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
        intentResponse.putExtra(Constants.COM_APP_ID, appId);
        intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, "0");
        sendBroadcast(intentResponse);

        new DownloadFileFromURL().execute(appLink);

    }

    public void installApk(Uri uri) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(uri,
                "application/vnd.android.package-archive");
        DownloadApkService.this.startActivity(install);

    }

    /**
     * Background Async Task to download file
     */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        /**
         * Downloading file in background thread
         */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                Log.e("ULR", f_url[0]);
                URL url = new URL(f_url[0].trim());
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lenghtOfFile = connection.getContentLength();
                Log.e("Length", lenghtOfFile + "");

                // download the file
                InputStream input = connection.getInputStream();

                downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
                String fileName = appName + ".apk";
                downloadLocation += fileName;

                // Output stream
                FileOutputStream output = new FileOutputStream(downloadLocation);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getStackTrace().toString());
            }

            return null;
        }

        /**
         * Updating progress bar
         */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            Intent intentResponse = new Intent();
            intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
            intentResponse.putExtra(Constants.COM_APP_ID, appId);
            intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, progress[0]);
            sendBroadcast(intentResponse);
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            notificationManager.cancel(0);
            installApk(Uri.fromFile(new File(downloadLocation)));

        }

    }
}
</code>```

any help would be appriciated...

答:
Finally got answer for my own question.
I managed it with Queue class that is in java.util package.
The code i have been used is below:

```<code>public class DownloadApkService extends Service {

    private NotificationManager notificationManager = null;

    String downloadLocation;

    String appId = null;
    String appLink = null;
    String appName = null;
    String isApkFromServer = null;

    public boolean isDownloading = false;

    public static Queue<QueueData> downloadQueue = new LinkedList<>();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (isDownloading) {
            QueueData queueData = new QueueData();
            queueData.setAppId(intent.getStringExtra(Constants.COM_APP_ID));
            queueData.setAppLink(intent.getStringExtra(Constants.COM_APP_LINK));
            queueData.setIsApkFromServer(intent.getStringExtra(Constants.COM_APK_FROM_SERVER));
            queueData.setAppName(intent.getStringExtra(Constants.COM_APP_NAME));

            downloadQueue.add(queueData);
            Intent intentQueueingApk = new Intent();
            intentQueueingApk.setAction(Constants.ACTION_QUEUEING_APK);
            sendBroadcast(intentQueueingApk);
            return START_NOT_STICKY;
        } else {
            appId = intent.getStringExtra(Constants.COM_APP_ID);
            appLink = intent.getStringExtra(Constants.COM_APP_LINK);
            appName = intent.getStringExtra(Constants.COM_APP_NAME);
            isApkFromServer = intent.getStringExtra(Constants.COM_APK_FROM_SERVER);
        }
        Thread thread = new Thread(new MyThread());
        thread.start();

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (notificationManager != null) {
            notificationManager.cancel(0);
        }
    }

    class MyThread implements Runnable {

        MyThread() {
        }

        @Override
        public void run() {

            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(DownloadApkService.this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(appName).setProgress(0, 0, true)
                    .setContentText(getResources().getText(R.string.downloading_notification))
                    .setOngoing(true)
                    .setAutoCancel(true);
            notificationManager.notify(0, notificationBuilder.build());
            new DownloadFileFromURL().execute(appLink);

        }
    }

    public void installApk(Uri uri) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(uri,
                "application/vnd.android.package-archive");
        DownloadApkService.this.startActivity(install);

    }

    /**
     * Background Async Task to download file
     */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            isDownloading = true;

            Intent intentResponse = new Intent();
            intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
            intentResponse.putExtra(Constants.COM_APP_ID, appId);
            intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, "0");
            sendBroadcast(intentResponse);
        }

        /**
         * Downloading file in background thread
         */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            HttpURLConnection connection=null;
            try {
                String link=f_url[0].replace(" ","%20");
                URL url = new URL(link);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Accept-Encoding", "identity");
                int lenghtOfFile = connection.getContentLength();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar

                // download the file
                InputStream input = new BufferedInputStream(connection.getInputStream());

                downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
                String fileName = appName + ".apk";
                downloadLocation += fileName;

                File sourceFile = new File(downloadLocation);
                if (sourceFile.exists()) {
                    sourceFile.delete();
                }

                // Output stream
                FileOutputStream output = new FileOutputStream(downloadLocation);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                return "fail";
            }finally {
                if(connection != null)
                    connection.disconnect();
            }

            return "success";
        }

        /**
         * Updating progress bar
         */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            Intent intentResponse = new Intent();
            intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
            intentResponse.putExtra(Constants.COM_APP_ID, appId);
            intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, progress[0]);
            sendBroadcast(intentResponse);

            Intent intentQueueingApk = new Intent();
            intentQueueingApk.setAction(Constants.ACTION_QUEUEING_APK);
            sendBroadcast(intentQueueingApk);
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        @Override
        protected void onPostExecute(String file_url) {

            notificationManager.cancel(0);
            if (file_url.equals("success")) {
                Intent intentResponse = new Intent();
                intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK_COMPLETE);
                intentResponse.putExtra(Constants.COM_APP_ID, appId);
                sendBroadcast(intentResponse);

                isDownloading = false;

                if (isApkFromServer!=null && isApkFromServer.equals("0")) {
                    Intent intent = new Intent(DownloadApkService.this, UploadApkService.class);
                    intent.putExtra(Constants.COM_APP_ID, mAppDetails.getId());
                    intent.putExtra(Constants.COM_APK_FILE_PATH, downloadLocation);
                    startService(intent);
                }

                installApk(Uri.fromFile(new File(downloadLocation)));
            } else if (file_url.equals("fail")) {
                isDownloading = false;
                Intent intentResponse = new Intent();
                intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK_FAILED);
                intentResponse.putExtra(Constants.COM_APP_ID, appId);
                sendBroadcast(intentResponse);
            }

            if (/*isDownloading &&*/ !downloadQueue.isEmpty()) {
                QueueData queueData = downloadQueue.poll();
                appId = queueData.getAppId();
                appLink = queueData.getAppLink();
                appName = queueData.getAppName();
                isApkFromServer = queueData.getIsApkFromServer();

                Thread thread = new Thread(new MyThread());
                thread.start();
            }

        }

    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        if (notificationManager != null)
            notificationManager.cancel(0);
    }
}
</code>```

I hope it's going to be helpful for someone.

Title: Manage Queue in android with service

Body:
I have a activity with recycler-view, and each list item has a download button.inside button click event i manage make call for download-service.so how can i manage queue when user click more than one download button with custom notification update.

I have googled and tried some solutions are:

1.How to Manage Queue of Runnable Tasks in Android

2.how to handle a queue in android?? java

3.Best way to update Activity from a Queue

but doesn't find the correct way to implement queue with notification update.

Here is my DownloadService Code:

public class DownloadApkService extends Service {

    private NotificationCompat.Builder notificationBuilder;
    private NotificationManager notificationManager;

    String downloadLocation;

    String appId = null;
    String appLink = null;
    String appName = null;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Queue", "queue");

        appId = intent.getStringExtra(Constants.COM_APP_ID);
        appLink = intent.getStringExtra(Constants.COM_APP_LINK);
        appName = intent.getStringExtra(Constants.COM_APP_NAME);

        Thread thread=new Thread(new MyThread(startId));
        thread.start();

        return START_STICKY;
    }

    final class MyThread implements Runnable {

        int service_id;

        MyThread(int service_id) {
            this.service_id = service_id;
        }

        @Override
        public void run() {

            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationBuilder = new NotificationCompat.Builder(DownloadApkService.this)
                    .setSmallIcon(R.drawable.ic_list_app_icon)
                    .setContentTitle(appName).setProgress(0, 0, true)
                    .setContentText("Downloading APK")
                    .setOngoing(true)
                    .setAutoCancel(true);
            notificationManager.notify(0, notificationBuilder.build());

            downloadApk();

        }
    }

    private void downloadApk() {

        downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
        String fileName = appName + ".apk";
        downloadLocation += fileName;

        File sourceFile = new File(downloadLocation);
        if (sourceFile.exists()) {
            sourceFile.delete();
        }

        Intent intentResponse = new Intent();
        intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
        intentResponse.putExtra(Constants.COM_APP_ID, appId);
        intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, "0");
        sendBroadcast(intentResponse);

        new DownloadFileFromURL().execute(appLink);

    }

    public void installApk(Uri uri) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(uri,
                "application/vnd.android.package-archive");
        DownloadApkService.this.startActivity(install);

    }

    /**
     * Background Async Task to download file
     */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        /**
         * Downloading file in background thread
         */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                Log.e("ULR", f_url[0]);
                URL url = new URL(f_url[0].trim());
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lenghtOfFile = connection.getContentLength();
                Log.e("Length", lenghtOfFile + "");

                // download the file
                InputStream input = connection.getInputStream();

                downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
                String fileName = appName + ".apk";
                downloadLocation += fileName;

                // Output stream
                FileOutputStream output = new FileOutputStream(downloadLocation);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getStackTrace().toString());
            }

            return null;
        }

        /**
         * Updating progress bar
         */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            Intent intentResponse = new Intent();
            intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
            intentResponse.putExtra(Constants.COM_APP_ID, appId);
            intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, progress[0]);
            sendBroadcast(intentResponse);
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            notificationManager.cancel(0);
            installApk(Uri.fromFile(new File(downloadLocation)));

        }

    }
}

any help would be appriciated...

Body:
Finally got answer for my own question.
I managed it with Queue class that is in java.util package.
The code i have been used is below:

public class DownloadApkService extends Service {

    private NotificationManager notificationManager = null;

    String downloadLocation;

    String appId = null;
    String appLink = null;
    String appName = null;
    String isApkFromServer = null;

    public boolean isDownloading = false;

    public static Queue<QueueData> downloadQueue = new LinkedList<>();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (isDownloading) {
            QueueData queueData = new QueueData();
            queueData.setAppId(intent.getStringExtra(Constants.COM_APP_ID));
            queueData.setAppLink(intent.getStringExtra(Constants.COM_APP_LINK));
            queueData.setIsApkFromServer(intent.getStringExtra(Constants.COM_APK_FROM_SERVER));
            queueData.setAppName(intent.getStringExtra(Constants.COM_APP_NAME));

            downloadQueue.add(queueData);
            Intent intentQueueingApk = new Intent();
            intentQueueingApk.setAction(Constants.ACTION_QUEUEING_APK);
            sendBroadcast(intentQueueingApk);
            return START_NOT_STICKY;
        } else {
            appId = intent.getStringExtra(Constants.COM_APP_ID);
            appLink = intent.getStringExtra(Constants.COM_APP_LINK);
            appName = intent.getStringExtra(Constants.COM_APP_NAME);
            isApkFromServer = intent.getStringExtra(Constants.COM_APK_FROM_SERVER);
        }
        Thread thread = new Thread(new MyThread());
        thread.start();

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (notificationManager != null) {
            notificationManager.cancel(0);
        }
    }

    class MyThread implements Runnable {

        MyThread() {
        }

        @Override
        public void run() {

            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(DownloadApkService.this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(appName).setProgress(0, 0, true)
                    .setContentText(getResources().getText(R.string.downloading_notification))
                    .setOngoing(true)
                    .setAutoCancel(true);
            notificationManager.notify(0, notificationBuilder.build());
            new DownloadFileFromURL().execute(appLink);

        }
    }

    public void installApk(Uri uri) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(uri,
                "application/vnd.android.package-archive");
        DownloadApkService.this.startActivity(install);

    }

    /**
     * Background Async Task to download file
     */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            isDownloading = true;

            Intent intentResponse = new Intent();
            intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
            intentResponse.putExtra(Constants.COM_APP_ID, appId);
            intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, "0");
            sendBroadcast(intentResponse);
        }

        /**
         * Downloading file in background thread
         */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            HttpURLConnection connection=null;
            try {
                String link=f_url[0].replace(" ","%20");
                URL url = new URL(link);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Accept-Encoding", "identity");
                int lenghtOfFile = connection.getContentLength();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar

                // download the file
                InputStream input = new BufferedInputStream(connection.getInputStream());

                downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
                String fileName = appName + ".apk";
                downloadLocation += fileName;

                File sourceFile = new File(downloadLocation);
                if (sourceFile.exists()) {
                    sourceFile.delete();
                }

                // Output stream
                FileOutputStream output = new FileOutputStream(downloadLocation);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                return "fail";
            }finally {
                if(connection != null)
                    connection.disconnect();
            }

            return "success";
        }

        /**
         * Updating progress bar
         */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            Intent intentResponse = new Intent();
            intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
            intentResponse.putExtra(Constants.COM_APP_ID, appId);
            intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, progress[0]);
            sendBroadcast(intentResponse);

            Intent intentQueueingApk = new Intent();
            intentQueueingApk.setAction(Constants.ACTION_QUEUEING_APK);
            sendBroadcast(intentQueueingApk);
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        @Override
        protected void onPostExecute(String file_url) {

            notificationManager.cancel(0);
            if (file_url.equals("success")) {
                Intent intentResponse = new Intent();
                intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK_COMPLETE);
                intentResponse.putExtra(Constants.COM_APP_ID, appId);
                sendBroadcast(intentResponse);

                isDownloading = false;

                if (isApkFromServer!=null && isApkFromServer.equals("0")) {
                    Intent intent = new Intent(DownloadApkService.this, UploadApkService.class);
                    intent.putExtra(Constants.COM_APP_ID, mAppDetails.getId());
                    intent.putExtra(Constants.COM_APK_FILE_PATH, downloadLocation);
                    startService(intent);
                }

                installApk(Uri.fromFile(new File(downloadLocation)));
            } else if (file_url.equals("fail")) {
                isDownloading = false;
                Intent intentResponse = new Intent();
                intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK_FAILED);
                intentResponse.putExtra(Constants.COM_APP_ID, appId);
                sendBroadcast(intentResponse);
            }

            if (/*isDownloading &&*/ !downloadQueue.isEmpty()) {
                QueueData queueData = downloadQueue.poll();
                appId = queueData.getAppId();
                appLink = queueData.getAppLink();
                appName = queueData.getAppName();
                isApkFromServer = queueData.getIsApkFromServer();

                Thread thread = new Thread(new MyThread());
                thread.start();
            }

        }

    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        if (notificationManager != null)
            notificationManager.cancel(0);
    }
}

I hope it's going to be helpful for someone.


问:
Change other table view cell's data when selecting one of them
When I tap on a table view cell I need to change another cell's detail label text.
How can I do this?</p>

答:
You need to stored indexPath for selected row. You can put a condition in cellForRow about same.

Here is sort example:

Declare variable in .h file:

```<code>int selectedIndexPath;
</code>```

.m

```<code>    -(void)viewDidLoad
     {
           [super viewDidLoad];
           // So it won't show any select for the first time
           selectedIndexPath = -1;
           [tableView reloadData];
     }

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        int currentRow = (int)indexPath.row;
        if(currentRow == selectedIndexPath)
        {
            // Show your base cell
        }
        else
        {
            // Show detail cell
        }
    }
    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        selectedIndexPath = (int)indexPath.row;
        [tableView reloadData];

    }
</code>```

Body:
You need to stored indexPath for selected row. You can put a condition in cellForRow about same.

Here is sort example:

Declare variable in .h file:

int selectedIndexPath;

.m

    -(void)viewDidLoad
     {
           [super viewDidLoad];
           // So it won't show any select for the first time
           selectedIndexPath = -1;
           [tableView reloadData];
     }

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        int currentRow = (int)indexPath.row;
        if(currentRow == selectedIndexPath)
        {
            // Show your base cell
        }
        else
        {
            // Show detail cell
        }
    }
    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        selectedIndexPath = (int)indexPath.row;
        [tableView reloadData];

    }


问:
How to open a second activity on click of button in android app
I am learning to build android applications and I need some specific help. I can't seem to get my head around which bits of template code I am required to change, and which bits are static.

In the LAYOUT folder I have my ACTIVITY_MAIN.XML which reads

```<code> <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="horizontal">

 <Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/main_buttons_photos" />

 </LinearLayout>
</code>```

Next, I have my second activity ACTIVITY_SEND_PHOTOS.XML which is

```<code> <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="match_parent" >

 <TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world"
    tools:context=".SendPhotos" />

 <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="@string/title_activity_send_photos"
    android:textAppearance="?android:attr/textAppearanceLarge" />

 </RelativeLayout>
</code>```

I then have my MainActivity.java (is this the .class?) this reads
     package com.example.assent.bc;

```<code> import android.os.Bundle;
 import android.app.Activity;
 import android.view.Menu;
 import android.view.View;

 public class MainActivity extends Activity {

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

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
     getMenuInflater().inflate(R.menu.activity_main, menu);
     return true;
 }
 /** Called when the user clicks the Send button */
 public void sendMessage(View view) {
     // Do something in response to button
 }
 }
</code>```

and then my SendPhotos.java file which is;

```<code> package com.example.assent.bc;

 import android.os.Bundle;
 import android.app.Activity;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.support.v4.app.NavUtils;

 public class SendPhotos extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_photos);
    getActionBar().setDisplayHomeAsUpEnabled(true);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_send_photos, menu);
    return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
 }

 }
</code>```

I would like the button in my main activity to link through to my sendphotos activity, simply opening up that activity, nothing fancy, not sending any data or anything.

I know that somewhere I need my

```<code> Intent i = new Intent(FromActivity.this, ToActivity.class);
 startActivity(i);
</code>```

but I have no idea what to replace ToActivity.class with or what else I need where.

答:
```<code> <Button
            android:id="@+id/btnSignIn"
            android:layout_width="250dp"
            android:layout_height="40dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:background="@drawable/circal"
            android:text="Sign in"
            android:textColor="@color/white"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/etPasswordLogin" />
</code>```

IN JAVA CODE

```<code>Button signIn= (Button) findViewById(R.id.btnSignIn);

signIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(SignInPage.this,MainActivity.class));
            }
        });
</code>```

}

Body:
I am learning to build android applications and I need some specific help. I can't seem to get my head around which bits of template code I am required to change, and which bits are static.

In the LAYOUT folder I have my ACTIVITY_MAIN.XML which reads

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="horizontal">

 <Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/main_buttons_photos" />

 </LinearLayout>

Next, I have my second activity ACTIVITY_SEND_PHOTOS.XML which is

 <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="match_parent" >

 <TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world"
    tools:context=".SendPhotos" />

 <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="@string/title_activity_send_photos"
    android:textAppearance="?android:attr/textAppearanceLarge" />

 </RelativeLayout>

I then have my MainActivity.java (is this the .class?) this reads
     package com.example.assent.bc;

 import android.os.Bundle;
 import android.app.Activity;
 import android.view.Menu;
 import android.view.View;

 public class MainActivity extends Activity {

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

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
     getMenuInflater().inflate(R.menu.activity_main, menu);
     return true;
 }
 /** Called when the user clicks the Send button */
 public void sendMessage(View view) {
     // Do something in response to button
 }
 }

and then my SendPhotos.java file which is;

 package com.example.assent.bc;

 import android.os.Bundle;
 import android.app.Activity;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.support.v4.app.NavUtils;

 public class SendPhotos extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_photos);
    getActionBar().setDisplayHomeAsUpEnabled(true);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_send_photos, menu);
    return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
 }

 }

I would like the button in my main activity to link through to my sendphotos activity, simply opening up that activity, nothing fancy, not sending any data or anything.

I know that somewhere I need my

 Intent i = new Intent(FromActivity.this, ToActivity.class);
 startActivity(i);

but I have no idea what to replace ToActivity.class with or what else I need where.

Body:
 <Button
            android:id="@+id/btnSignIn"
            android:layout_width="250dp"
            android:layout_height="40dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:background="@drawable/circal"
            android:text="Sign in"
            android:textColor="@color/white"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/etPasswordLogin" />

IN JAVA CODE

Button signIn= (Button) findViewById(R.id.btnSignIn);

signIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(SignInPage.this,MainActivity.class));
            }
        });

}


问:
tcl script to extract values from multiple text files having same format and generating column based reports
I have the output logs which are created from Seg-Y files.
Example :

```<code>TRACE HEADER====================================================================================================================
                                                                                MIN            MAX           MEAN          COUNT
Trace sequence number within line                          [001-004]:             1         140400       70200.50         140400
Trace sequence number within SEGY file                     [005-008]:             1         140400       70200.50         140400
Original field record number                               [009-012]:          1001           4900        2950.50         140400
Trace number within original field record                  [013-016]:             1             36          18.50         140400
Energy source point                                        [017-020]:          1001           4900        2950.50         140400
Not used for NFH                                           [021-024]:             0              0           0.00         140400
Hydrophone number in gun source                            [025-028]:             1             18           9.50         140400
Trace identification code                                  [029-030]:             1              1           1.00         140400
No of vertically summed traces yielding this trace         [031-032]:             1              1           1.00         140400
No of horizontally stacked traces yielding this trace      [033-034]:             1              1           1.00         140400
Production1/test2                                          [035-036]:             1              1           1.00         140400
Distance from COS to centre of receiver group              [037-040]:             0             68          22.72         140400
Receiver group depth (scalar #1)                           [041-044]:           460            580         529.82         140400
Tidal observation to vertical datum (scalar #1)            [045-048]:           -82             61           3.00         140400
Source depth (scalar #1)                                   [049-052]:           580            650         613.37         140400
Not used                                                   [053-056]:             0              0           0.00         140400
Not used                                                   [057-060]:             0              0           0.00         140400
Water depth at source (scalar #1)                          [061-064]:        298955         357609      330298.17         140400
Water depth at receiver group (scalar #1)                  [065-068]:        298946         357610      330298.17         140400
Scalar #1 (-ve => divisor)                                 [069-070]:          -100           -100        -100.00         140400
Scalar #2 (-ve => divisor)                                 [071-072]:          -100           -100        -100.00         140400
Source coordinate - X (scalar #2)                          [073-076]:      53664190       53702900    53682718.56         140400
Source coordinate - Y (scalar #2)                          [077-080]:      97593580      107341780   102467937.72         140400
Receiver group coordinate - X (scalar #2)                  [081-084]:      53663450       53703800    53682718.74         140400
Receiver group coordinate - Y (scalar #2)                  [085-088]:      97592690      107342690   102467936.95         140400
Coordinate units                                           [089-090]:             1              1           1.00         140400
Water velocity (as used in p1 water depth)                 [091-092]:          1496           1496        1496.00         140400
Not used                                                   [093-094]:             0              0           0.00         140400
Skew static correction (Scalar #3). Not used for NFH       [095-096]:             0              0           0.00         140400
Water bottom time at CDP/bin centre (Scalar #3)            [097-098]:          3997           4781        4415.75         140400
Source static correction (Scalar #3). Not used for NFH     [099-100]:             0              0           0.00         140400
Receiver group static corr (Scalar #3). Not used for NFH   [101-102]:             0              0           0.00         140400
Total static corr applied (Scalar #3). Not used for NFH    [103-104]:             0              0           0.00         140400
Lag time A. Not used for NFH                               [105-106]:             0              0           0.00         140400
Delay recording time (Scalar #3)                           [107-108]:           -50            -50         -50.00         140400
Original delay recording time. Not used for NFH            [109-110]:             0              0           0.00         140400
Mute time - start (Scalar #3). Not used for NFH            [111-112]:             0              0           0.00         140400
Mute time - end (Scalar #3). Not used for NFH              [113-114]:             0              0           0.00         140400
Number of samples in this trace                            [115-116]:         22529          22529       22529.00         140400
Sample interval for this trace in microsecs                [117-118]:           500            500         500.00         140400
Gain type of field instruments                             [119-120]:             1              1           1.00         140400
Instrument gain - constant. Not used for NFH               [121-122]:             0              0           0.00         140400
Instrument early/initial gain. Not used for NFH            [123-124]:             0              0           0.00         140400
Streamer section serial number. Not used for NFH           [125-128]:             0              0           0.00         140400
Continuous recording shot timer. Not used for NFH          [129-132]:             0              0           0.00         140400
Value obs jitter in aux chan timing. Not used for NFH      [133-134]:             0              0           0.00         140400
Not used                                                   [135-136]:             0              0           0.00         140400
Not used                                                   [137-138]:             0              0           0.00         140400
Not used                                                   [139-140]:             0              0           0.00         140400
Anti-alias filter frequency                                [141-142]:           800            800         800.00         140400
Anti-alias filter slope                                    [143-144]:           240            240         240.00         140400
Not used                                                   [145-146]:             0              0           0.00         140400
Bandpass filter type                                       [147-148]:             0              0           0.00         140400
Low cut filter frequency                                   [149-150]:             3              3           3.00         140400
High cut frequency                                         [151-152]:           800            800         800.00         140400
Low cut filter slope                                       [153-154]:             6              6           6.00         140400
High cut filter slope                                      [155-156]:           240            240         240.00         140400
Year data recorded                                         [157-158]:          2017           2017        2017.00         140400
Day of year data recorded                                  [159-160]:           134            135         134.09         140400
Hour of day data recorded                                  [161-162]:             0             23          17.44         140400
Minute of hour data recorded                               [163-164]:             0             59          29.70         140400
Second of minute data recorded                             [165-166]:             0             59          29.58         140400
Time basis code                                            [167-168]:             4              4           4.00         140400
Not used                                                   [169-170]:             0              0           0.00         140400
This file elevation datum                                  [171-172]:             2              2           2.00         140400
Final survey elevation datum. Not used for NFH             [173-174]:             0              0           0.00         140400
Start time of data ms. Not used for NFH                    [175-176]:             0              0           0.00         140400
End time of data ms. Not used for NFH                      [177-178]:             0              0           0.00         140400
Scalar #3 (-ve => divisor). Not used for NFH               [179-180]:             0              0           0.00         140400
Gun string id number                                       [181-182]:             1              6           3.50         140400
Sailed line sequence number                                [183-184]:           101            101         101.00         140400
Gun mask                                                   [185-186]:             1              2           1.50         140400
Original gun mask                                          [187-188]:             7             56          31.50         140400
Numerical sail line number                                 [189-192]:          4300           4300        4300.00         140400
Receiver cable depth                                       [193-196]:           460            580         529.82         140400
Shot point number                                          [197-200]:          1001           4900        2950.50         140400
Calibration scalar                                         [201-202]:           643           2808        2000.00         140400
Trace value measurement                                    [203-204]:             3              3           3.00         140400
3D inline number                                           [205-208]:          4298           4314        4305.40         140400
3D crossline number                                        [209-212]:         10009          25608       17808.88         140400
Ensemble coordinate - X                                    [213-216]:      53663820       53703350    53682718.65         140400
Ensemble coordinate - Y                                    [217-220]:      97593135      107342235   102467937.34         140400
Gun boat identifier. Not sued for NFH                      [221-222]:             0              0           0.00         140400
Streamer boat identifier. Not used NFH                     [223-224]:             0              0           0.00         140400
Waterbottom time at CDP/bin centre ms                      [225-228]:          3997           4781        4415.75         140400
Source-receiver azimuth                                    [229-230]:             0            359         172.57         140400
</code>```

There are bunch of these log as one log is created for each Seg-Y file.
I have already created a shell script which extracts information from these logs and prints it column wise.

see below link :

http://textuploader.com/d0z0u

The script uses grep and awk mainly.

What I was planning on doing was writing the same script in tcl so that I can have a GUI on Tk and acheive the same functionality using arrays or lists somehow using split but I am new to Tcl and can't get my head around properly extracting information from the logs , I am already working on building the front end GUI just want to get the tcl script sorted so that I can start binding it with GUI.

I want to extract linename , RANGE , FILE etc etc from EBCDIC Header part
Line NUmber , Reel NUmber etc from BInary header part
and all the MIN-MAX from the Trace Header Part

In my report I want the column names to be the same as row names.

Thanks For help.

答:
There a number of ways to do this. Maybe the simplest is just using

exec <yourexistingscript>

You know your script pulls the right stuff out, just have Tcl run that.

Otherwise, here's a basic skeleton of how I write file-parsing code in Tcl when I'm doing it from scratch:

```<code>set fh [open "file.dat", "r"]
while {[gets $fh line] >= 0} {
  if {<line matches pattern 1>} {
  }
  if {<line matches pattern 2>} {
  }
}
close $fh
</code>```

etc, where the <line matches pattern N> parts are either [string match...] or [regexp ...] lines, depending on the situation. This is basically exactly how awk works. A line-based thing with matches and code to run on them.

The code inside those matches will also vary depending on the situation, but a typical chunk uses [split] to break the line up by some delimiter. It looks like a space might work here, but I haven't perused your file in detail.

Body:
I have the output logs which are created from Seg-Y files.
Example :

TRACE HEADER====================================================================================================================
                                                                                MIN            MAX           MEAN          COUNT
Trace sequence number within line                          [001-004]:             1         140400       70200.50         140400
Trace sequence number within SEGY file                     [005-008]:             1         140400       70200.50         140400
Original field record number                               [009-012]:          1001           4900        2950.50         140400
Trace number within original field record                  [013-016]:             1             36          18.50         140400
Energy source point                                        [017-020]:          1001           4900        2950.50         140400
Not used for NFH                                           [021-024]:             0              0           0.00         140400
Hydrophone number in gun source                            [025-028]:             1             18           9.50         140400
Trace identification code                                  [029-030]:             1              1           1.00         140400
No of vertically summed traces yielding this trace         [031-032]:             1              1           1.00         140400
No of horizontally stacked traces yielding this trace      [033-034]:             1              1           1.00         140400
Production1/test2                                          [035-036]:             1              1           1.00         140400
Distance from COS to centre of receiver group              [037-040]:             0             68          22.72         140400
Receiver group depth (scalar #1)                           [041-044]:           460            580         529.82         140400
Tidal observation to vertical datum (scalar #1)            [045-048]:           -82             61           3.00         140400
Source depth (scalar #1)                                   [049-052]:           580            650         613.37         140400
Not used                                                   [053-056]:             0              0           0.00         140400
Not used                                                   [057-060]:             0              0           0.00         140400
Water depth at source (scalar #1)                          [061-064]:        298955         357609      330298.17         140400
Water depth at receiver group (scalar #1)                  [065-068]:        298946         357610      330298.17         140400
Scalar #1 (-ve => divisor)                                 [069-070]:          -100           -100        -100.00         140400
Scalar #2 (-ve => divisor)                                 [071-072]:          -100           -100        -100.00         140400
Source coordinate - X (scalar #2)                          [073-076]:      53664190       53702900    53682718.56         140400
Source coordinate - Y (scalar #2)                          [077-080]:      97593580      107341780   102467937.72         140400
Receiver group coordinate - X (scalar #2)                  [081-084]:      53663450       53703800    53682718.74         140400
Receiver group coordinate - Y (scalar #2)                  [085-088]:      97592690      107342690   102467936.95         140400
Coordinate units                                           [089-090]:             1              1           1.00         140400
Water velocity (as used in p1 water depth)                 [091-092]:          1496           1496        1496.00         140400
Not used                                                   [093-094]:             0              0           0.00         140400
Skew static correction (Scalar #3). Not used for NFH       [095-096]:             0              0           0.00         140400
Water bottom time at CDP/bin centre (Scalar #3)            [097-098]:          3997           4781        4415.75         140400
Source static correction (Scalar #3). Not used for NFH     [099-100]:             0              0           0.00         140400
Receiver group static corr (Scalar #3). Not used for NFH   [101-102]:             0              0           0.00         140400
Total static corr applied (Scalar #3). Not used for NFH    [103-104]:             0              0           0.00         140400
Lag time A. Not used for NFH                               [105-106]:             0              0           0.00         140400
Delay recording time (Scalar #3)                           [107-108]:           -50            -50         -50.00         140400
Original delay recording time. Not used for NFH            [109-110]:             0              0           0.00         140400
Mute time - start (Scalar #3). Not used for NFH            [111-112]:             0              0           0.00         140400
Mute time - end (Scalar #3). Not used for NFH              [113-114]:             0              0           0.00         140400
Number of samples in this trace                            [115-116]:         22529          22529       22529.00         140400
Sample interval for this trace in microsecs                [117-118]:           500            500         500.00         140400
Gain type of field instruments                             [119-120]:             1              1           1.00         140400
Instrument gain - constant. Not used for NFH               [121-122]:             0              0           0.00         140400
Instrument early/initial gain. Not used for NFH            [123-124]:             0              0           0.00         140400
Streamer section serial number. Not used for NFH           [125-128]:             0              0           0.00         140400
Continuous recording shot timer. Not used for NFH          [129-132]:             0              0           0.00         140400
Value obs jitter in aux chan timing. Not used for NFH      [133-134]:             0              0           0.00         140400
Not used                                                   [135-136]:             0              0           0.00         140400
Not used                                                   [137-138]:             0              0           0.00         140400
Not used                                                   [139-140]:             0              0           0.00         140400
Anti-alias filter frequency                                [141-142]:           800            800         800.00         140400
Anti-alias filter slope                                    [143-144]:           240            240         240.00         140400
Not used                                                   [145-146]:             0              0           0.00         140400
Bandpass filter type                                       [147-148]:             0              0           0.00         140400
Low cut filter frequency                                   [149-150]:             3              3           3.00         140400
High cut frequency                                         [151-152]:           800            800         800.00         140400
Low cut filter slope                                       [153-154]:             6              6           6.00         140400
High cut filter slope                                      [155-156]:           240            240         240.00         140400
Year data recorded                                         [157-158]:          2017           2017        2017.00         140400
Day of year data recorded                                  [159-160]:           134            135         134.09         140400
Hour of day data recorded                                  [161-162]:             0             23          17.44         140400
Minute of hour data recorded                               [163-164]:             0             59          29.70         140400
Second of minute data recorded                             [165-166]:             0             59          29.58         140400
Time basis code                                            [167-168]:             4              4           4.00         140400
Not used                                                   [169-170]:             0              0           0.00         140400
This file elevation datum                                  [171-172]:             2              2           2.00         140400
Final survey elevation datum. Not used for NFH             [173-174]:             0              0           0.00         140400
Start time of data ms. Not used for NFH                    [175-176]:             0              0           0.00         140400
End time of data ms. Not used for NFH                      [177-178]:             0              0           0.00         140400
Scalar #3 (-ve => divisor). Not used for NFH               [179-180]:             0              0           0.00         140400
Gun string id number                                       [181-182]:             1              6           3.50         140400
Sailed line sequence number                                [183-184]:           101            101         101.00         140400
Gun mask                                                   [185-186]:             1              2           1.50         140400
Original gun mask                                          [187-188]:             7             56          31.50         140400
Numerical sail line number                                 [189-192]:          4300           4300        4300.00         140400
Receiver cable depth                                       [193-196]:           460            580         529.82         140400
Shot point number                                          [197-200]:          1001           4900        2950.50         140400
Calibration scalar                                         [201-202]:           643           2808        2000.00         140400
Trace value measurement                                    [203-204]:             3              3           3.00         140400
3D inline number                                           [205-208]:          4298           4314        4305.40         140400
3D crossline number                                        [209-212]:         10009          25608       17808.88         140400
Ensemble coordinate - X                                    [213-216]:      53663820       53703350    53682718.65         140400
Ensemble coordinate - Y                                    [217-220]:      97593135      107342235   102467937.34         140400
Gun boat identifier. Not sued for NFH                      [221-222]:             0              0           0.00         140400
Streamer boat identifier. Not used NFH                     [223-224]:             0              0           0.00         140400
Waterbottom time at CDP/bin centre ms                      [225-228]:          3997           4781        4415.75         140400
Source-receiver azimuth                                    [229-230]:             0            359         172.57         140400

There are bunch of these log as one log is created for each Seg-Y file.
I have already created a shell script which extracts information from these logs and prints it column wise.

see below link :

http://textuploader.com/d0z0u

The script uses grep and awk mainly.

What I was planning on doing was writing the same script in tcl so that I can have a GUI on Tk and acheive the same functionality using arrays or lists somehow using split but I am new to Tcl and can't get my head around properly extracting information from the logs , I am already working on building the front end GUI just want to get the tcl script sorted so that I can start binding it with GUI.

I want to extract linename , RANGE , FILE etc etc from EBCDIC Header part
Line NUmber , Reel NUmber etc from BInary header part
and all the MIN-MAX from the Trace Header Part

In my report I want the column names to be the same as row names.

Thanks For help.

Body:
There a number of ways to do this. Maybe the simplest is just using

exec <yourexistingscript>

You know your script pulls the right stuff out, just have Tcl run that.

Otherwise, here's a basic skeleton of how I write file-parsing code in Tcl when I'm doing it from scratch:

set fh [open "file.dat", "r"]
while {[gets $fh line] >= 0} {
  if {<line matches pattern 1>} {
  }
  if {<line matches pattern 2>} {
  }
}
close $fh

etc, where the <line matches pattern N> parts are either [string match...] or [regexp ...] lines, depending on the situation. This is basically exactly how awk works. A line-based thing with matches and code to run on them.

The code inside those matches will also vary depending on the situation, but a typical chunk uses [split] to break the line up by some delimiter. It looks like a space might work here, but I haven't perused your file in detail.


问:
How to get persistent access to a user's google account?
My app pulls info from my users' Google Calendars.
The users already have to login to my app, so they find it annoying that they have to "Grant Access" to their google account at least once per session (currently using OAuth).

Is there a way to get a permanent (or closer to it) grant?

I'm even open to using openID as my primary authentication. Would that help?

I believe the GData API offers a ClientLogin protocol which would require me to store the users' login info, and I'm not comfortable with that, although if it comes down to it I suppose it's better than the alternative.

答: There is an Oauth/OpenID hybrid solution (see source) - basically you ask for certain scope access, get basic user data and request token in return, then you exchange it for auth token and save it for future use.

ContentLicense: CC BY-SA 2.5


问:
Javascript remove elements by class name
How we can remove the all div by same name of class.</p>

```<code> <input class="form-control" type="text" name="option[]"><input class="form-control" type="text" name="option[]"><input class="form-control" type="text" name="option[]">
</code>```

答:
Try with querySelectorAll() And NodeList#forEach use to iterate the element

```<code>document.querySelectorAll('.classname').forEach(function(a){
a.remove()
})
</code>```

Example snippet

document.querySelectorAll('.form-control').forEach(function(a) {
  a.remove()
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class="form-control" type="text" name="option[]">
<input class="form-control" type="text" name="option[]">
<input class="form" type="text" name="option[]" value="not same class">
<input class="form-control" type="text" name="option[]"></code>```

Body:
How we can remove the all div by same name of class.

 <input class="form-control" type="text" name="option[]"><input class="form-control" type="text" name="option[]"><input class="form-control" type="text" name="option[]">

Body:
Try with querySelectorAll() And NodeList#forEach use to iterate the element

document.querySelectorAll('.classname').forEach(function(a){
a.remove()
})

Example snippet

document.querySelectorAll('.form-control').forEach(function(a) {
  a.remove()
})

<input class="form-control" type="text" name="option[]">
<input class="form-control" type="text" name="option[]">
<input class="form" type="text" name="option[]" value="not same class">
<input class="form-control" type="text" name="option[]">


问:
Android - pass uri/string/int within same class
I would like to pass the selected videoUri to a inner class(inside same activity).

I tried doing this with bundle.putString, I am not sure if I can acheive this with bundle, I was also thinking of doing it with Intent.putExtra, but I am not passing it to a new activity?

This is what I tried:

```<code>@Override
public void OnClickVideo(Uri videoUri) {

    Bundle bundle = new Bundle();
    bundle.putString("MyBundle", videoUri.toString());

    DoAction();

}

private void DoAction() {
    mStringFilePath = getIntent().getStringExtra("MyBundle");

    Toast.makeText(getApplicationContext(), mStringFilePath, Toast.LENGTH_LONG).show();

}
</code>```

The Toast is empty...

My Question:

Is there a way to pass data/strings within the same class?

答:
You can directly pass, no need of bundle. A bundle is to transfer between Android components.

```<code>@Override
public void OnClickVideo(Uri videoUri) {

    DoAction(videoUri.toString());

}

private void DoAction(String videoUri) {

    Toast.makeText(getApplicationContext(), videoUri, Toast.LENGTH_LONG).show();

}
</code>```

or you can directly do in that method itself

```<code>@Override
public void OnClickVideo(Uri videoUri) {

    Toast.makeText(getApplicationContext(), videoUri.toString(), Toast.LENGTH_LONG).show();

}
</code>```

Body:
I would like to pass the selected videoUri to a inner class(inside same activity).

I tried doing this with bundle.putString, I am not sure if I can acheive this with bundle, I was also thinking of doing it with Intent.putExtra, but I am not passing it to a new activity?

This is what I tried:

@Override
public void OnClickVideo(Uri videoUri) {

    Bundle bundle = new Bundle();
    bundle.putString("MyBundle", videoUri.toString());

    DoAction();

}

private void DoAction() {
    mStringFilePath = getIntent().getStringExtra("MyBundle");

    Toast.makeText(getApplicationContext(), mStringFilePath, Toast.LENGTH_LONG).show();

}

The Toast is empty...

My Question:

Is there a way to pass data/strings within the same class?

Body:
You can directly pass, no need of bundle. A bundle is to transfer between Android components.

@Override
public void OnClickVideo(Uri videoUri) {

    DoAction(videoUri.toString());

}

private void DoAction(String videoUri) {

    Toast.makeText(getApplicationContext(), videoUri, Toast.LENGTH_LONG).show();

}

or you can directly do in that method itself

@Override
public void OnClickVideo(Uri videoUri) {

    Toast.makeText(getApplicationContext(), videoUri.toString(), Toast.LENGTH_LONG).show();

}


问:
Jmeter warning sign meaning
I am running a stress test on server with Jmeter with

```<code>3000 threads (users)
30 second ramp up period
</code>```

Question: Shouldn't the test finish in 30 seconds then? The test keeps going and I get something like (past 30 sec)

Something seems really wrong. What is the mistake?

答: ramp up period is about until when to start the threads, not when it ends. See warning in jneter.log or click on warning sign to find warning.</p>

Title: Jmeter warning sign meaning

Body:
I am running a stress test on server with Jmeter with

3000 threads (users)
30 second ramp up period

Question: Shouldn't the test finish in 30 seconds then? The test keeps going and I get something like (past 30 sec)

Something seems really wrong. What is the mistake?


答:
If you are using in same class means do like this </p>

```<code>@Override
public void OnClickVideo(Uri videoUri) {

DoAction(videoUri.toString());

}

private void DoAction(String mStringFilePath) {

Toast.makeText(getApplicationContext(), mStringFilePath, Toast.LENGTH_LONG).show();

}
</code>```

Title: Android - pass uri/string/int within same class

Body:
If you are using in same class means do like this

@Override
public void OnClickVideo(Uri videoUri) {

DoAction(videoUri.toString());

}

private void DoAction(String mStringFilePath) {

Toast.makeText(getApplicationContext(), mStringFilePath, Toast.LENGTH_LONG).show();

}


问:
In Java should I copy a volatile reference locally before I foreach it
If I have the following

```<code>private volatile Collection<Integer> ints;

private void myMethod()
{
   for ( Integer i : ints )
   {
      ...
   }
}
</code>```

The ints collection is never changed but the entire collection maybe replaced by another thread (so it's an immutable collection).

Should I be copying the ints variable locally before I iterate it?  I'm not sure if it will be accessed multiple times.  ie Iterating the collection, another thread replaces the collection, the code continues iterating but with the new collection.

EDIT : This question is relevant for additional info on how foreach works internally.

答: I do not think that the guys are right. That is right that you are iterating over using iterator obtained once. But if target collection is being changed during your iteration you get ConcurrentModificationException. You can easily try it. I believe that if you collection can be changed you have to track this by synchronization. </p>

Body:
If I have the following

private volatile Collection<Integer> ints;

private void myMethod()
{
   for ( Integer i : ints )
   {
      ...
   }
}

The ints collection is never changed but the entire collection maybe replaced by another thread (so it's an immutable collection).

Should I be copying the ints variable locally before I iterate it?  I'm not sure if it will be accessed multiple times.  ie Iterating the collection, another thread replaces the collection, the code continues iterating but with the new collection.

EDIT : This question is relevant for additional info on how foreach works internally.


问:
Load Enum into a Camel header
I have the following class including an enumeration:

```<code>package com.xxx.enumeration;

public class Message {
    public enum Severity {
        INFO, ERROR, WARNING;
    }
}
</code>```

How can I create a Camel header in blueprint having the ERROR value?

I tried to do the following

```<code><setHeader headerName="CamelLogSeverity">
    <simple>${type:com.xxx.enumeration.Message.Severity.ERROR}</simple>
</setHeader>
</code>```

but I am getting an exception

```<code>Caused by: java.lang.ClassNotFoundException: Cannot find type com.xxx.enumeration.Message.Severity.ERROR
</code>```

If I put the Enum out of the class it works! But how can I refer to an Enum which is a Java class?

Thanks!

答:
Posting comment as an answer so you can mark this as answered.

use Java's $ for sub classes, so it would be

```<code><simple>${type:com.xxx.enumeration.Message$Severity.ERROR}</simple>
</code>```

Title: Load Enum into a Camel header

Body:
I have the following class including an enumeration:

package com.xxx.enumeration;

public class Message {
    public enum Severity {
        INFO, ERROR, WARNING;
    }
}

How can I create a Camel header in blueprint having the ERROR value?

I tried to do the following

<setHeader headerName="CamelLogSeverity">
    <simple>${type:com.xxx.enumeration.Message.Severity.ERROR}</simple>
</setHeader>

but I am getting an exception

Caused by: java.lang.ClassNotFoundException: Cannot find type com.xxx.enumeration.Message.Severity.ERROR

If I put the Enum out of the class it works! But how can I refer to an Enum which is a Java class?

Thanks!

Body:
Posting comment as an answer so you can mark this as answered.

use Java's $ for sub classes, so it would be

<simple>${type:com.xxx.enumeration.Message$Severity.ERROR}</simple>


问:
How to make an existing Android app implement a master-detail layout
So I've built an application where you enter a bunch of information, click a button and it opens a new activity that graphs all the results.

I would like the interface and graph activities to be side-by-side on tablet devices, e.g. master-detail layout.

I've been through all the tutorials and understand it has something to do with Fragments, but don't need the tutorials lists or RecyclerView type approaches.

Can someone point me in the right direction? Reading more tutorials on lists and RecyclerView's isn't helping :(

答:
An easy way is the following:

For your main activity with the button, you create a normal layout and another layout (with the same name) in layout-sw600dp-land.  This second layout should contain two layouts, the left layout should include all the components from the normal activity and the right side should have an empty layout that you will evenutally put a fragment into.

In your main activity's onCreate(), you can do a findviewbyid on the right hand layout and if it's not null, you know you are in the "landscape tablet mode".  For this case (right hand layout not null) when the button is pressed, you can use the fragment manager to add a fragment to that right hand layout - if not, you do what you are currently doing and launch another activity.


问:
guzzle, how to force content-type in a multipart/form-data
I'm new with Guzzle and I'm trying to make a REST request to sign PDF file. The provider says :

you need to use BASIC authentication

the request must be a POST request

the mimetype should be multipart/form-data

the file sent must be application/octet-stream and its name should be "file"

the data sent must be application/json and its name should be "data"

The system returns a response which contains the signed PDF file and type is application/octet-stream

This is the code I tested with Guzzle, but the provider says that the type mime sent in application/pdf. How can I "force" the mimetype for the PDF file ?

```<code>$client = new Client([
    'auth' => ['login', 'password'],
    'debug' => true,
    'curl'  => [
                  CURLOPT_PROXY => '192.168.1.232',
                  CURLOPT_PROXYPORT => '8080',
                  CURLOPT_PROXYUSERPWD => 'username:password',
             ],
]);
$boundary = 'my_custom_boundary';
$multipart = [
            [
                'name'     => 'data',
                'contents' => "{'nomDocument':'documentTest.pdf','externalid':'123456'}",
                'Content-Type'  => 'application/json'
            ],
            [
                'name'     => 'file',
                'contents' => fopen('documentTest.pdf', 'r'),
                'Content-Type'  => 'application/octet-stream'
            ],
        ];

$params = [
    'headers' => [
        'Connection' => 'close',
        'Content-Type' => 'multipart/form-data; boundary='.$boundary,
    ],
    'body' => new GuzzleHttp\Psr7\MultipartStream($multipart, $boundary),
];

try{
    $response = $client->request('POST', 'https://server.com/api/sendDocument', $params);
} catch (RequestException $e) {
    echo Psr7\str($e->getRequest());
    if ($e->hasResponse()) {
        echo Psr7\str($e->getResponse());
    }
}
</code>```

Thank you for your help.

答:
You have to pass the Content-Type in headers

```<code>$multipart = [
        [
            'name'     => 'data',
            'contents' => "{'nomDocument':'documentTest.pdf','externalid':'123456'}",
            'headers'  => [ 'Content-Type' => 'application/json']
        ],
        [
            'name'     => 'file',
            'contents' => fopen('documentTest.pdf', 'r'),
            'headers'  => [ 'Content-Type' => 'application/octet-stream']
        ],
    ];
</code>```

in Guzzle Documentation say that you can specify headers for every multipart data.
If you not set header Guzzle put a Content-Type for you based on file.

Body:
I'm new with Guzzle and I'm trying to make a REST request to sign PDF file. The provider says :

you need to use BASIC authentication

the request must be a POST request

the mimetype should be multipart/form-data

the file sent must be application/octet-stream and its name should be "file"

the data sent must be application/json and its name should be "data"

The system returns a response which contains the signed PDF file and type is application/octet-stream

This is the code I tested with Guzzle, but the provider says that the type mime sent in application/pdf. How can I "force" the mimetype for the PDF file ?

$client = new Client([
    'auth' => ['login', 'password'],
    'debug' => true,
    'curl'  => [
                  CURLOPT_PROXY => '192.168.1.232',
                  CURLOPT_PROXYPORT => '8080',
                  CURLOPT_PROXYUSERPWD => 'username:password',
             ],
]);
$boundary = 'my_custom_boundary';
$multipart = [
            [
                'name'     => 'data',
                'contents' => "{'nomDocument':'documentTest.pdf','externalid':'123456'}",
                'Content-Type'  => 'application/json'
            ],
            [
                'name'     => 'file',
                'contents' => fopen('documentTest.pdf', 'r'),
                'Content-Type'  => 'application/octet-stream'
            ],
        ];

$params = [
    'headers' => [
        'Connection' => 'close',
        'Content-Type' => 'multipart/form-data; boundary='.$boundary,
    ],
    'body' => new GuzzleHttp\Psr7\MultipartStream($multipart, $boundary),
];

try{
    $response = $client->request('POST', 'https://server.com/api/sendDocument', $params);
} catch (RequestException $e) {
    echo Psr7\str($e->getRequest());
    if ($e->hasResponse()) {
        echo Psr7\str($e->getResponse());
    }
}

Thank you for your help.

Body:
You have to pass the Content-Type in headers

$multipart = [
        [
            'name'     => 'data',
            'contents' => "{'nomDocument':'documentTest.pdf','externalid':'123456'}",
            'headers'  => [ 'Content-Type' => 'application/json']
        ],
        [
            'name'     => 'file',
            'contents' => fopen('documentTest.pdf', 'r'),
            'headers'  => [ 'Content-Type' => 'application/octet-stream']
        ],
    ];

in Guzzle Documentation say that you can specify headers for every multipart data.
If you not set header Guzzle put a Content-Type for you based on file.


问:
Tomcat Access Logs in Spring Boot for different operating systems
Recently I've started to work with Spring Boot and have a following question:

We have different environments (like stage, development, production) and all of them can be run on windows or linux.
So I've created application-stage.properties, application-prod.properties, application-devl.properties to specify stuff like db connections and so on because its OS agnostic (the same for windows and linux).

Now I would like to enable access logs for embedded Tomcat server.
So following various guides I used the following in my application.properties file:

```<code>server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.enabled=true
</code>```

I was forced to specify a relative path because we use both linux and windows, however I would like the access log to be created in different places depending on the OS .
For example, we store logs in windows under c:\<product>\logs and in linux we use /var/log/<product>/...

For usual logs we use logbacks and it allows stuff like this, but since access log is not actually logback driven and instead uses Valves, my question is: how we can achieve the same level of flexibility here?

I don't think I should provide additional profile for this and use it like:

```<code>--spring.profiles.active=windows / linux
</code>```

Because I believe spring boot has some solution up on its sleeves for this :)
Thanks a lot in advance

答:
My favorite solution is to use additional classpath in Tomcat and load the environment-specific properties from there.

I.e. Tomcat's 'common.loader' property in conf/catalina.properties

In addition, I normally keep default properties inside the .war file, this way you will only specify the differences in the environment-specific ones.

Body:
Recently I've started to work with Spring Boot and have a following question:

We have different environments (like stage, development, production) and all of them can be run on windows or linux.
So I've created application-stage.properties, application-prod.properties, application-devl.properties to specify stuff like db connections and so on because its OS agnostic (the same for windows and linux).

Now I would like to enable access logs for embedded Tomcat server.
So following various guides I used the following in my application.properties file:

server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.enabled=true

I was forced to specify a relative path because we use both linux and windows, however I would like the access log to be created in different places depending on the OS .
For example, we store logs in windows under c:\<product>\logs and in linux we use /var/log/<product>/...

For usual logs we use logbacks and it allows stuff like this, but since access log is not actually logback driven and instead uses Valves, my question is: how we can achieve the same level of flexibility here?

I don't think I should provide additional profile for this and use it like:

--spring.profiles.active=windows / linux

Because I believe spring boot has some solution up on its sleeves for this :)
Thanks a lot in advance


问:
Resizing a component added to the canvas by dragging along the edge
I am developing an application where I need  to place rectangular slabs of different shapes to create the shape of a Bench Top. I am placing the rectangular slabs of different shapes(I am using a the Canvas container as the slab) in a repeater and dragging them on the main canvas. One functionality that needs to be implemented is the ability to resize these slabs once the are dragged from the repeater into the drawing canvas by dragging along their edges like we resize the windows that we normally see. Is there any way this can be done.</p>

答:
I just found an component developed for the purpose

http://www.rogue-development.com/objectHandles.html

I am going to check it out.

Please inform if anyone has any other solutions.


问:
Redirect url without changing root
I want change url like this

mysite.org/myhtml5/index.html.txt
 mysite.org/myhtml5/opera/index.html.txt

  mysite.org/myhtml5/clicker/index.html.txt

To

mysite.org/myhtml5/index.html
 mysite.org/myhtml5/opera/index.html

  mysite.org/myhtml5/clicker/index.html

so i tried like this

location ~ $/index.html.txt {

  return 302 $1/index.html;
}

But it's not working. Would you help me? T_T

and i'm a newbie so i don't know about rule or like something. let me know when i'm doing something wrong.

答:
Try this :</p>

```<code>rewrite /(.*)$ /$1.txt last;
</code>```

Title: Redirect url without changing root

Body:
Try this :

rewrite /(.*)$ /$1.txt last;