问:
"java.io.FileNotFoundException (No such file or directory)"
I have a class in my project to upload an image and save in my database and if successful, save it locally. This works and I am able to save the the image in a custom folder I created on my android phone.

However, in another class, I'm trying to download an encoded image in text form and save it locally using the method i used above but it doesn't work anymore. It seems I can't create the folder.

I don't understand how it worked on my other class and not in this

I tried checking my manifest file and see if I included the needed permissions and if they are in the right places

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="buenaventura.dorothy.tbmgmtapp">

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/lungs"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        tools:replace="android:icon">
...

</code>```

[EDIT] Ok, I tried removing the whitespace in my filepath to check if the whitespace was really what was causing the problem and it still didn't work

```<code>File folder = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM) + File.separator + "TBSystem" + File.separator + patient_id + File.separator + "lab_result_" + sqlDateToString(result_date) + ".jpg");
</code>```

Also, how come it works on my other class with the whitespace and not on this one? :(

```<code>File folder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM) + File.separator + "TB System" + File.separator + patient_id);

if (!folder.exists()) {
    folder.mkdirs();
}

folder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM) + File.separator + "TB System" + File.separator + patient_id + File.separator + "lab_result_" + result_date + ".jpg");

byte[] decodedBytes = Base64.decode(encoded_image, 0);
Bitmap imageBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);

try (
    FileOutputStream out = new FileOutputStream(folder)) {
    imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (IOException e) {
    e.printStackTrace();
}

W/System.err: java.io.FileNotFoundException: /storage/emulated/0/DCIM/TB System/pat1/lab_result_2019-04-06.jpg (No such file or directory)
W/System.err:     at java.io.FileOutputStream.open0(Native Method)
        at java.io.FileOutputStream.open(FileOutputStream.java:308)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:238)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:180)
        at buenaventura.dorothy.tbmgmtapp.db_volley.VolleyDownloadRequest$1.onResponse(VolleyDownloadRequest.java:569)
        at buenaventura.dorothy.tbmgmtapp.db_volley.VolleyDownloadRequest$1.onResponse(VolleyDownloadRequest.java:103)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:6981)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

</code>```

patient_id and result_date are just strings. encoded_image is a lontext

I need to be able to convert the encoded text I downloaded to bitmap and save it in the custom folder 'TB System' I expect to find inside DCIM. Another folder should be created inside TB System (i.e pat1, pat2, pat3, ...) and the images will be saved inside these.

答:
There is a problem in your code, i have tested the combinations with Space in folder & also with exact file name it is working. Working code snippet based on your problem is as below,

Image Downloaded Successfully Snapshot

Code Layout View

build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.zackdawood.albummanager"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

strings.xml

```<code><resources>
    <string name="app_name">AlbumManager</string>
    <string name="write_button">Write Image</string>
    <string name="read_button">Read Image</string>
    <string name="request_access">Request Access</string>
</resources>
</code>```

external_files.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>
</code>```

network_security_config.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">maven.apache.org</domain>
    <domain includeSubdomains="true">upload.wikimedia.org</domain>
</domain-config>
</network-security-config>
</code>```

GenericFileProvider.java

```<code>package com.zackdawood.albummanager;

import android.support.v4.content.FileProvider;

public class GenericFileProvider extends FileProvider {
}
</code>```

FileDownloader.java

```<code>package com.zackdawood.albummanager;

import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {

    private static final String TAG = "FileDownloader";

    private static final int MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory) {
        try {
            Log.v(TAG, "downloadFile() invoked ");
            Log.v(TAG, "downloadFile() fileUrl " + fileUrl);
            Log.v(TAG, "downloadFile() directory " + directory);

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
            Log.v(TAG, "downloadFile() completed ");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        }
    }
}
</code>```

MainActivity.java

```<code>package com.zackdawood.albummanager;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.INTERNET};

    private static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);
        Log.v(TAG, "onCreate() Method invoked ");
    }

    public void write(View view) {
        if (!hasPermissions(MainActivity.this, PERMISSIONS)) {

            Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");

            Toast t = Toast.makeText(getApplicationContext(), "You don't have write access !", Toast.LENGTH_LONG);
            t.show();

        } else {

            new DownloadFile().execute("https://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/Adler.jpg/547px-Adler.jpg", "lab_result_2019-04-06.jpg");

        }
    }

    public void read(View view) {
        if (!hasPermissions(MainActivity.this, PERMISSIONS)) {

            Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");

            Toast t = Toast.makeText(getApplicationContext(), "You don't have read access !", Toast.LENGTH_LONG);
            t.show();

        } else {

            File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

            File directory = new File(folder + "/TB System");
            File imgFile = new File(directory, "lab_result_2019-04-06.jpg");

            Log.v(TAG, "view() Method imgfile " + imgFile.getAbsolutePath());

            Uri path = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", imgFile);

            Log.v(TAG, "view() Method path " + path);

            Intent imageIntent = new Intent(Intent.ACTION_VIEW);
            imageIntent.setDataAndType(path, "image/*");
            imageIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            imageIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            try {
                startActivity(imageIntent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(MainActivity.this, "No Application available to view Image", Toast.LENGTH_SHORT).show();
            }

        }
    }

    public void request(View view) {
        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);

    }

    private class DownloadFile extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... strings) {
            Log.v(TAG, "doInBackground() Method invoked ");

            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

            File directory = new File(folder + "/TB System");
            if (!directory.exists()) {
                directory.mkdir();
                Log.v(TAG, "doInBackground() Method Directory Created ");

            }

            File imgFile = new File(directory, fileName);
            Log.v(TAG, "doInBackground() imgFile invoked " + imgFile.getAbsolutePath());
            Log.v(TAG, "doInBackground() imgFile invoked " + imgFile.getAbsoluteFile());

            try {
                imgFile.createNewFile();
                Log.v(TAG, "doInBackground() file created" + imgFile);

            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "doInBackground() error" + e.getMessage());
                Log.e(TAG, "doInBackground() error" + e.getStackTrace());

            }
            FileDownloader.downloadFile(fileUrl, imgFile);
            Log.v(TAG, "doInBackground() file download completed");

            return null;
        }
    }

}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="395dp"
        android:layout_height="715dp"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/write_button"
            android:onClick="write"/>

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/read_button"
            android:onClick="read"/>

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/request_access"
            android:onClick="request"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zackdawood.albummanager">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:networkSecurityConfig="@xml/network_security_config">
        <provider
            android:name=".GenericFileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/external_files"/>
        </provider>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

App Launcher Screen

Read Image Output

Body:
I have a class in my project to upload an image and save in my database and if successful, save it locally. This works and I am able to save the the image in a custom folder I created on my android phone.

However, in another class, I'm trying to download an encoded image in text form and save it locally using the method i used above but it doesn't work anymore. It seems I can't create the folder.

I don't understand how it worked on my other class and not in this

I tried checking my manifest file and see if I included the needed permissions and if they are in the right places

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="buenaventura.dorothy.tbmgmtapp">

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/lungs"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        tools:replace="android:icon">
...

[EDIT] Ok, I tried removing the whitespace in my filepath to check if the whitespace was really what was causing the problem and it still didn't work

File folder = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM) + File.separator + "TBSystem" + File.separator + patient_id + File.separator + "lab_result_" + sqlDateToString(result_date) + ".jpg");

Also, how come it works on my other class with the whitespace and not on this one? :(

File folder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM) + File.separator + "TB System" + File.separator + patient_id);

if (!folder.exists()) {
    folder.mkdirs();
}

folder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM) + File.separator + "TB System" + File.separator + patient_id + File.separator + "lab_result_" + result_date + ".jpg");

byte[] decodedBytes = Base64.decode(encoded_image, 0);
Bitmap imageBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);

try (
    FileOutputStream out = new FileOutputStream(folder)) {
    imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (IOException e) {
    e.printStackTrace();
}

W/System.err: java.io.FileNotFoundException: /storage/emulated/0/DCIM/TB System/pat1/lab_result_2019-04-06.jpg (No such file or directory)
W/System.err:     at java.io.FileOutputStream.open0(Native Method)
        at java.io.FileOutputStream.open(FileOutputStream.java:308)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:238)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:180)
        at buenaventura.dorothy.tbmgmtapp.db_volley.VolleyDownloadRequest$1.onResponse(VolleyDownloadRequest.java:569)
        at buenaventura.dorothy.tbmgmtapp.db_volley.VolleyDownloadRequest$1.onResponse(VolleyDownloadRequest.java:103)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:6981)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

patient_id and result_date are just strings. encoded_image is a lontext

I need to be able to convert the encoded text I downloaded to bitmap and save it in the custom folder 'TB System' I expect to find inside DCIM. Another folder should be created inside TB System (i.e pat1, pat2, pat3, ...) and the images will be saved inside these.

Body:
There is a problem in your code, i have tested the combinations with Space in folder & also with exact file name it is working. Working code snippet based on your problem is as below,

Image Downloaded Successfully Snapshot

Code Layout View

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.zackdawood.albummanager"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

strings.xml

<resources>
    <string name="app_name">AlbumManager</string>
    <string name="write_button">Write Image</string>
    <string name="read_button">Read Image</string>
    <string name="request_access">Request Access</string>
</resources>

external_files.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">maven.apache.org</domain>
    <domain includeSubdomains="true">upload.wikimedia.org</domain>
</domain-config>
</network-security-config>

GenericFileProvider.java

package com.zackdawood.albummanager;

import android.support.v4.content.FileProvider;

public class GenericFileProvider extends FileProvider {
}

FileDownloader.java

package com.zackdawood.albummanager;

import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {

    private static final String TAG = "FileDownloader";

    private static final int MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory) {
        try {
            Log.v(TAG, "downloadFile() invoked ");
            Log.v(TAG, "downloadFile() fileUrl " + fileUrl);
            Log.v(TAG, "downloadFile() directory " + directory);

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
            Log.v(TAG, "downloadFile() completed ");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        }
    }
}

MainActivity.java

package com.zackdawood.albummanager;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.INTERNET};

    private static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);
        Log.v(TAG, "onCreate() Method invoked ");
    }

    public void write(View view) {
        if (!hasPermissions(MainActivity.this, PERMISSIONS)) {

            Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");

            Toast t = Toast.makeText(getApplicationContext(), "You don't have write access !", Toast.LENGTH_LONG);
            t.show();

        } else {

            new DownloadFile().execute("https://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/Adler.jpg/547px-Adler.jpg", "lab_result_2019-04-06.jpg");

        }
    }

    public void read(View view) {
        if (!hasPermissions(MainActivity.this, PERMISSIONS)) {

            Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");

            Toast t = Toast.makeText(getApplicationContext(), "You don't have read access !", Toast.LENGTH_LONG);
            t.show();

        } else {

            File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

            File directory = new File(folder + "/TB System");
            File imgFile = new File(directory, "lab_result_2019-04-06.jpg");

            Log.v(TAG, "view() Method imgfile " + imgFile.getAbsolutePath());

            Uri path = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", imgFile);

            Log.v(TAG, "view() Method path " + path);

            Intent imageIntent = new Intent(Intent.ACTION_VIEW);
            imageIntent.setDataAndType(path, "image/*");
            imageIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            imageIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            try {
                startActivity(imageIntent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(MainActivity.this, "No Application available to view Image", Toast.LENGTH_SHORT).show();
            }

        }
    }

    public void request(View view) {
        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);

    }

    private class DownloadFile extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... strings) {
            Log.v(TAG, "doInBackground() Method invoked ");

            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

            File directory = new File(folder + "/TB System");
            if (!directory.exists()) {
                directory.mkdir();
                Log.v(TAG, "doInBackground() Method Directory Created ");

            }

            File imgFile = new File(directory, fileName);
            Log.v(TAG, "doInBackground() imgFile invoked " + imgFile.getAbsolutePath());
            Log.v(TAG, "doInBackground() imgFile invoked " + imgFile.getAbsoluteFile());

            try {
                imgFile.createNewFile();
                Log.v(TAG, "doInBackground() file created" + imgFile);

            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "doInBackground() error" + e.getMessage());
                Log.e(TAG, "doInBackground() error" + e.getStackTrace());

            }
            FileDownloader.downloadFile(fileUrl, imgFile);
            Log.v(TAG, "doInBackground() file download completed");

            return null;
        }
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="395dp"
        android:layout_height="715dp"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/write_button"
            android:onClick="write"/>

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/read_button"
            android:onClick="read"/>

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/request_access"
            android:onClick="request"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zackdawood.albummanager">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:networkSecurityConfig="@xml/network_security_config">
        <provider
            android:name=".GenericFileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/external_files"/>
        </provider>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

App Launcher Screen

Read Image Output


来源: stackexchange

问:
tkinter.TclError: no display name and no $DISPLAY environment variable python
I want to execute my python file in a remote system using ssh. I exported the file to the remote system.

Here's the sample file:

```<code>import os
import time
import pymsgbox

pymsgbox.alert('Hi Afreeth ', 'Welcome')
if 'DISPLAY' not in os.environ:
    pass
</code>```

I want to execute it using ssh from my system and it should display in the remote system.
But it fails

Error i got:

```<code>Traceback (most recent call last):
  File "cd1.py", line 5, in <module>
  File "pymsgbox/__init__.py", line 100, in alert
  File "pymsgbox/__init__.py", line 156, in _buttonbox
  File "tkinter/__init__.py", line 1871, in __init__
_tkinter.TclError: no display name and no $DISPLAY environment variable
[12113] Failed to execute script myprogram
</code>```

How to fix it. I found some answers on stack but it doesn't solve me. If i go and execute it in the remote system, it works. But when i execute from my system,it fails. How to fix it.

答:
Found the Answer:
I just need to run export DISPLAY=:0 in their ssh session and programs run will run on the remote display. A quick example:

```<code>paulsteven@smackcoders:~$ ssh afreeth@his_ipaddress
afreeth@smackcoders:~$ export DISPLAY=:0
afreeth@smackcoders:~$ firefox
Firefox is now running on afreeth's display.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to execute my python file in a remote system using ssh. I exported the file to the remote system.

Here's the sample file:

import os
import time
import pymsgbox

pymsgbox.alert('Hi Afreeth ', 'Welcome')
if 'DISPLAY' not in os.environ:
    pass

I want to execute it using ssh from my system and it should display in the remote system.
But it fails

Error i got:

Traceback (most recent call last):
  File "cd1.py", line 5, in <module>
  File "pymsgbox/__init__.py", line 100, in alert
  File "pymsgbox/__init__.py", line 156, in _buttonbox
  File "tkinter/__init__.py", line 1871, in __init__
_tkinter.TclError: no display name and no $DISPLAY environment variable
[12113] Failed to execute script myprogram

How to fix it. I found some answers on stack but it doesn't solve me. If i go and execute it in the remote system, it works. But when i execute from my system,it fails. How to fix it.

Body:
Found the Answer:
I just need to run export DISPLAY=:0 in their ssh session and programs run will run on the remote display. A quick example:

paulsteven@smackcoders:~$ ssh afreeth@his_ipaddress
afreeth@smackcoders:~$ export DISPLAY=:0
afreeth@smackcoders:~$ firefox
Firefox is now running on afreeth's display.


问:
making map coordinates(lan,& long)storing in sqlite database
how to created an application that records a series of longitude and latitude values in a SQLite database and display them as a coloured track on a MapActivity.

I need help. How can store the map coordinates in sqlite database  and display like journey details in table .For example I have done one journey from  mumbai to Pune .Then how can store the data into database that can available for future reference .when user click on journey name  it should give all details

答:
If you are new to Sqlite Then look into this class for data base
Create two database file as the following

---->>>>
Database.h

Write the following code in this file

```<code>#import <Foundation/Foundation.h>
#import <sqlite3.h>

@interface DataBase : NSObject {

    sqlite3 *database;

}

+(DataBase *) shareDataBase;

-(BOOL) createDataBase:(NSString *)DataBaseName;

-(NSString*) GetDatabasePath:(NSString *)database;

-(NSMutableArray *) getAllDataForQuery:(NSString *)sql  forDatabase:(NSString *)database;
-(void) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1;
-(void) deleteQuery:(NSString *) deleteSql forDatabase:(NSString *)database1;
-(void) updateQuery:(NSString *) updateSql forDatabase:(NSString *)database1;

@end
</code>```

---->>>>
    Database.m

Write the following code in this file

```<code>#import "DataBase.h"

@implementation DataBase

static DataBase *SampleDataBase =nil;

+(DataBase*) shareDataBase{

    if(!SampleDataBase){
        SampleDataBase = [[DataBase alloc] init];
    }

    return SampleDataBase;

}

-(NSString *) GetDatabasePath:(NSString *)database1{

    [self createDataBase:database1];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:database1];
}

-(BOOL) createDataBase:(NSString *)DataBaseName{
    BOOL success;

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DataBaseName];

    success = [fileManager fileExistsAtPath:writableDBPath];
    if (success) return success;
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DataBaseName];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];

    if (!success) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!!!" message:@"Failed to create writable database" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
        [alert show];
        [alert release];

    }
    return success;
}

-(NSMutableArray *) getAllDataForQuery:(NSString *)sql  forDatabase:(NSString *)database1{

    sqlite3_stmt *statement = nil ;

    NSString *path = [self GetDatabasePath:database1];

    NSMutableArray *alldata;
    alldata = [[NSMutableArray alloc] init];

    if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
    {
        NSString *query = sql;

        if((sqlite3_prepare_v2(database,[query UTF8String],-1, &statement, NULL)) == SQLITE_OK)
        {
            while(sqlite3_step(statement) == SQLITE_ROW)
            {

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

                int count = sqlite3_column_count(statement);

                for (int i=0; i < count; i++) {

                    char *name = (char*) sqlite3_column_name(statement, i);
                    char *data = (char*) sqlite3_column_text(statement, i);

                    NSString *columnData;
                    NSString *columnName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];

                    if(data != nil)
                        columnData = [NSString stringWithCString:data encoding:NSUTF8StringEncoding];
                    else {
                        columnData = @"";
                    }

                    [currentRow setObject:columnData forKey:columnName];
                }

                [alldata addObject:currentRow];
            }
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(database);

    return alldata;

}

-(void) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1{

    sqlite3_stmt *statement = nil ;

    NSString *path = [self GetDatabasePath:database1];

    if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
    {
        if((sqlite3_prepare_v2(database,[insertSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
        {
            if(sqlite3_step(statement) == SQLITE_OK){
            }
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(database);

}

-(void) updateQuery:(NSString *) updateSql forDatabase:(NSString *)database1{

    sqlite3_stmt *statement = nil ;

    NSString *path = [self GetDatabasePath:database1];

    if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
    {
        if((sqlite3_prepare_v2(database,[updateSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
        {
            if(sqlite3_step(statement) == SQLITE_OK){
            }
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(database);

}

-(void) deleteQuery:(NSString *) deleteSql forDatabase:(NSString *)database1{

    sqlite3_stmt *statement = nil ;

    NSString *path = [self GetDatabasePath:database1];

    if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
    {
        if((sqlite3_prepare_v2(database,[deleteSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
        {
            if(sqlite3_step(statement) == SQLITE_OK){
            }
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(database);

}

@end
</code>```

Now to get data use the following code

```<code>NSString *sql = @"select * from UserInfo"; <br>
userInfo = [[DataBase shareDataBase] getAllDataForQuery:sql forDatabase:@"Sample.db"];
</code>```

It will return array of all the row in form of NSDictionary.

To add new record use the following code

```<code>NSString *sql = [NSString stringWithFormat:@"insert into userInfo values ('city','name','phone')"];
[[DataBase shareDataBase] inseryQuery:sql forDatabase:@"Sample.db"];
</code>```

In the same way there is also method to update and delete record.

so This is the best example I have seen we just need to call one method to for fetch, insert , update or delete.

Thanks for seeing the question,

ContentLicense: CC BY-SA 3.0

Body:
If you are new to Sqlite Then look into this class for data base
Create two database file as the following

---->>>>
Database.h

Write the following code in this file

#import <Foundation/Foundation.h>
#import <sqlite3.h>

@interface DataBase : NSObject {

    sqlite3 *database;

}

+(DataBase *) shareDataBase;

-(BOOL) createDataBase:(NSString *)DataBaseName;

-(NSString*) GetDatabasePath:(NSString *)database;

-(NSMutableArray *) getAllDataForQuery:(NSString *)sql  forDatabase:(NSString *)database;
-(void) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1;
-(void) deleteQuery:(NSString *) deleteSql forDatabase:(NSString *)database1;
-(void) updateQuery:(NSString *) updateSql forDatabase:(NSString *)database1;

@end

---->>>>
    Database.m

Write the following code in this file

#import "DataBase.h"

@implementation DataBase

static DataBase *SampleDataBase =nil;

+(DataBase*) shareDataBase{

    if(!SampleDataBase){
        SampleDataBase = [[DataBase alloc] init];
    }

    return SampleDataBase;

}

-(NSString *) GetDatabasePath:(NSString *)database1{

    [self createDataBase:database1];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:database1];
}

-(BOOL) createDataBase:(NSString *)DataBaseName{
    BOOL success;

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DataBaseName];

    success = [fileManager fileExistsAtPath:writableDBPath];
    if (success) return success;
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DataBaseName];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];

    if (!success) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!!!" message:@"Failed to create writable database" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
        [alert show];
        [alert release];

    }
    return success;
}

-(NSMutableArray *) getAllDataForQuery:(NSString *)sql  forDatabase:(NSString *)database1{

    sqlite3_stmt *statement = nil ;

    NSString *path = [self GetDatabasePath:database1];

    NSMutableArray *alldata;
    alldata = [[NSMutableArray alloc] init];

    if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
    {
        NSString *query = sql;

        if((sqlite3_prepare_v2(database,[query UTF8String],-1, &statement, NULL)) == SQLITE_OK)
        {
            while(sqlite3_step(statement) == SQLITE_ROW)
            {

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

                int count = sqlite3_column_count(statement);

                for (int i=0; i < count; i++) {

                    char *name = (char*) sqlite3_column_name(statement, i);
                    char *data = (char*) sqlite3_column_text(statement, i);

                    NSString *columnData;
                    NSString *columnName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];

                    if(data != nil)
                        columnData = [NSString stringWithCString:data encoding:NSUTF8StringEncoding];
                    else {
                        columnData = @"";
                    }

                    [currentRow setObject:columnData forKey:columnName];
                }

                [alldata addObject:currentRow];
            }
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(database);

    return alldata;

}

-(void) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1{

    sqlite3_stmt *statement = nil ;

    NSString *path = [self GetDatabasePath:database1];

    if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
    {
        if((sqlite3_prepare_v2(database,[insertSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
        {
            if(sqlite3_step(statement) == SQLITE_OK){
            }
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(database);

}

-(void) updateQuery:(NSString *) updateSql forDatabase:(NSString *)database1{

    sqlite3_stmt *statement = nil ;

    NSString *path = [self GetDatabasePath:database1];

    if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
    {
        if((sqlite3_prepare_v2(database,[updateSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
        {
            if(sqlite3_step(statement) == SQLITE_OK){
            }
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(database);

}

-(void) deleteQuery:(NSString *) deleteSql forDatabase:(NSString *)database1{

    sqlite3_stmt *statement = nil ;

    NSString *path = [self GetDatabasePath:database1];

    if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
    {
        if((sqlite3_prepare_v2(database,[deleteSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
        {
            if(sqlite3_step(statement) == SQLITE_OK){
            }
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(database);

}

@end

Now to get data use the following code

NSString *sql = @"select * from UserInfo"; <br>
userInfo = [[DataBase shareDataBase] getAllDataForQuery:sql forDatabase:@"Sample.db"];

It will return array of all the row in form of NSDictionary.

To add new record use the following code

NSString *sql = [NSString stringWithFormat:@"insert into userInfo values ('city','name','phone')"];
[[DataBase shareDataBase] inseryQuery:sql forDatabase:@"Sample.db"];

In the same way there is also method to update and delete record.

so This is the best example I have seen we just need to call one method to for fetch, insert , update or delete.

Thanks for seeing the question,


问:
WPF validation error remains until control loses focus
I got a text box on which I added a validation rule in the xaml. The rule works and it detects errors, but only after the user gives the focus to some other element in the window, like another text box.

This is the defintion:

```<code><TextBox x:Name="textBoxLongitude" Grid.Row="1" Grid.Column="1" Margin="0,0,0,10" VerticalContentAlignment="Center">
        <TextBox.Text>
            <Binding Path="CustomerLongitude">
                <Binding.ValidationRules>
                    <local:IsDoubleValidationRule MaxValue ="180"/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
</code>```

I've tried solving the issue by adding this to the xaml of the text box:

```<code>TextChanged="textBoxTextChanged"
</code>```

And the implementation:

```<code>private void textBoxTextChanged(object sender, TextChangedEventArgs e)
{
     CommandManager.InvalidateRequerySuggested();
}
</code>```

It didn't help..

How can I make the validation rule detect the error and when it's fixed even without the user needing to give the focus to another control?

答:
Set the binding's UpdateSourceTrigger to PropertyChanged to commit and re-evaluate a bound value on every change instead of LostFocus.

Bindings that are TwoWay or OneWayToSource listen for changes in the target property and propagate them back to the source. This is known as updating the source. Usually, these updates happen whenever the target property changes. This is fine for check boxes and other simple controls, but it is usually not appropriate for text fields. Updating after every keystroke can diminish performance and it denies the user the usual opportunity to backspace and fix typing errors before committing to the new value. Therefore, the default UpdateSourceTrigger value of the Text property is LostFocus and not PropertyChanged.

This is how to do it: <Binding Path="CustomerLongitude" UpdateSourceTrigger="PropertyChanged">

Body:
I got a text box on which I added a validation rule in the xaml. The rule works and it detects errors, but only after the user gives the focus to some other element in the window, like another text box.

This is the defintion:

<TextBox x:Name="textBoxLongitude" Grid.Row="1" Grid.Column="1" Margin="0,0,0,10" VerticalContentAlignment="Center">
        <TextBox.Text>
            <Binding Path="CustomerLongitude">
                <Binding.ValidationRules>
                    <local:IsDoubleValidationRule MaxValue ="180"/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

I've tried solving the issue by adding this to the xaml of the text box:

TextChanged="textBoxTextChanged"

And the implementation:

private void textBoxTextChanged(object sender, TextChangedEventArgs e)
{
     CommandManager.InvalidateRequerySuggested();
}

It didn't help..

How can I make the validation rule detect the error and when it's fixed even without the user needing to give the focus to another control?


问:
POST large json string from Javascript to Django
I have a small cordova (phonegap) mobile app with simple form. I need select a file, fill other fields and save form. Then I want to send this data later.

How I save my form data:

form fields in localStorage as json string of serialized array, and file in LocalFileSystem as reader.readAsText() in file (just file with base64 string).

How I send data to server:

I push base64 string to my serialized array and make an ajax post to server stringified data.

My problem:

I cant send large json string (when file > 2 MB) to my server, I get an error: code 414, message Request-URI Too Long.

How can I fix that?

答:
The problem was in Django settings!

DATA_UPLOAD_MAX_MEMORY_SIZE - by default it is 2.5 MB (2621440).

DATA_UPLOAD_MAX_MEMORY_SIZE = 26214400 solved my problem (25MB)


问:
Arrays difference and elements partially equal
I would like to compare two arrays excluding elements partially equal.

I have reached the following result:

```<code>1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
21 22 23 24 25
</code>```

The desired result is:

```<code>21 22 23 24 25
</code>```

Attempt:

```<code>$aa = array("1 2 3 4 5", "6 7 8 9 10", "11 12 13 14 15", "16 17 18 19 20", "21 22 23 24 25");
$bb = array("1 2", "6 7 8", "11 12 13 14", "16 17 18 19 20");
$final = array_diff($aa, $bb);
print_r($final)
</code>```

答:
You can use preg_grep in order to not have to do any manipulation the the data.

This will regex to see what is matching and then you just use array_diff.

```<code>$aa = array("1 2 3 4 5", "6 7 8 9 10", "11 12 13 14 15", "16 17 18 19 20", "21 22 23 24 25");
$bb = array("1 2", "6 7 8", "11 12 13 14", "16 17 18 19 20");

$exclude = [];
foreach($bb as $b){
    $exclude = array_merge($exclude, preg_grep("/^". preg_quote($b) . "/", $aa));
}
$final = array_diff($aa, $exclude);

print_r($final);
</code>```

https://3v4l.org/XI9Jd

Body:
I would like to compare two arrays excluding elements partially equal.

I have reached the following result:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
21 22 23 24 25

The desired result is:

21 22 23 24 25

Attempt:

$aa = array("1 2 3 4 5", "6 7 8 9 10", "11 12 13 14 15", "16 17 18 19 20", "21 22 23 24 25");
$bb = array("1 2", "6 7 8", "11 12 13 14", "16 17 18 19 20");
$final = array_diff($aa, $bb);
print_r($final)

Body:
You can use preg_grep in order to not have to do any manipulation the the data.

This will regex to see what is matching and then you just use array_diff.

$aa = array("1 2 3 4 5", "6 7 8 9 10", "11 12 13 14 15", "16 17 18 19 20", "21 22 23 24 25");
$bb = array("1 2", "6 7 8", "11 12 13 14", "16 17 18 19 20");

$exclude = [];
foreach($bb as $b){
    $exclude = array_merge($exclude, preg_grep("/^". preg_quote($b) . "/", $aa));
}
$final = array_diff($aa, $exclude);

print_r($final);

https://3v4l.org/XI9Jd


问:
how to get the unique max data
I have below table

```<code>userid      comp_dd     coursecode  qualification   course_id   course      passyear    totalmarks             func        stream
----------- ----------- ----------- --------------- ----------- -------------------------------------------------- ----------- -----------------
60          26          1           High School     15          Class 10     26          67                     2           All Subject
60          26          2           Senior Secondry 15          Class 12     26          85                     2           Commerce
60          2010        3           Graduates       4           B.Tech/B.E   2010        54                     1           IT/Computers
60          2013        4            Post Graduates 9           M.com        2013        98.5                   2           Commerce
</code>```

i wanted to get the unique record of max coursecode, the output should be

```<code>userid      comp_dd     coursecode  qualification   course_id   course      passyear    totalmarks             func        stream
----------- ----------- ----------- --------------- ----------- -------------------------------------------------- ----------- -----------------
60          2013        4            Post Graduates 9           M.com        2013        98.5                   2           Commerce
</code>```

There will be many records of the different userids

答:
Sort the table by coursecode descending and get the 1st row:

```<code>select top 1 *
from tablename
order by coursecode desc
</code>```

This will work only if there are no duplicates in the column coursecode since it will fetch only 1 row, but I guess this is the case because you say:

i wanted to get the unique record of max coursecode

Title: how to get the unique max data

Body:
I have below table

userid      comp_dd     coursecode  qualification   course_id   course      passyear    totalmarks             func        stream
----------- ----------- ----------- --------------- ----------- -------------------------------------------------- ----------- -----------------
60          26          1           High School     15          Class 10     26          67                     2           All Subject
60          26          2           Senior Secondry 15          Class 12     26          85                     2           Commerce
60          2010        3           Graduates       4           B.Tech/B.E   2010        54                     1           IT/Computers
60          2013        4            Post Graduates 9           M.com        2013        98.5                   2           Commerce

i wanted to get the unique record of max coursecode, the output should be

userid      comp_dd     coursecode  qualification   course_id   course      passyear    totalmarks             func        stream
----------- ----------- ----------- --------------- ----------- -------------------------------------------------- ----------- -----------------
60          2013        4            Post Graduates 9           M.com        2013        98.5                   2           Commerce

There will be many records of the different userids

Body:
Sort the table by coursecode descending and get the 1st row:

select top 1 *
from tablename
order by coursecode desc

This will work only if there are no duplicates in the column coursecode since it will fetch only 1 row, but I guess this is the case because you say:

i wanted to get the unique record of max coursecode


问:
Match Substrings between Multiple Dataframes and Sum Weighted Value in Separate Column
I'm trying to categorise a list of strings called keywords based on whether they contain 1 or more substrings from another DataFrame.

The substring is weighted so that at the end each keyword has a weight in approximately 4 columns. These columns will be called loan, mortgage, accounts, and cards.

I've attempted to use join(), concat() and merge() to join multiple dataframes, as well as attempting to use where(), isin() and contains().

I've come close a few times to achieve my desired goal but thwarted either by errors or scalability. I have limited experience with Python and Pandas, so there may be a completely different approach that I've not considered.

import pandas as pd

df = pd.read_csv('Inputs/keyword.csv', header=0)
df['loan'] = 0
df2 = pd.read_csv('Essentials/Groups/loans.csv', header=0)

#review the data in df
print(df.head())

output:
           keywords  search_volume  loan
0             loans         132000     0
1    funding circle          81000     0
2        government          36000     0
3  short term loans          30000     0
4           company          27000     0
```

<p>In the above code I'm loading up my list of keywords including an associated search volume. It currently has no loan column so I've added one with the default value set to 0.</p>

<p>Below, I have another DataFrame that includes a list of terms and an associated weighting. I've arbitrarily picked an integer of 5 that I would like added to the existing total.</p>

<pre class="lang-py prettyprint-override"><code>#review the data in df2
print(df2.head())

output:
      terms  weight
0      loan       5
1     loans       5
2  personal       3
3  business       3
4       apr       4
</code>```

There is a problem that I have spotted but don't know how to resolve.

My list includes both loan and loans. It is fine for me to have these duplicates on my end. However, row 3 has a value of 'short term loans' and is marked as False.

Since the term loan and loans both appear in short term loans, I would have expected it to be marked as True. I've tried reversing the .isin() statement so that I'm searching df2['terms'] in df['keywords'], but the result came out the same.

#review the true/false for overlaps
print(df['keywords'].isin(df2['terms']).head())

output:
0     True
1    False
2    False
3    False
4    False
```

<p>Lastly, once we fix this boolean issue, I don't know how to vectorise a sum change in <code>df['loan']</code> based on matches. I'm trying to avoid for loops because I'm expecting the keyword list to include around 100,000+ rows and each category DataFrame may include 1,000 terms.</p>

<p>The desired output would look something like this:</p>

<pre class="lang-py prettyprint-override"><code>output:
           keywords  search_volume  loan  mortgage  accounts  cards
0             loans         132000     10        0         0      0
1    funding circle          81000     0         0         0      0
2        government          36000     0         0         0      0
3  short term loans          30000     10        0         0      0
4           company          27000     0         0         0      0
</code>```

答:
Considering the df1 as :

```<code>           keywords  search_volume
0             loans         132000
1    funding circle          81000
2        government          36000
3  short term loans          30000
4           company          27000
</code>```

you can take help of series.str.extract() and df.assign() we can do something like:

```<code>d=df2.set_index('terms')['weight']
pat=r'({})'.format('|'.join(df2.terms))
#'(loan|loans|personal|business|apr)'
df1=df1.assign(**{'term_match':df1.keywords.str.extract(pat,expand=False),
              'weight':df1.keywords.str.extract(pat,expand=False).map(d)})
print(df1)
</code>```

Output

```<code>           keywords  search_volume term_match  weight
0             loans         132000       loan     5.0
1    funding circle          81000        NaN     NaN
2        government          36000        NaN     NaN
3  short term loans          30000       loan     5.0
4           company          27000        NaN     NaN
</code>```

EDIT
To find all matching strings lets update df2 as: df2.loc[5]=['term',3] just for testing.

Then using series.str.findall():

```<code>s=df1.keywords.str.findall(pat)
df1=df1.assign(**{'term_match':s.apply(','.join),
              'weight':s.apply(lambda x: sum([d.get(item,item)  for item in x]))})
print(df1)
</code>```

```<code>           keywords  search_volume  loan term_match  weight
0             loans         132000     0       loan       5
1    funding circle          81000     0                  0
2        government          36000     0                  0
3  short term loans          30000     0  term,loan       8
4           company          27000     0                  0
</code>```

Body:
I'm trying to categorise a list of strings called keywords based on whether they contain 1 or more substrings from another DataFrame.

The substring is weighted so that at the end each keyword has a weight in approximately 4 columns. These columns will be called loan, mortgage, accounts, and cards.

I've attempted to use join(), concat() and merge() to join multiple dataframes, as well as attempting to use where(), isin() and contains().

I've come close a few times to achieve my desired goal but thwarted either by errors or scalability. I have limited experience with Python and Pandas, so there may be a completely different approach that I've not considered.

import pandas as pd

df = pd.read_csv('Inputs/keyword.csv', header=0)
df['loan'] = 0
df2 = pd.read_csv('Essentials/Groups/loans.csv', header=0)

#review the data in df
print(df.head())

output:
           keywords  search_volume  loan
0             loans         132000     0
1    funding circle          81000     0
2        government          36000     0
3  short term loans          30000     0
4           company          27000     0

In the above code I'm loading up my list of keywords including an associated search volume. It currently has no loan column so I've added one with the default value set to 0.

Below, I have another DataFrame that includes a list of terms and an associated weighting. I've arbitrarily picked an integer of 5 that I would like added to the existing total.

#review the data in df2
print(df2.head())

output:
      terms  weight
0      loan       5
1     loans       5
2  personal       3
3  business       3
4       apr       4

There is a problem that I have spotted but don't know how to resolve.

My list includes both loan and loans. It is fine for me to have these duplicates on my end. However, row 3 has a value of 'short term loans' and is marked as False.

Since the term loan and loans both appear in short term loans, I would have expected it to be marked as True. I've tried reversing the .isin() statement so that I'm searching df2['terms'] in df['keywords'], but the result came out the same.

#review the true/false for overlaps
print(df['keywords'].isin(df2['terms']).head())

output:
0     True
1    False
2    False
3    False
4    False

Lastly, once we fix this boolean issue, I don't know how to vectorise a sum change in df['loan'] based on matches. I'm trying to avoid for loops because I'm expecting the keyword list to include around 100,000+ rows and each category DataFrame may include 1,000 terms.

The desired output would look something like this:

output:
           keywords  search_volume  loan  mortgage  accounts  cards
0             loans         132000     10        0         0      0
1    funding circle          81000     0         0         0      0
2        government          36000     0         0         0      0
3  short term loans          30000     10        0         0      0
4           company          27000     0         0         0      0

Body:
Considering the df1 as :

           keywords  search_volume
0             loans         132000
1    funding circle          81000
2        government          36000
3  short term loans          30000
4           company          27000

you can take help of series.str.extract() and df.assign() we can do something like:

d=df2.set_index('terms')['weight']
pat=r'({})'.format('|'.join(df2.terms))
#'(loan|loans|personal|business|apr)'
df1=df1.assign(**{'term_match':df1.keywords.str.extract(pat,expand=False),
              'weight':df1.keywords.str.extract(pat,expand=False).map(d)})
print(df1)

Output

           keywords  search_volume term_match  weight
0             loans         132000       loan     5.0
1    funding circle          81000        NaN     NaN
2        government          36000        NaN     NaN
3  short term loans          30000       loan     5.0
4           company          27000        NaN     NaN

EDIT
To find all matching strings lets update df2 as: df2.loc[5]=['term',3] just for testing.

Then using series.str.findall():

s=df1.keywords.str.findall(pat)
df1=df1.assign(**{'term_match':s.apply(','.join),
              'weight':s.apply(lambda x: sum([d.get(item,item)  for item in x]))})
print(df1)

           keywords  search_volume  loan term_match  weight
0             loans         132000     0       loan       5
1    funding circle          81000     0                  0
2        government          36000     0                  0
3  short term loans          30000     0  term,loan       8
4           company          27000     0                  0


问:
How to speed up copying/creating a file many times in Google Apps Script?
So, I'm setting up student surveys in a college. There are lots of forms to be handed out to lots of groups of students. For one particular survey, I have a template google form.

What I do is a loop that on every iteration creates a copy of this template and then modifies it a little bit. It takes A LOT of time. Google is copying and modifying 220 forms for like 40-50 minutes. I found my way around the time limit put on google script, but it's still too long. Do you see any way to speed this up a little?

Now it looks schematically like this:

for(some range):{
   template.makeCopy("template", formsFolder);
   var formFile = formsFolder.getFilesByName("template").next();
   var form = FormApp.openById(formFile.getId())
//   ... do some modifications
  }```

Thank you!

答:
I am surprised that your script actually finishes and does not timeout as the maximum script run time is 30 minutes or so dependent on your edition. I have had a very similar obstacle where I needed to run a script over 200-300 different sheets and copy data. The number of calls to the API was about 3-5 per loop and then some javascript to filter that dataset before writing to a sheet.  It would regularly fail.

I found that my best approach was to leverage Triggers and rather than have 300 sheets processed at once have 100 sheets processed every 5 minutes or so. In my circumstances there really was no reason why these sheets had to be processed at the exact same time as long as my parameters for filtering was accurate.  I would control all the parameters through inputs on a sheet.

Body:
So, I'm setting up student surveys in a college. There are lots of forms to be handed out to lots of groups of students. For one particular survey, I have a template google form.

What I do is a loop that on every iteration creates a copy of this template and then modifies it a little bit. It takes A LOT of time. Google is copying and modifying 220 forms for like 40-50 minutes. I found my way around the time limit put on google script, but it's still too long. Do you see any way to speed this up a little?

Now it looks schematically like this:

for(some range):{
   template.makeCopy("template", formsFolder);
   var formFile = formsFolder.getFilesByName("template").next();
   var form = FormApp.openById(formFile.getId())
//   ... do some modifications
  }

Thank you!


问:
Calling a Range (as a variable) in a different Worksheet
So, I have set a Range as a variable

```<code>Set Range_Count = Range("A2", Range("A2").End(xlDown))
</code>```

And now I'm trying to call it in a WorksheetFunction using VBA without needing to select the worksheet

```<code>'This is what I don't want to do anymore
Sheets(1).Select
Count_Product = Application.WorksheetFunction.CountIf(Range_Count, "<>")

'This is what I'm wondering if it's possible to be done
Count_Product = Application.WokrsheetFunction.CountIf(Sheets(2).Range_Count, "<>")
</code>```

But It doesn't seem to work. Is there a way to do this?

答:
So, I just solved it by putting the sheets before Application like this

```<code>Dim Range_Count As Range
Set Range_Count = Range("A2", Range("A2").End(xlDown))

Sheets(2).Application.WorksheetFunction.CountIf(Range_Count, "<>")
</code>```

Easier than I thought

Body:
So, I have set a Range as a variable

Set Range_Count = Range("A2", Range("A2").End(xlDown))

And now I'm trying to call it in a WorksheetFunction using VBA without needing to select the worksheet

'This is what I don't want to do anymore
Sheets(1).Select
Count_Product = Application.WorksheetFunction.CountIf(Range_Count, "<>")

'This is what I'm wondering if it's possible to be done
Count_Product = Application.WokrsheetFunction.CountIf(Sheets(2).Range_Count, "<>")

But It doesn't seem to work. Is there a way to do this?

Body:
So, I just solved it by putting the sheets before Application like this

Dim Range_Count As Range
Set Range_Count = Range("A2", Range("A2").End(xlDown))

Sheets(2).Application.WorksheetFunction.CountIf(Range_Count, "<>")

Easier than I thought


问:
convert nested object into recursive array or nested array in javascript es6
I worked nested object which I want to convert into recursive array or nested array.

I tried iterate the object something like below but it was creating single object of array.

Can anyone give suggestions or share your ideas it will helpful for me

```<code>        iterate(obj) {
                for (let property in obj) {
                  this.configArray.push({key: property,children: [], isValue: false, value: ''});
                    if (obj.hasOwnProperty(property)) {
                      const index = Object.keys(obj).indexOf(property);
                        if (typeof obj[property] == "object") {
                            this.iterate(obj[property]);
                        }
                        else {
                            this.configArray[index].children.push({ key: property, value: obj[property], isValue: true, children: [] });
                        }
                    }
                }
            }
</code>```

INPUT

```<code>{
"Parent 1": {
    "11": "Child 1",
    "12": "Child 2",
},
"Parent 2": {
    "20": {
        "21": "Grand Child 1",
        "22": "Grand Child 2",
    }
},
"Parent 3": {
    "31": "Child 1",
    "32": "Child 2",
}
</code>```

}

OUTPUT

```<code>  [
{
    key: "Parent 1",
    value: "",
    children: [
        { key: 11, value: "Child 1", children: [] },
        { key: 12, value: "Child 2", children: [] }
    ]
},
{
    key: "Parent 2",
    value: "",
    children: [
        {
            key: 20,
            value: "",
            children: [
                { key: 21, value: "Grand Child 1", children: [] },
                { key: 22, value: "Grand Child 2", children: [] }
            ]
        }
    ]
},
{
    key: "Parent 3",
    value: "",
    children: [
        { key: 31, value: "Child 1", children: [] },
        { key: 32, value: "Child 2", children: [] }
    ]
},
];
</code>```

答:
You could take a recursive approach and map the value or the children, if value is an object.

function transform(object) {
    return Object
        .entries(object)
        .map(([key, value]) => Object.assign({ key }, value && typeof value === 'object'
            ? { value: '', children: transform(value) }
            : { value, children: [] }
        ));
}

var data = { "Parent 1": { 11: "Child 1", 12: "Child 2" }, "Parent 2": { 20: { 21: "Grand Child 1", 22: "Grand Child 2" } }, "Parent 3": { 31: "Child 1", 32: "Child 2" } },
    result = transform(data);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I worked nested object which I want to convert into recursive array or nested array.

I tried iterate the object something like below but it was creating single object of array.

Can anyone give suggestions or share your ideas it will helpful for me

        iterate(obj) {
                for (let property in obj) {
                  this.configArray.push({key: property,children: [], isValue: false, value: ''});
                    if (obj.hasOwnProperty(property)) {
                      const index = Object.keys(obj).indexOf(property);
                        if (typeof obj[property] == "object") {
                            this.iterate(obj[property]);
                        }
                        else {
                            this.configArray[index].children.push({ key: property, value: obj[property], isValue: true, children: [] });
                        }
                    }
                }
            }

INPUT

{
"Parent 1": {
    "11": "Child 1",
    "12": "Child 2",
},
"Parent 2": {
    "20": {
        "21": "Grand Child 1",
        "22": "Grand Child 2",
    }
},
"Parent 3": {
    "31": "Child 1",
    "32": "Child 2",
}

}

OUTPUT

  [
{
    key: "Parent 1",
    value: "",
    children: [
        { key: 11, value: "Child 1", children: [] },
        { key: 12, value: "Child 2", children: [] }
    ]
},
{
    key: "Parent 2",
    value: "",
    children: [
        {
            key: 20,
            value: "",
            children: [
                { key: 21, value: "Grand Child 1", children: [] },
                { key: 22, value: "Grand Child 2", children: [] }
            ]
        }
    ]
},
{
    key: "Parent 3",
    value: "",
    children: [
        { key: 31, value: "Child 1", children: [] },
        { key: 32, value: "Child 2", children: [] }
    ]
},
];

Body:
You could take a recursive approach and map the value or the children, if value is an object.

function transform(object) {
    return Object
        .entries(object)
        .map(([key, value]) => Object.assign({ key }, value && typeof value === 'object'
            ? { value: '', children: transform(value) }
            : { value, children: [] }
        ));
}

var data = { "Parent 1": { 11: "Child 1", 12: "Child 2" }, "Parent 2": { 20: { 21: "Grand Child 1", 22: "Grand Child 2" } }, "Parent 3": { 31: "Child 1", 32: "Child 2" } },
    result = transform(data);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
invalidate only works in custom view
so i created a view called "drawable view"

```<code> class DrawableView extends View{
        Context mContext;

        int touches=0,k,Xoffs,clicks=0;

  double x_1 = 0,x_2=0;

        private float mLastTouchX, mLastTouchY;

        public DrawableView(Context context) {
        super(context);
        mContext = context;
        }

....
    @Override
    protected void onDraw(Canvas canvas){

        Paint myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

canvas.drawColor(Color.BLUE);
myPaint.setColor(Color.WHITE);

canvas.drawCircle(200, 100, 20, myPaint);

    }

..... more code....

}
</code>```

and it can only be invalidated within the ondraw command! ie: calling "invalidate();" at the end of the ondraw command causes it to loop.

I have tried many times to call g_draw.invalidate(); or g_draw.postInvalidate(); (g_draw is the name of the created Drawable View)from other classes and even the main activity class and it doesnt work. why and how can i fix it?

thanks

答:
You may want to call invalidate() somewhere in your DrawableView class. For example, if you want your view to redraw itself after any touch event, you would do something like this:

```<code>public boolean onTouchEvent( MotionEvent event) {

    if(event.getAction() == MotionEvent.ACTION_UP){
        invalidate();
    }
}
</code>```

This is how I draw the movable pieces in my puzzle game.

Title: invalidate only works in custom view

Body:
so i created a view called "drawable view"

 class DrawableView extends View{
        Context mContext;

        int touches=0,k,Xoffs,clicks=0;

  double x_1 = 0,x_2=0;

        private float mLastTouchX, mLastTouchY;

        public DrawableView(Context context) {
        super(context);
        mContext = context;
        }

....
    @Override
    protected void onDraw(Canvas canvas){

        Paint myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

canvas.drawColor(Color.BLUE);
myPaint.setColor(Color.WHITE);

canvas.drawCircle(200, 100, 20, myPaint);

    }

..... more code....

}

and it can only be invalidated within the ondraw command! ie: calling "invalidate();" at the end of the ondraw command causes it to loop.

I have tried many times to call g_draw.invalidate(); or g_draw.postInvalidate(); (g_draw is the name of the created Drawable View)from other classes and even the main activity class and it doesnt work. why and how can i fix it?

thanks

Body:
You may want to call invalidate() somewhere in your DrawableView class. For example, if you want your view to redraw itself after any touch event, you would do something like this:

public boolean onTouchEvent( MotionEvent event) {

    if(event.getAction() == MotionEvent.ACTION_UP){
        invalidate();
    }
}

This is how I draw the movable pieces in my puzzle game.


问:
ArgumentException: Requested value 'X86' was not found
i try to import GoogleMobileAds sdk to unity. when i import PlayServicesResolver package, i am getting error on console like this 'ArgumentException: Requested value 'X86' was not found.' I cant figure out why?

ArgumentException: Requested value 'X86' was not found.
  System.Enum+EnumResult.SetFailure (System.Enum+ParseFailureKind failure, System.String failureMessageID, System.Object failureMessageFormatArgument) (at <23c160f925be47d7a4fd083a3a62c920>:0)
  System.Enum.TryParseEnum (System.Type enumType, System.String value, System.Boolean ignoreCase, System.Enum+EnumResult& parseResult) (at <23c160f925be47d7a4fd083a3a62c920>:0)
  System.Enum.Parse (System.Type enumType, System.String value, System.Boolean ignoreCase) (at <23c160f925be47d7a4fd083a3a62c920>:0)
  System.Enum.Parse (System.Type enumType, System.String value) (at <23c160f925be47d7a4fd083a3a62c920>:0)
  GooglePlayServices.AndroidAbis.EnumValueStringToULong (System.Type enumType, System.String enumValueString) (at /Users/smiles/dev/src/unity-jar-resolver/source/PlayServicesResolver/src/AndroidAbis.cs:220)
  GooglePlayServices.AndroidAbis.get_Current () (at /Users/smiles/dev/src/unity-jar-resolver/source/PlayServicesResolver/src/AndroidAbis.cs:278)
  GooglePlayServices.PlayServicesResolver.m__1B () (at /Users/smiles/dev/src/unity-jar-resolver/source/PlayServicesResolver/src/PlayServicesResolver.cs:1201)
  GooglePlayServices.PlayServicesResolver+PropertyPoller1[T].Poll (System.Func1[TResult] getCurrentValue, GooglePlayServices.PlayServicesResolver+PropertyPoller`1+Changed[T] changed) (at /Users/smiles/dev/src/unity-jar-resolver/source/PlayServicesResolver/src/PlayServicesResolver.cs:278)
  GooglePlayServices.PlayServicesResolver.PollAndroidAbis () (at /Users/smiles/dev/src/unity-jar-resolver/source/PlayServicesResolver/src/PlayServicesResolver.cs:1201)
  UnityEditor.EditorApplication.Internal_CallUpdateFunctions () (at C:/buildslave/unity/build/Editor/Mono/EditorApplication.cs:303)

答:
It looks like something is wrong with this version.

I'm running 2019.3.0a3 on Mac and have the same error... Sadly I didn't saw it before importing my project and kinda of lost everything, because I can't downgrade my project properly.

My solution is not the best, but here's what I've done:

Downloaded the latest stable build 2019.1.4f1

Created a new project using this build

Copied all the files from my previous project and pasted it inside my new project folder (export package in 2019.3.0a3 not working as well... how great!)

Recreated all my scenes because pasting the files is not enough to replicate them

Aaaaand that's it, hard work but I think it should do (I'm currently doing it right now, I hope it works).

Also, as this is not the best solution, I wished to write it as a comment and not an answer, but my reputation here is kinda low yet.

Cya, good luck with your project and update us if you have any solution better than mine!


问:
How Can I output the response to text file and open the text file when done
I want to modify a Perl script to save the result to text file output.txt and open the results output.txt when task is done

I have tried used "use strict;
use warnings;" and other methods but I keep getting an errors' The Last error was "Couldn't open output.txt"

```<code>#!/usr/bin/perl

use HTTP::Request;
use LWP::UserAgent;

system('cls');
system "color c";
print"\n";
print" |||||||||||||||||Robots scanner|||||||||||||||||||||";
print "\n";

print " Scan Your site Site\n\n Example: www.test.com \n\n-> ";

$site=<STDIN>;
chomp $site;

if($site !~ /http:\/\//) { $site = "http://$site/"; };

print "\n";

@path = ('robotx.txt','robots.txt','robot.txt','search',);

foreach $robots(@path){

  $url = $site.$robots;
  $req = HTTP::Request->new(GET=>$url);
  $useragent = LWP::UserAgent->new();

  $response = $useragent->request($req);
  my $filename = 'report.txt';
  open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
  if ($response->is_success){

    print  ">>>>>>Robots Found !!!>>>: $url\n";
    print $fh "out put has been generated by perl\n"; # THIS DOESN'T WORK THE report.txt is empty
    print "done\n";

  }else{
    print "NotFound : $robots\n";
    print "done\n";
    # I want to open the file from windows explorer automatically here when its done
    close $fh;
  }

}
</code>```

after running cmd as Admin , as you can see the report.txt file shows empty
I expect to see the out put of the Response

I also want perl to open the report.txt ( without going to windows explorer and opening it manually by the user )  I want it automatically open when its done but I wasn't able to achieve that.

Thanks!

答:
Seems you're always overwriting your report file.

Your open is inside the foreach loop. The loop is done 4 times. You will only receive the output of the last run as the first 3 file creations will be overwritten by the last one.

You should put the open and close outside the loop.

If you only need the first result, you can leave, the loop by putting a last statement at the end of the "then-part" of your if.

Body:
I want to modify a Perl script to save the result to text file output.txt and open the results output.txt when task is done

I have tried used "use strict;
use warnings;" and other methods but I keep getting an errors' The Last error was "Couldn't open output.txt"

#!/usr/bin/perl

use HTTP::Request;
use LWP::UserAgent;

system('cls');
system "color c";
print"\n";
print" |||||||||||||||||Robots scanner|||||||||||||||||||||";
print "\n";

print " Scan Your site Site\n\n Example: www.test.com \n\n-> ";

$site=<STDIN>;
chomp $site;

if($site !~ /http:\/\//) { $site = "http://$site/"; };

print "\n";

@path = ('robotx.txt','robots.txt','robot.txt','search',);

foreach $robots(@path){

  $url = $site.$robots;
  $req = HTTP::Request->new(GET=>$url);
  $useragent = LWP::UserAgent->new();

  $response = $useragent->request($req);
  my $filename = 'report.txt';
  open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
  if ($response->is_success){

    print  ">>>>>>Robots Found !!!>>>: $url\n";
    print $fh "out put has been generated by perl\n"; # THIS DOESN'T WORK THE report.txt is empty
    print "done\n";

  }else{
    print "NotFound : $robots\n";
    print "done\n";
    # I want to open the file from windows explorer automatically here when its done
    close $fh;
  }

}

after running cmd as Admin , as you can see the report.txt file shows empty
I expect to see the out put of the Response

I also want perl to open the report.txt ( without going to windows explorer and opening it manually by the user )  I want it automatically open when its done but I wasn't able to achieve that.

Thanks!


问:
Getting value data-toggle radio button
I am having trouble getting the value from a Bootstrap radio button field with data-toggle="wizard-radio".

$('[data-toggle="wizard-radio"]').click(function() {
      wizard = $(this).closest('.wizard-card');
      wizard.find('[data-toggle="wizard-radio"]').removeClass('active');
      $(this).addClass('active');
      $(wizard).find('[type="radio"]').removeAttr('checked');
      $(this).find('[type="radio"]').attr('checked', 'true');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-sm-4 col-sm-offset-2">
  <div class="choice" data-toggle="wizard-radio" rel="tooltip" title="Selecteer deze optie als het een eengezinswoning betreft" name="mhb_type">
    <label>
    <input type="radio" value="House" name="mhb_type">
    <div class="icon">
       <i class="material-icons">home</i>
    </div>
    </label>
    <h6>Eengezinswoning</h6>
  </div>
</div></code>```

It can't get the value of radio button. Anyone any idea how to fix this?

答:
Just try to get the value using active class like :</p>

```<code>$('.choice.active input').val()
</code>```

Title: Getting value data-toggle radio button

Body:
I am having trouble getting the value from a Bootstrap radio button field with data-toggle="wizard-radio".

$('[data-toggle="wizard-radio"]').click(function() {
      wizard = $(this).closest('.wizard-card');
      wizard.find('[data-toggle="wizard-radio"]').removeClass('active');
      $(this).addClass('active');
      $(wizard).find('[type="radio"]').removeAttr('checked');
      $(this).find('[type="radio"]').attr('checked', 'true');
});

    <input type="radio" value="House" name="mhb_type">

       home

Eengezinswoning

It can't get the value of radio button. Anyone any idea how to fix this?

Body:
Just try to get the value using active class like :

$('.choice.active input').val()


问:
max file descriptors [4096] for elasticsearch process is too low, increase to at least [65536]
Using Ubuntu 16.10
Docker 1.12.3
Docker Composer 1.8
Elastic latest tag of official elastic docker image

docker-compose.yml

```<code>version: '2'
services:
    elastic:
        image: elasticsearch
        environment:
            - ES_JAVA_OPTS=-Xmx2g -Xms2g
</code>```

getting on logs

elastic_1 | ERROR: bootstrap checks failed
elastic_1 | max file descriptors [4096] for elasticsearch process is too low, increase to at least [65536]
elastic_1 | [2016-11-18T17:48:17,058][INFO ][o.e.n.Node ] [HK_OIan] stopping ...

Any idea, thanks

答:
check for the actual limit when the process is running (albeit short) with:

```<code>cat /proc/<pid>/limits
</code>```

You will find lines similar to this:

```<code>Limit                     Soft Limit           Hard Limit           Units
Max cpu time              unlimited            unlimited            seconds
Max file size             unlimited            unlimited            bytes
Max data size             unlimited            unlimited            bytes
Max stack size            8388608              unlimited            bytes
Max core file size        0                    unlimited            bytes
<truncated>
</code>```

Then depend on the runner or container (in my case it was supervisord's minfds value), you can lift the actual limitation configuration.

Body:
Using Ubuntu 16.10
Docker 1.12.3
Docker Composer 1.8
Elastic latest tag of official elastic docker image

docker-compose.yml

version: '2'
services:
    elastic:
        image: elasticsearch
        environment:
            - ES_JAVA_OPTS=-Xmx2g -Xms2g

getting on logs

elastic_1 | ERROR: bootstrap checks failed
elastic_1 | max file descriptors [4096] for elasticsearch process is too low, increase to at least [65536]
elastic_1 | [2016-11-18T17:48:17,058][INFO ][o.e.n.Node ] [HK_OIan] stopping ...

Any idea, thanks

Body:
check for the actual limit when the process is running (albeit short) with:

cat /proc/<pid>/limits

You will find lines similar to this:

Limit                     Soft Limit           Hard Limit           Units
Max cpu time              unlimited            unlimited            seconds
Max file size             unlimited            unlimited            bytes
Max data size             unlimited            unlimited            bytes
Max stack size            8388608              unlimited            bytes
Max core file size        0                    unlimited            bytes
<truncated>

Then depend on the runner or container (in my case it was supervisord's minfds value), you can lift the actual limitation configuration.


问:
What is the most elegant way to cast a variable you just received as an argument?
More specifically, what's the most elegant way to cast the Graphics object in a paint() call up to a Graphics2D object?

```<code>public void paint(Graphics g) {
    // How do I convert/cast/etc the g variable to a Graphics2D object?
}
</code>```

Or am I missing the point here? Is there a better way to handle this in general?

答:
Its not directly relevant, but in Scala they recognised this "unpleasantness" - and encourage you to use pattern matching to deal with the correct class instead of a cast:

```<code>g match {
     case Graphics2D(g2d) => //code goes here !
     case _ => Nothing //or throw exception etc
}
</code>```

They actively discourage casts (there is no special cast syntax, only a method).

Not entirely relevant to you, but thought its worth noting that others are troubled by what troubles you ;)

OwnerDisplayName: spligak

ContentLicense: CC BY-SA 2.5

Body:
More specifically, what's the most elegant way to cast the Graphics object in a paint() call up to a Graphics2D object?

public void paint(Graphics g) {
    // How do I convert/cast/etc the g variable to a Graphics2D object?
}

Or am I missing the point here? Is there a better way to handle this in general?

Body:
Its not directly relevant, but in Scala they recognised this "unpleasantness" - and encourage you to use pattern matching to deal with the correct class instead of a cast:

g match {
     case Graphics2D(g2d) => //code goes here !
     case _ => Nothing //or throw exception etc
}

They actively discourage casts (there is no special cast syntax, only a method).

Not entirely relevant to you, but thought its worth noting that others are troubled by what troubles you ;)

OwnerDisplayName: Michael Neale


问:
Is it possible to pass in a git repo tag to an ADO build pipeline as a variable?
Is it possible to pass in a git tag associated with a build in an Azure DevOps build pipeline?

Our tags contain the version of the software being built and released and I want to pass the version in to the build process so it can be included in the code that is being built.

I know there are pre-defined variables for things like Build.BuildNumber, and Build.SourceBranch, but I want to be able to define get the git tag associated with the underlying git repo that the build is based on.

答:
If you build version is a tag (and not branch/commit) you can get the tag value in these 2 variables:</p>

```<code>Build.SourceBranch = refs/tags/test
Build.SourceBranchName = test
</code>```

Body:
If you build version is a tag (and not branch/commit) you can get the tag value in these 2 variables:

Build.SourceBranch = refs/tags/test
Build.SourceBranchName = test


问:
Why JSColor is not initializing on input?
I'm trying to integrate jscolor in a page but it's not working

Input:

```<code><input type="text" id="background_color" name="background_color" class="jscolor" placeholder="Background Color" data-bind="value: background_color">
</code>```

JSColor CDN Link:

```<code><script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/color-js/1.0.1/color.min.js"></script>
</code>```

I'm not getting any errors in console! When I click the input field it doesn't show the color picker!

Snippet:

<input type="text" id="background_color" name="background_color" class="jscolor" placeholder="Background Color" data-bind="value: background_color">```

UPDATE:

The problem was in the src url I was using for js-color library. From the answer below I got the correct URL!

答:
After some searching, I found a different URL that makes it work:

```<code>src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js"
</code>```

I assume this is fine, unless you really want to specifically use that version/library, though I'm not sure if your URL is JSColor or some different library.

Body:
I'm trying to integrate jscolor in a page but it's not working

Input:

<input type="text" id="background_color" name="background_color" class="jscolor" placeholder="Background Color" data-bind="value: background_color">

JSColor CDN Link:

I'm not getting any errors in console! When I click the input field it doesn't show the color picker!

Snippet:

<input type="text" id="background_color" name="background_color" class="jscolor" placeholder="Background Color" data-bind="value: background_color">

UPDATE:

The problem was in the src url I was using for js-color library. From the answer below I got the correct URL!

Body:
After some searching, I found a different URL that makes it work:

src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js"

I assume this is fine, unless you really want to specifically use that version/library, though I'm not sure if your URL is JSColor or some different library.


问:
Error in Hadoop MapReduce
When I run a mapreduce program using Hadoop, I get the following error.

```<code>10/01/18 10:52:48 INFO mapred.JobClient: Task Id : attempt_201001181020_0002_m_000014_0, Status : FAILED
  java.io.IOException: Task process exit with nonzero status of 1.
    at org.apache.hadoop.mapred.TaskRunner.run(TaskRunner.java:418)
10/01/18 10:52:48 WARN mapred.JobClient: Error reading task outputhttp://ubuntu.ubuntu-domain:50060/tasklog?plaintext=true&taskid=attempt_201001181020_0002_m_000014_0&filter=stdout
10/01/18 10:52:48 WARN mapred.JobClient: Error reading task outputhttp://ubuntu.ubuntu-domain:50060/tasklog?plaintext=true&taskid=attempt_201001181020_0002_m_000014_0&filter=stderr
</code>```

What is this error about?

答: I was having the same issue when I run out of space on disk with log directory.</p>

Title: Error in Hadoop MapReduce

Body:
When I run a mapreduce program using Hadoop, I get the following error.

10/01/18 10:52:48 INFO mapred.JobClient: Task Id : attempt_201001181020_0002_m_000014_0, Status : FAILED
  java.io.IOException: Task process exit with nonzero status of 1.
    at org.apache.hadoop.mapred.TaskRunner.run(TaskRunner.java:418)
10/01/18 10:52:48 WARN mapred.JobClient: Error reading task outputhttp://ubuntu.ubuntu-domain:50060/tasklog?plaintext=true&taskid=attempt_201001181020_0002_m_000014_0&filter=stdout
10/01/18 10:52:48 WARN mapred.JobClient: Error reading task outputhttp://ubuntu.ubuntu-domain:50060/tasklog?plaintext=true&taskid=attempt_201001181020_0002_m_000014_0&filter=stderr

What is this error about?