问:
Android - NullPointerException with storage == null
Hi I'm having problems with an android app I'm building. It is a mediaplayer that allows playing at the background. It keeps crashing when I try to run it with the mentioned exception. I would really appreciate some help on how to stop this error please. Here's my Main Activity:

```<code>package com.example.katelee.mp3player;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.example.katelee.mp3player.myService.LocalBinder;

import android.net.Uri;
import android.os.IBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import java.io.File;

public class MainActivity extends AppCompatActivity  {

    private Intent i;
    myService mService;
    boolean mBound = false;

    private Button btnPlayPause, btnStop;
    private SeekBar seekBar;
    MP3Player mediaPlayer;
    private TextView tx;

    public String selectedMusic;
    File musicDir = new File(Environment.getExternalStorageDirectory().getPath()+ "/Music/");

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

        btnPlayPause = (Button) findViewById(R.id.play);
        btnStop = (Button) findViewById(R.id.stop);

        final ListView lv = (ListView) findViewById(R.id.list_view);
        seekBar = (SeekBar) findViewById(R.id.seek_bar);
        tx = (TextView) findViewById(R.id.textView);

        mediaPlayer = MP3Player.getInstance();

        btnPlayPause.setOnClickListener(new OnClickPlayPauseListener());
        btnStop.setOnClickListener(new OnClickStopListener());
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt,long mylng) {
                File selectedFromList =(File) (lv.getItemAtPosition(myItemInt));
                Log.d("g53mdp", selectedFromList.getAbsolutePath());
                selectedMusic = selectedFromList.getAbsolutePath();
            }
        });

        File list[] = musicDir.listFiles();
        lv.setAdapter(new ArrayAdapter<File>(this,android.R.layout.simple_list_item_1, list));

    }
    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        i = new Intent(this, myService.class);
        bindService(i, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    private class OnClickPlayPauseListener implements OnClickListener {

        @Override
        public void onClick(View arg0) {
            if(mBound)
            {
                if(mService.getState() == MP3Player.MP_STATE.PLAYING) {
                    mService.pause();
                }
                else if (mService.getState() == MP3Player.MP_STATE.PAUSED) {
                    mService.start();
                }
                else {
                    seekBar = (SeekBar) findViewById(R.id.seek_bar);

                    configureSeekBar(seekBar);
                    Uri uri = Uri.parse(selectedMusic);
                    mService.playLocalFile(getApplicationContext(), uri);
                }
            }
        }
    }

    private class OnClickStopListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            mService.stop();
        }
    }

    /** Defines callback for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {

            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

    public void configureSeekBar(SeekBar seekBar) {
        this.seekBar = seekBar;

        new Thread(new SeekBarThread()).start();
    }

    private class SeekBarThread implements Runnable {

        @Override
        public void run() {
            try {
                while (mService.getState().equals(MP3Player.MP_STATE.STOPPED)) {
                    Thread.sleep(1000);
                }
                seekBar.setMax(mService.getDuration());
                seekBar.setOnSeekBarChangeListener(new MyOnSeekBarChangedListener());
                while (true) {
                    if (mService.getState() != MP3Player.MP_STATE.STOPPED) {
                        if(mService.getCurrentPosition() < mService.getDuration()){
                            seekBar.setProgress(mService.getCurrentPosition());
                        }
                    }
                    else {
                        seekBar.setProgress(0);
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    private class MyOnSeekBarChangedListener implements OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
            if(fromTouch) {
                mService.seekTo(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            //Empty method
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            //Empty method
        }
    }

}
</code>```

And this is my service class:

```<code>package com.example.katelee.mp3player;

import com.example.katelee.mp3player.MP3Player.MP_STATE;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;

public class myService extends Service implements OnCompletionListener {

    private MP3Player mediaPlayer = MP3Player.getInstance();

    private final IBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        myService getService() {
            return myService.this;
        }
    }

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

    @Override
    public void onCompletion(MediaPlayer arg0) {
        // TODO Auto-generated method stub

    }

    public synchronized MP_STATE getState() {
        return mediaPlayer.getState();
    }

    public void start() {
        mediaPlayer.start();
    }

    public void pause() {
        mediaPlayer.pause();
    }

    public void stop() {
        mediaPlayer.stop();
    }

    public void playLocalFile(Context c, Uri filepath) {
        mediaPlayer.playLocalFile(c, filepath);
    }

    public int getDuration() {
        return mediaPlayer.getDuration();
    }

    public int getCurrentPosition() {
        return mediaPlayer.getCurrentPosition();
    }
    public void seekTo(int sec)
    {
        mediaPlayer.seekTo(sec);
    }
}
</code>```

My MP3Player class:

```<code>package com.example.katelee.mp3player;

import java.io.IOException;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;

public class MP3Player extends MediaPlayer {

    private static MP3Player myMediaPlayer;
    private MP_STATE state;

    public enum MP_STATE {
        ERROR,
        PLAYING,
        PAUSED,
        STOPPED
    }

    public static MP3Player getInstance() {
        if (myMediaPlayer == null) {
            myMediaPlayer = new MP3Player();
        }
        return myMediaPlayer;
    }

    private MP3Player() {
        state = MP3Player.MP_STATE.STOPPED;
    }

    @Override
    public void start() {
        state = MP_STATE.PLAYING;
    }

    @Override
    public void pause() {
        state = MP_STATE.PAUSED;
    }

    @Override
    public void stop() {
        state = MP_STATE.STOPPED;
        super.stop();
        super.reset();
    }

    public void playLocalFile(Context c, Uri filepath) {
        if (!state.equals(MP_STATE.STOPPED)) {
            stop();
        }
        setAudioStreamType(AudioManager.STREAM_MUSIC);
        setOnPreparedListener(new MyOnPreparedListener());
        try {
            setDataSource(c, filepath);
            prepareAsync();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized MP_STATE getState() {
        return state;
    }

    private class MyOnPreparedListener implements OnPreparedListener {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            mediaPlayer.start();
        }
    }
    public int getCurrentPosition() {

        return super.getCurrentPosition();

    }
    public int getDuration()
    {
        return super.getDuration();
    }
    public void seekTo(int sec){
        super.seekTo(sec);
    }

}
</code>```

Here's the logcat:

```<code>12-08 01:03:48.488 13915-13915/? I/art: Not late-enabling -Xcheck:jni (already on)
12-08 01:03:48.519 13915-13921/? E/art: Failed sending reply to debugger: Broken pipe
12-08 01:03:48.520 13915-13921/? I/art: Debugger is no longer active
12-08 01:03:48.554 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_dependencies_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_dependencies_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.671 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_0_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_0_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.692 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_1_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_1_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.736 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_2_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_2_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.758 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_3_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_3_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.782 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_4_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_4_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.810 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_5_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_5_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.832 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_6_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_6_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.850 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_7_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_7_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.873 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_8_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_8_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.911 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_9_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_9_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.912 13915-13915/? W/System: ClassLoader referenced unknown path: /data/app/com.example.katelee.mp3player-1/lib/x86
12-08 01:03:48.914 13915-13915/? I/InstantRun: Starting Instant Run Server for com.example.katelee.mp3player
12-08 01:03:49.413 13915-13915/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
12-08 01:03:49.911 13915-13915/com.example.katelee.mp3player D/AndroidRuntime: Shutting down VM
12-08 01:03:49.913 13915-13915/com.example.katelee.mp3player E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.katelee.mp3player, PID: 13915
                                                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.katelee.mp3player/com.example.katelee.mp3player.MainActivity}: java.lang.NullPointerException: storage == null
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                Caused by: java.lang.NullPointerException: storage == null
                                                                                at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
                                                                                at java.util.Arrays.asList(Arrays.java:155)
                                                                                at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:137)
                                                                                at com.example.katelee.mp3player.MainActivity.onCreate(MainActivity.java:67)
                                                                                at android.app.Activity.performCreate(Activity.java:6237)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

I've already included the necessary tag in my Manifest file so the issue should rise from there. I know the problem that my storage is null but I'm pretty sure it is not null so I'm not sure how to tackle this problem :(

答: listFiles() can return a null, and passing a null array to ArrayAdapter causes this problem. Check for null return value and replace with an empty array before passing it to ArrayAdapter.

Body:
Hi I'm having problems with an android app I'm building. It is a mediaplayer that allows playing at the background. It keeps crashing when I try to run it with the mentioned exception. I would really appreciate some help on how to stop this error please. Here's my Main Activity:

package com.example.katelee.mp3player;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.example.katelee.mp3player.myService.LocalBinder;

import android.net.Uri;
import android.os.IBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import java.io.File;

public class MainActivity extends AppCompatActivity  {

    private Intent i;
    myService mService;
    boolean mBound = false;

    private Button btnPlayPause, btnStop;
    private SeekBar seekBar;
    MP3Player mediaPlayer;
    private TextView tx;

    public String selectedMusic;
    File musicDir = new File(Environment.getExternalStorageDirectory().getPath()+ "/Music/");

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

        btnPlayPause = (Button) findViewById(R.id.play);
        btnStop = (Button) findViewById(R.id.stop);

        final ListView lv = (ListView) findViewById(R.id.list_view);
        seekBar = (SeekBar) findViewById(R.id.seek_bar);
        tx = (TextView) findViewById(R.id.textView);

        mediaPlayer = MP3Player.getInstance();

        btnPlayPause.setOnClickListener(new OnClickPlayPauseListener());
        btnStop.setOnClickListener(new OnClickStopListener());
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt,long mylng) {
                File selectedFromList =(File) (lv.getItemAtPosition(myItemInt));
                Log.d("g53mdp", selectedFromList.getAbsolutePath());
                selectedMusic = selectedFromList.getAbsolutePath();
            }
        });

        File list[] = musicDir.listFiles();
        lv.setAdapter(new ArrayAdapter<File>(this,android.R.layout.simple_list_item_1, list));

    }
    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        i = new Intent(this, myService.class);
        bindService(i, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    private class OnClickPlayPauseListener implements OnClickListener {

        @Override
        public void onClick(View arg0) {
            if(mBound)
            {
                if(mService.getState() == MP3Player.MP_STATE.PLAYING) {
                    mService.pause();
                }
                else if (mService.getState() == MP3Player.MP_STATE.PAUSED) {
                    mService.start();
                }
                else {
                    seekBar = (SeekBar) findViewById(R.id.seek_bar);

                    configureSeekBar(seekBar);
                    Uri uri = Uri.parse(selectedMusic);
                    mService.playLocalFile(getApplicationContext(), uri);
                }
            }
        }
    }

    private class OnClickStopListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            mService.stop();
        }
    }

    /** Defines callback for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {

            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

    public void configureSeekBar(SeekBar seekBar) {
        this.seekBar = seekBar;

        new Thread(new SeekBarThread()).start();
    }

    private class SeekBarThread implements Runnable {

        @Override
        public void run() {
            try {
                while (mService.getState().equals(MP3Player.MP_STATE.STOPPED)) {
                    Thread.sleep(1000);
                }
                seekBar.setMax(mService.getDuration());
                seekBar.setOnSeekBarChangeListener(new MyOnSeekBarChangedListener());
                while (true) {
                    if (mService.getState() != MP3Player.MP_STATE.STOPPED) {
                        if(mService.getCurrentPosition() < mService.getDuration()){
                            seekBar.setProgress(mService.getCurrentPosition());
                        }
                    }
                    else {
                        seekBar.setProgress(0);
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    private class MyOnSeekBarChangedListener implements OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
            if(fromTouch) {
                mService.seekTo(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            //Empty method
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            //Empty method
        }
    }

}

And this is my service class:

package com.example.katelee.mp3player;

import com.example.katelee.mp3player.MP3Player.MP_STATE;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;

public class myService extends Service implements OnCompletionListener {

    private MP3Player mediaPlayer = MP3Player.getInstance();

    private final IBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        myService getService() {
            return myService.this;
        }
    }

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

    @Override
    public void onCompletion(MediaPlayer arg0) {
        // TODO Auto-generated method stub

    }

    public synchronized MP_STATE getState() {
        return mediaPlayer.getState();
    }

    public void start() {
        mediaPlayer.start();
    }

    public void pause() {
        mediaPlayer.pause();
    }

    public void stop() {
        mediaPlayer.stop();
    }

    public void playLocalFile(Context c, Uri filepath) {
        mediaPlayer.playLocalFile(c, filepath);
    }

    public int getDuration() {
        return mediaPlayer.getDuration();
    }

    public int getCurrentPosition() {
        return mediaPlayer.getCurrentPosition();
    }
    public void seekTo(int sec)
    {
        mediaPlayer.seekTo(sec);
    }
}

My MP3Player class:

package com.example.katelee.mp3player;

import java.io.IOException;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;

public class MP3Player extends MediaPlayer {

    private static MP3Player myMediaPlayer;
    private MP_STATE state;

    public enum MP_STATE {
        ERROR,
        PLAYING,
        PAUSED,
        STOPPED
    }

    public static MP3Player getInstance() {
        if (myMediaPlayer == null) {
            myMediaPlayer = new MP3Player();
        }
        return myMediaPlayer;
    }

    private MP3Player() {
        state = MP3Player.MP_STATE.STOPPED;
    }

    @Override
    public void start() {
        state = MP_STATE.PLAYING;
    }

    @Override
    public void pause() {
        state = MP_STATE.PAUSED;
    }

    @Override
    public void stop() {
        state = MP_STATE.STOPPED;
        super.stop();
        super.reset();
    }

    public void playLocalFile(Context c, Uri filepath) {
        if (!state.equals(MP_STATE.STOPPED)) {
            stop();
        }
        setAudioStreamType(AudioManager.STREAM_MUSIC);
        setOnPreparedListener(new MyOnPreparedListener());
        try {
            setDataSource(c, filepath);
            prepareAsync();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized MP_STATE getState() {
        return state;
    }

    private class MyOnPreparedListener implements OnPreparedListener {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            mediaPlayer.start();
        }
    }
    public int getCurrentPosition() {

        return super.getCurrentPosition();

    }
    public int getDuration()
    {
        return super.getDuration();
    }
    public void seekTo(int sec){
        super.seekTo(sec);
    }

}

Here's the logcat:

12-08 01:03:48.488 13915-13915/? I/art: Not late-enabling -Xcheck:jni (already on)
12-08 01:03:48.519 13915-13921/? E/art: Failed sending reply to debugger: Broken pipe
12-08 01:03:48.520 13915-13921/? I/art: Debugger is no longer active
12-08 01:03:48.554 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_dependencies_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_dependencies_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.671 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_0_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_0_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.692 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_1_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_1_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.736 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_2_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_2_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.758 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_3_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_3_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.782 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_4_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_4_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.810 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_5_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_5_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.832 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_6_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_6_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.850 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_7_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_7_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.873 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_8_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_8_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.911 13915-13915/? W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.katelee.mp3player-1/split_lib_slice_9_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.katelee.mp3player-1@split_lib_slice_9_apk.apk@classes.dex) because non-0 exit status
12-08 01:03:48.912 13915-13915/? W/System: ClassLoader referenced unknown path: /data/app/com.example.katelee.mp3player-1/lib/x86
12-08 01:03:48.914 13915-13915/? I/InstantRun: Starting Instant Run Server for com.example.katelee.mp3player
12-08 01:03:49.413 13915-13915/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
12-08 01:03:49.911 13915-13915/com.example.katelee.mp3player D/AndroidRuntime: Shutting down VM
12-08 01:03:49.913 13915-13915/com.example.katelee.mp3player E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.katelee.mp3player, PID: 13915
                                                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.katelee.mp3player/com.example.katelee.mp3player.MainActivity}: java.lang.NullPointerException: storage == null
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                Caused by: java.lang.NullPointerException: storage == null
                                                                                at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
                                                                                at java.util.Arrays.asList(Arrays.java:155)
                                                                                at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:137)
                                                                                at com.example.katelee.mp3player.MainActivity.onCreate(MainActivity.java:67)
                                                                                at android.app.Activity.performCreate(Activity.java:6237)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

I've already included the necessary tag in my Manifest file so the issue should rise from there. I know the problem that my storage is null but I'm pretty sure it is not null so I'm not sure how to tackle this problem :(


来源: stackexchange

问:
Ansible - use with_items and with_sequence at the same time
Is there any way to make a part of role like this:
I need to run five times commands that are in the nrpe.cfg (there 5 commands in the config file - so 5 x 5 commands) ?</p>

```<code>- name: grep the commands from nagios
  shell: grep -R check_http_ /etc/nagios/nrpe.cfg | cut -d= -f2-
  register: nagios_check
- name: check_before
  shell: (printf $(echo '{{ item }}' | awk -F'country=' '{print $2}' | cut -d'&' -f1); printf ' ';{{ item }} | cut -d ' ' -f-2) >> {{ ansible_env.DATA_LOG }}/eden-{{ dateext.stdout }}
  register: checkedenbefore
  with_items: "{{ nagios_check.stdout_lines }}"
  **with_sequence: count=5**
  ignore_errors: True
</code>```

答:
You can use with_nested.</p>

```<code>- name: grep the commands from nagios
  shell: grep -R check_http_ /etc/nagios/nrpe.cfg | cut -d= -f2-
  register: nagios_check

- name: check_before
  shell: (printf $(echo '{{ item.0 }}' | awk -F'country=' '{print $2}' | cut -d'&' -f1); printf ' ';{{ item.0 }} | cut -d ' ' -f-2) >> {{ ansible_env.DATA_LOG }}/eden-{{ dateext.stdout }}
  register: checkedenbefore
  with_nested:
   - "{{ nagios_check.stdout_lines }}"
   - "{{ range(0, 5) }}"
  ignore_errors: True
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there any way to make a part of role like this:
I need to run five times commands that are in the nrpe.cfg (there 5 commands in the config file - so 5 x 5 commands) ?

- name: grep the commands from nagios
  shell: grep -R check_http_ /etc/nagios/nrpe.cfg | cut -d= -f2-
  register: nagios_check
- name: check_before
  shell: (printf $(echo '{{ item }}' | awk -F'country=' '{print $2}' | cut -d'&' -f1); printf ' ';{{ item }} | cut -d ' ' -f-2) >> {{ ansible_env.DATA_LOG }}/eden-{{ dateext.stdout }}
  register: checkedenbefore
  with_items: "{{ nagios_check.stdout_lines }}"
  **with_sequence: count=5**
  ignore_errors: True

Body:
You can use with_nested.

- name: grep the commands from nagios
  shell: grep -R check_http_ /etc/nagios/nrpe.cfg | cut -d= -f2-
  register: nagios_check

- name: check_before
  shell: (printf $(echo '{{ item.0 }}' | awk -F'country=' '{print $2}' | cut -d'&' -f1); printf ' ';{{ item.0 }} | cut -d ' ' -f-2) >> {{ ansible_env.DATA_LOG }}/eden-{{ dateext.stdout }}
  register: checkedenbefore
  with_nested:
   - "{{ nagios_check.stdout_lines }}"
   - "{{ range(0, 5) }}"
  ignore_errors: True


问:
Using WebClient how do I code the data parameter for posting to a URI?
I have created a test html form using the code shown here which, when I enter a value in the Key textbox, select the first of the two Types and click the Continue button the browser window will navigate to an XML version of a web page. If I replace XML with JSON on the form action line, it would render the same web page in a JSON format. Replace it with SUBMIT and the resulting web page would be just a normal web page.

```<code><!DOCTYPE html>
<html lang="en-us">
<head>
    <meta charset="utf-8" />
</head>
<body>
    <form action="https://www.someaddress.com/xxxxxxxxxx/999999999/XML" method="post">
        <table role="presentation">
            <tr>
                <th><label for="key">Key</label></th>
                <td><input type="text" id="key" name="key" size="10" autofocus> </td>
            </tr>
            <tr>
                <th>Type</th>
                <td>
                    <label><input type="radio" name="type" id="type1" value="type1"> Type 1</label>
                    <label><input type="radio" name="type" id="type2" value="type2"> Type 2</label>
                </td>
            </tr>
            <tr>
                <td></td>
                <td><button type="submit" class="btn btn--primary">Continue</button></td>
            </tr>
        </table>
    </form>
</body>
</html>
</code>```

The problem I'm having is with an attempt I'm making to convert the action of the web form above into a method of a console application below. When using WebClient (which is how this application interacts with the web in several other places), how should the value of the string variable "data" be written so that it will be posted to the destination ip address being passed into the method and return a string containing the XML data that is the web page? I've tried the line shown below (which was taken from one web page that I found when searching the Internet for an answer to this question) and also with the values of MyKeyVal and type1 surrounded by escaped double quotes but neither way is working for me. I get errors stating “meta start tag on line 14 position 6 does not match the end tag of head line 22 position 3” but since the “data” variable doesn’t have any tags I’m not sure what should be changed to resolve such an error.

```<code>static string Submit(string ip, string id)
{
    string response;
    using (var client = new WebClient())
    {
        Uri uri = new System.Uri("https://" + ip + "/xxxxxxxxxx/" + id + "/XML");
        string data = "key = MyKeyVal type = type1";
        response = client.UploadString(uri, data);
    }
    //additional parsing of the response goes here
    return response;
}
</code>```

答:
A coworker of mine suggested the following which, even though it doesn't employ the use of WebClient, it does resolve the issue I was having:</p>

```<code>    static string Submit(string ip, string id)
    {
    string response;
    var client = (HttpWebRequest)WebRequest.Create("https://" + ip + "/xxxxxxxxxx/" + rt + "/XML");
    client.ContentType = "application/x-www-form-urlencoded";
    client.Method = "POST";
    var requestStream = client.GetRequestStreamAsync().Result;
    var data = Encoding.UTF8.GetBytes("key=MyKeyVal&type=type1");
    requestStream.Write(data, 0, data.Length);
    var result = client.GetResponseAsync().Result;
    using (var reader = new StreamReader(result.GetResponseStream()))
    {
        response = reader.ReadToEnd();
    }
    //additional parsing of the response goes here
    return response;
}
</code>```

Body:
I have created a test html form using the code shown here which, when I enter a value in the Key textbox, select the first of the two Types and click the Continue button the browser window will navigate to an XML version of a web page. If I replace XML with JSON on the form action line, it would render the same web page in a JSON format. Replace it with SUBMIT and the resulting web page would be just a normal web page.

<!DOCTYPE html>

    <meta charset="utf-8" />

    <form action="https://www.someaddress.com/xxxxxxxxxx/999999999/XML" method="post">

                Key
                <input type="text" id="key" name="key" size="10" autofocus>

                Type

                    <input type="radio" name="type" id="type1" value="type1"> Type 1
                    <input type="radio" name="type" id="type2" value="type2"> Type 2

                <button type="submit" class="btn btn--primary">Continue</button>

    </form>

The problem I'm having is with an attempt I'm making to convert the action of the web form above into a method of a console application below. When using WebClient (which is how this application interacts with the web in several other places), how should the value of the string variable "data" be written so that it will be posted to the destination ip address being passed into the method and return a string containing the XML data that is the web page? I've tried the line shown below (which was taken from one web page that I found when searching the Internet for an answer to this question) and also with the values of MyKeyVal and type1 surrounded by escaped double quotes but neither way is working for me. I get errors stating “meta start tag on line 14 position 6 does not match the end tag of head line 22 position 3” but since the “data” variable doesn’t have any tags I’m not sure what should be changed to resolve such an error.

static string Submit(string ip, string id)
{
    string response;
    using (var client = new WebClient())
    {
        Uri uri = new System.Uri("https://" + ip + "/xxxxxxxxxx/" + id + "/XML");
        string data = "key = MyKeyVal type = type1";
        response = client.UploadString(uri, data);
    }
    //additional parsing of the response goes here
    return response;
}

Body:
A coworker of mine suggested the following which, even though it doesn't employ the use of WebClient, it does resolve the issue I was having:

    static string Submit(string ip, string id)
    {
    string response;
    var client = (HttpWebRequest)WebRequest.Create("https://" + ip + "/xxxxxxxxxx/" + rt + "/XML");
    client.ContentType = "application/x-www-form-urlencoded";
    client.Method = "POST";
    var requestStream = client.GetRequestStreamAsync().Result;
    var data = Encoding.UTF8.GetBytes("key=MyKeyVal&type=type1");
    requestStream.Write(data, 0, data.Length);
    var result = client.GetResponseAsync().Result;
    using (var reader = new StreamReader(result.GetResponseStream()))
    {
        response = reader.ReadToEnd();
    }
    //additional parsing of the response goes here
    return response;
}


问:
What is the good ruby world-wide programming competition other than Rails rumble?
Please name one or more ruby world-wide programming competitions other than rails rumble</p>

答:
http://rubyquiz.com </p>

<p>It is not a programming competition per say but quiet close. </p>

ContentLicense: CC BY-SA 2.5

Body:
http://rubyquiz.com

It is not a programming competition per say but quiet close.


问:
Building triangle with nested loops
I'm trying to build a triangle using nested loops.

var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  for (var x = 0; x < row; x++) {
    line += "#";
  }
  triangle += line + "\n";
}

console.log(triangle);```

I expected that each row is more than the last by only one "#" like this:

But this is the result I got:

答:
You need to empty your line before each nested iteration. Without this you have one line and every time concatenate new items to it. Also you can leave the line variable and just use the triangle.

var triangle = '';

for (var row = 1; row <= 7; row++) {
  for (var x = 0; x < row; x++) {
    triangle += "#";
  }
  triangle += "\n";
}

console.log(triangle);```
</div>
</div>
</p>

<p>You can also try this solution with String#repeat</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var triangle = '';

for (var row = 1; row <= 7; row++) {
  triangle += '#'.repeat(row) + '\n';
}

console.log(triangle);</code>```

Title: Building triangle with nested loops

Body:
I'm trying to build a triangle using nested loops.

var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  for (var x = 0; x < row; x++) {
    line += "#";
  }
  triangle += line + "\n";
}

console.log(triangle);

I expected that each row is more than the last by only one "#" like this:

But this is the result I got:

Body:
You need to empty your line before each nested iteration. Without this you have one line and every time concatenate new items to it. Also you can leave the line variable and just use the triangle.

var triangle = '';

for (var row = 1; row <= 7; row++) {
  for (var x = 0; x < row; x++) {
    triangle += "#";
  }
  triangle += "\n";
}

console.log(triangle);

You can also try this solution with String#repeat

var triangle = '';

for (var row = 1; row <= 7; row++) {
  triangle += '#'.repeat(row) + '\n';
}

console.log(triangle);


问:
Data rotation in DB2
The data for reprocessing requests from the previous week gets moved to a back up table on  due to which I am unable to reprocess failures that occurs during the weekend.

For a particular table, we have three different identical versions. Lets say, we have table1 to store the status and id of the documents. So we have three identical versions of Table1.

Table1_A

Table1_B

Table1_C

Table1_A will be active for a week and will store all records and on weekend, a script is run and after that Table1_A will be inactive and table1_B (which is empty) will take its place as active table for the week. Table1_A will retain data from the previous week. The following weekend the script will make Table1_C active, Table1_B will retain its data from the previous week and Table1_A will remove all its data. Same process will repeat every week.

Since the data pertaining to the previous week is in a table that is not active anymore, we are unable to troubleshoot any failures from the previous week.

I have though about copying the previous weeks data from the previous active table to the new active table. The new active table instead of being empty now will have data from previous week.

So, my question is what is a good way to copy this data?

And what are things that I need to worry about while copying this data?

Also, is there a better way to resolve this?

Thanks for your help.

答:
The described solution is very inflexible.
You do not describe the reason for doing this but I would urgently recommend to have a look at partitioning Range Partitioning will give you SQL performance and fast roll out of data if this is a concern.

When data resides in in Table1_a while Table1_b is active - table1_a is still there and could be queried. It may be offline from an application point of view but not from a database point of view.

Without any more business background information I just could recommend to check out table partitioning.

Title: Data rotation in DB2


问:
How to take screenshots using marmalade with c++?
I searched along the documentation and found nothing, then after searching on google i found this glReadPixels and i guess i may be able to take screenshots.

I need to create a facebookdialog with an image so im using this lines:

```<code>static s3eFBRequest* req = s3eFBRequest_WithGraphPath(MultiLoginScene::getSession(), "me/photos", "POST");
s3eFBRequest_AddParamString(req, "picture", XXX);
</code>```

XXX is a const char* that would be this screenshot I need to take and then i will just send the request.

How can I do that?

答:
Marmalade website is gone.  Unfortunate the answer wasn't posted here, but briefly:</p>

```<code>int w = s3eSurfaceGetInt(S3E_SURFACE_WIDTH);
int h = s3eSurfaceGetInt(S3E_SURFACE_HEIGHT);

int dataSize = w * h * 3;
unsigned char *framebuffer = (unsigned char *) malloc(dataSize * sizeof(unsigned char));
glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, framebuffer);
flipVertical(framebuffer, w, h);

CIwImage image;
image.SetFormat(CIwImage::BGR_888);
image.SetWidth(w);
image.SetHeight(h);
image.SetBuffers(framebuffer, dataSize);
image.SavePng(filename);

free(framebuffer);
</code>```

Body:
I searched along the documentation and found nothing, then after searching on google i found this glReadPixels and i guess i may be able to take screenshots.

I need to create a facebookdialog with an image so im using this lines:

static s3eFBRequest* req = s3eFBRequest_WithGraphPath(MultiLoginScene::getSession(), "me/photos", "POST");
s3eFBRequest_AddParamString(req, "picture", XXX);

XXX is a const char* that would be this screenshot I need to take and then i will just send the request.

How can I do that?

Body:
Marmalade website is gone.  Unfortunate the answer wasn't posted here, but briefly:

int w = s3eSurfaceGetInt(S3E_SURFACE_WIDTH);
int h = s3eSurfaceGetInt(S3E_SURFACE_HEIGHT);

int dataSize = w * h * 3;
unsigned char *framebuffer = (unsigned char *) malloc(dataSize * sizeof(unsigned char));
glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, framebuffer);
flipVertical(framebuffer, w, h);

CIwImage image;
image.SetFormat(CIwImage::BGR_888);
image.SetWidth(w);
image.SetHeight(h);
image.SetBuffers(framebuffer, dataSize);
image.SavePng(filename);

free(framebuffer);


问:
How do we Check if there are some avro files available inside a HDFS folder?
I have some avro files inside HDFS folder /user/data/output_files/file_2017-10-18

```<code>scala> val hdfsLoc ="/user/data/output_files/file_2017-10-18/*.avro"
hdfsLoc: String = /user/data/output_files/file_2017-10-18/*.avro

scala>  val conf = new Configuration()

scala>   val fs  = FileSystem.get(conf)

scala> val result = fs.exists(new Path(hdfsLoc))
result: Boolean = false
</code>```

The above code gives result as false . It says there is no avro files  inside that HDFS folder

If I give the full name of avro file , then it returns true

```<code>scala>  val hdfsLoc ="/user/data/output_files/file_2017-10-18/part-r-00000-ed937f14-c7d1-480a-9c79-1cda3db4e6ce.avro"
hdfsLoc: String = /user/data/output_files/file_2017-10-18/part-r-00000-ed937f14-c7d1-480a-9c79-1cda3db4e6ce.avro

scala> val result = fs.exists(new Path(hdfsLoc))
result: Boolean = true
</code>```

How do I ensure that there are  one or more avro files inside a HDFS folder?

答:
Seems FileSystem doesn't support wildcards. The workaround should be as below though it looks nasty.</p>

```<code> val list = fs.listFiles(new Path("/test/"), true)

 var result=false

 while(list.hasNext()){
   if(list.next().getPath.getName.endsWith(".avro"))
     result=true
 }
</code>```

Body:
I have some avro files inside HDFS folder /user/data/output_files/file_2017-10-18

scala> val hdfsLoc ="/user/data/output_files/file_2017-10-18/*.avro"
hdfsLoc: String = /user/data/output_files/file_2017-10-18/*.avro

scala>  val conf = new Configuration()

scala>   val fs  = FileSystem.get(conf)

scala> val result = fs.exists(new Path(hdfsLoc))
result: Boolean = false

The above code gives result as false . It says there is no avro files  inside that HDFS folder

If I give the full name of avro file , then it returns true

scala>  val hdfsLoc ="/user/data/output_files/file_2017-10-18/part-r-00000-ed937f14-c7d1-480a-9c79-1cda3db4e6ce.avro"
hdfsLoc: String = /user/data/output_files/file_2017-10-18/part-r-00000-ed937f14-c7d1-480a-9c79-1cda3db4e6ce.avro

scala> val result = fs.exists(new Path(hdfsLoc))
result: Boolean = true

How do I ensure that there are  one or more avro files inside a HDFS folder?

Body:
Seems FileSystem doesn't support wildcards. The workaround should be as below though it looks nasty.

 val list = fs.listFiles(new Path("/test/"), true)

 var result=false

 while(list.hasNext()){
   if(list.next().getPath.getName.endsWith(".avro"))
     result=true
 }


问:
IIS process w3wp.exe is not showing in Task manager processes?
I am having a very weird issue that I am unable to see w3wp.exe anywhere in my system. I am learning ASP.NET using tutorials. In my computer w3wp.exe process is not showing in the taskmanager. Please help, I got frustrated by searching it throughout the whole day. I have iis7.5 installed!

答: In Task Manager processes it shows as IIS Worker Process, right click on it and click on 'Go to details' you will see w3wp.exe.</p>


问:
StatusCode.UNAUTHENTICATED Google assistant Windows 10
I am trying to run google assistant on my windows computer and have been following this guide: XDA developers guide

When I run:

```<code>python -m googlesamples.assistant.grpc.pushtotalk
</code>```

and then hit enter so send a command I get the following error:

```<code>Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Program Files\Python36\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Program Files\Python36\lib\site-packages\googlesamples\assistant\grpc\pushtotalk.py", line 328, in <module>
    main()
  File "C:\Program Files\Python36\lib\site-packages\click\core.py", line 722, in __call__
    return self.main(*args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\click\core.py", line 697, in main
    rv = self.invoke(ctx)
  File "C:\Program Files\Python36\lib\site-packages\click\core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "C:\Program Files\Python36\lib\site-packages\click\core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\googlesamples\assistant\grpc\pushtotalk.py", line 317, in main
    continue_conversation = assistant.converse()
  File "C:\Program Files\Python36\lib\site-packages\tenacity\__init__.py", line 87, in wrapped_f
    return r.call(f, *args, **kw)
  File "C:\Program Files\Python36\lib\site-packages\tenacity\__init__.py", line 235, in call
    do = self.iter(result=result, exc_info=exc_info)
  File "C:\Program Files\Python36\lib\site-packages\tenacity\__init__.py", line 194, in iter
    return fut.result()
  File "C:\Program Files\Python36\lib\concurrent\futures\_base.py", line 425, in result
    return self.__get_result()
  File "C:\Program Files\Python36\lib\concurrent\futures\_base.py", line 384, in __get_result
    raise self._exception
  File "C:\Program Files\Python36\lib\site-packages\tenacity\__init__.py", line 238, in call
    result = fn(*args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\googlesamples\assistant\grpc\pushtotalk.py", line 110, in converse
    self.deadline):
  File "C:\Program Files\Python36\lib\site-packages\grpc\_channel.py", line 349, in __next__
    return self._next()
  File "C:\Program Files\Python36\lib\site-packages\grpc\_channel.py", line 343, in _next
    raise self
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with (StatusCode.UNAUTHENTICATED, Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com
/identity/sign-in/web/devconsole-project.)>
</code>```

答:
You just have to wait until they fix that, the bug is on Google's side. Here is the issue they opened at github:

https://github.com/googlesamples/assistant-sdk-python/issues/138

Body:
I am trying to run google assistant on my windows computer and have been following this guide: XDA developers guide

When I run:

python -m googlesamples.assistant.grpc.pushtotalk

and then hit enter so send a command I get the following error:

Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Program Files\Python36\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Program Files\Python36\lib\site-packages\googlesamples\assistant\grpc\pushtotalk.py", line 328, in <module>
    main()
  File "C:\Program Files\Python36\lib\site-packages\click\core.py", line 722, in __call__
    return self.main(*args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\click\core.py", line 697, in main
    rv = self.invoke(ctx)
  File "C:\Program Files\Python36\lib\site-packages\click\core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "C:\Program Files\Python36\lib\site-packages\click\core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\googlesamples\assistant\grpc\pushtotalk.py", line 317, in main
    continue_conversation = assistant.converse()
  File "C:\Program Files\Python36\lib\site-packages\tenacity\__init__.py", line 87, in wrapped_f
    return r.call(f, *args, **kw)
  File "C:\Program Files\Python36\lib\site-packages\tenacity\__init__.py", line 235, in call
    do = self.iter(result=result, exc_info=exc_info)
  File "C:\Program Files\Python36\lib\site-packages\tenacity\__init__.py", line 194, in iter
    return fut.result()
  File "C:\Program Files\Python36\lib\concurrent\futures\_base.py", line 425, in result
    return self.__get_result()
  File "C:\Program Files\Python36\lib\concurrent\futures\_base.py", line 384, in __get_result
    raise self._exception
  File "C:\Program Files\Python36\lib\site-packages\tenacity\__init__.py", line 238, in call
    result = fn(*args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\googlesamples\assistant\grpc\pushtotalk.py", line 110, in converse
    self.deadline):
  File "C:\Program Files\Python36\lib\site-packages\grpc\_channel.py", line 349, in __next__
    return self._next()
  File "C:\Program Files\Python36\lib\site-packages\grpc\_channel.py", line 343, in _next
    raise self
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with (StatusCode.UNAUTHENTICATED, Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com
/identity/sign-in/web/devconsole-project.)>


问:
local MAMP Pro redirect to https
I have installed Mamp Pro to run my local host and it has been working great for a year or so but recently when I start it up and go to one of my hosts it redirects to a https connection and throws an error:

"Safari Can't Open Page.  Safari can't open page because Safari can't establish a secure connection to the server."

It works fine in Chrome but Safari is giving me issues.  I've restarted my computer, restarted MAMP and nothing has worked so far.  Any help would be greatly appreciated.

答:
If you are using .dev domains for local development ( mydomain.dev ) , try something else e.g. mydomain.local, mydomain.lcl

This happened to me with macOS 10.13.2, in both Safari and Chrome (63.0.3239.84).

After reading this post, it seems a better choice to just change my .dev domains than mess with browser default settings.

Title: local MAMP Pro redirect to https


问:
3d Stacked bar plot in R
I have a dataframe mydf as shown below. I want to plot a stacked 3d plot (as shown in sample plot below) where A, C, G, T columns are represented by bars (years in the sample plot). Length column ranges from 18 to 34 for each file.name and want them to be on the Gas Type axis as in example plot, then I finally want file.name column to be on country axis as in sample plot below. How can I get this plotted in R? Thanks for your help.

```<code>  mydf <-  structure(list(file.name = structure(c(1L, 1L, 2L, 2L, 4L, 4L
    ), .Label = c("merged_read_counts", "DCL1_VF_1_GAGTGG_L008_R1_001",
    "DCL1_VF_2_GGTAGC_L008_R1_001", "DCL2_VF_1_ACTGAT_L008_R1_001",
    "DCL2_VF_2_ATGAGC_L008_R1_001", "DCLd_SSHADV1_1_AGTTCC_L008_R1_001",
    "DCLd_SSHADV1_2_ATGTCA_L008_R1_001", "DCLd_SSHADV1_3_CCGTCC_L008_R1_001",
    "DCLd_SSHV2L_1_GTAGAG_L008_R1_001", "DCLd_SSHV2L_2_GTCCGC_L008_R1_001",
    "DCLd_SSHV2L_3_GTGAAA_L008_R1_001", "DCLd_VF_1_GTGGCC_L008_R1_001",
    "DCLd_VF_2_GTTTCG_L008_R1_001", "DCLd_VF_3_CGTACG_L008_R1_001",
    "WT_SSHADV1_1_GGCTAC_L008_R1_001", "WT_SSHADV1_2_CTTGTA_L008_R1_001",
    "WT_SSHADV1_3_AGTCAA_L008_R1_001", "WT_SSHV2L_1_GCCAAT_L008_R1_001",
    "WT_SSHV2L_2_CAGATC_L008_R1_001", "WT_SSHV2L_3_ACTTGA_L008_R1_001",
    "WT_SSHV2L_4_GATCAG_L008_R1_001", "WT_SSHV2L_5_TAGCTT_L008_R1_001",
    "WT_VF_1_ATCACG_L008_R1_001", "WT_VF_2_CGATGT_L008_R1_001", "WT_VF_3_TTAGGC_L008_R1_001",
    "WT_VF_4_TGACCA_L008_R1_001", "WT_VF_5_ACAGTG_L008_R1_001"), class = "factor"),
        length = c(18L, 19L, 18L, 19L, 18L, 19L), A = c(2294436L,
        2588528L, 52104L, 47190L, 103378L, 59269L), C = c(1501040L,
        2838174L, 35888L, 93922L, 38132L, 31912L), G = c(2106623L,
        1714702L, 80765L, 64930L, 129040L, 161517L), T = c(5065628L,
        7462881L, 62174L, 87905L, 274783L, 110125L)), .Names = c("file.name",
    "length", "A", "C", "G", "T"), row.names = c(1L, 2L, 18L, 19L,
    58L, 59L), class = "data.frame")
</code>```

答:
I don't think 3d bar plots are available in ggplot(ggplot2 3D Bar Plot).

I would suggest grouped, stacked barplots instead. Something like:

```<code>library(ggplot2)
library(reshape2)
df <- melt(mydf,id.vars=c("file.name","length"))
ggplot(df, aes(x = file.name, y = value, fill = variable)) +
  geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ length)
</code>```

Title: 3d Stacked bar plot in R

Body:
I have a dataframe mydf as shown below. I want to plot a stacked 3d plot (as shown in sample plot below) where A, C, G, T columns are represented by bars (years in the sample plot). Length column ranges from 18 to 34 for each file.name and want them to be on the Gas Type axis as in example plot, then I finally want file.name column to be on country axis as in sample plot below. How can I get this plotted in R? Thanks for your help.

  mydf <-  structure(list(file.name = structure(c(1L, 1L, 2L, 2L, 4L, 4L
    ), .Label = c("merged_read_counts", "DCL1_VF_1_GAGTGG_L008_R1_001",
    "DCL1_VF_2_GGTAGC_L008_R1_001", "DCL2_VF_1_ACTGAT_L008_R1_001",
    "DCL2_VF_2_ATGAGC_L008_R1_001", "DCLd_SSHADV1_1_AGTTCC_L008_R1_001",
    "DCLd_SSHADV1_2_ATGTCA_L008_R1_001", "DCLd_SSHADV1_3_CCGTCC_L008_R1_001",
    "DCLd_SSHV2L_1_GTAGAG_L008_R1_001", "DCLd_SSHV2L_2_GTCCGC_L008_R1_001",
    "DCLd_SSHV2L_3_GTGAAA_L008_R1_001", "DCLd_VF_1_GTGGCC_L008_R1_001",
    "DCLd_VF_2_GTTTCG_L008_R1_001", "DCLd_VF_3_CGTACG_L008_R1_001",
    "WT_SSHADV1_1_GGCTAC_L008_R1_001", "WT_SSHADV1_2_CTTGTA_L008_R1_001",
    "WT_SSHADV1_3_AGTCAA_L008_R1_001", "WT_SSHV2L_1_GCCAAT_L008_R1_001",
    "WT_SSHV2L_2_CAGATC_L008_R1_001", "WT_SSHV2L_3_ACTTGA_L008_R1_001",
    "WT_SSHV2L_4_GATCAG_L008_R1_001", "WT_SSHV2L_5_TAGCTT_L008_R1_001",
    "WT_VF_1_ATCACG_L008_R1_001", "WT_VF_2_CGATGT_L008_R1_001", "WT_VF_3_TTAGGC_L008_R1_001",
    "WT_VF_4_TGACCA_L008_R1_001", "WT_VF_5_ACAGTG_L008_R1_001"), class = "factor"),
        length = c(18L, 19L, 18L, 19L, 18L, 19L), A = c(2294436L,
        2588528L, 52104L, 47190L, 103378L, 59269L), C = c(1501040L,
        2838174L, 35888L, 93922L, 38132L, 31912L), G = c(2106623L,
        1714702L, 80765L, 64930L, 129040L, 161517L), T = c(5065628L,
        7462881L, 62174L, 87905L, 274783L, 110125L)), .Names = c("file.name",
    "length", "A", "C", "G", "T"), row.names = c(1L, 2L, 18L, 19L,
    58L, 59L), class = "data.frame")

Body:
I don't think 3d bar plots are available in ggplot(ggplot2 3D Bar Plot).

I would suggest grouped, stacked barplots instead. Something like:

library(ggplot2)
library(reshape2)
df <- melt(mydf,id.vars=c("file.name","length"))
ggplot(df, aes(x = file.name, y = value, fill = variable)) +
  geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ length)


问:
Firebase Dynamic Link can’t open app directly
According to Firebase document, I create Dynamic Link in Firebase console, then include the Dynamic Links SDK in my app.

Everything is good, but when I click share link (which is my dynamic link) from facebook or messenger, it popps up a page with a open-app button and ask me if I want to open my app or not.

And I didn't make this page. I want to remove this.

But I click the link from Memorandum, it opens my app and go to the right page directly.  I want the same way with the share links.

Here is my code, I use Xcode with Objective-c to develop iOS app. Thanks!

Appdelegate.m

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    [FIROptions defaultOptions].deepLinkURLScheme = @"com.levooya.LeVooya";
    [FIRApp configure];
    return YES;
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray * _Nullable))restorationHandler{
    NSURL *url = userActivity.webpageURL;
    NSLog(@"continueUserActivity url.absoluteString:%@",url.absoluteString);

    BOOL handled = [[FIRDynamicLinks dynamicLinks] handleUniversalLink:userActivity.webpageURL completion:^(FIRDynamicLink *dynamicLink, NSError *error){
        if(dynamicLink.url){
            NSLog(@"okokokokokok");
            NSLog(@"dynamicLink.url:%@",dynamicLink.url);

            NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:dynamicLink.url
                                                      resolvingAgainstBaseURL:NO];

            for(NSURLQueryItem *item in urlComponents.queryItems){
                if([item.name isEqualToString:@"product_id"]){
                    NSLog(@"item.value:%@",item.value);
                    NSString *productID = item.value;

                    NSDictionary *urlSchemeDict = [[NSDictionary alloc] init];

                    urlSchemeDict = [NSDictionary dictionaryWithObject:productID forKey:@"product_id"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"URLSchemeShowProduct" object:nil userInfo:urlSchemeDict];

                    leData = [LevooyaData getInstance];
                    leData.urlSchemeDict = nil;
                    leData.urlSchemeDict = urlSchemeDict;
                }
            }
        }
    }];
    return YES;
}
</code>```

ProductView.m

(This is the page which display product in my app, and here is the function I click share button to generate dynamic link.)

```<code>- (void)share{
    NSString *originalLink = [NSString stringWithFormat:@"https://pbu3y.app.goo.gl/?link=https://levooya.com/product?product_id=%u&isi=1221262097&ibi=com.levooya.LeVooya&product_id=%u", productID, productID];
    NSURL *link = [NSURL URLWithString:originalLink];
    FIRDynamicLinkComponents *components =
    [FIRDynamicLinkComponents componentsWithLink:link
                                          domain:@"pbu3y.app.goo.gl"];

    FIRDynamicLinkSocialMetaTagParameters *socialParams = [FIRDynamicLinkSocialMetaTagParameters parameters];
    socialParams.title = product.brand;
    socialParams.descriptionText = product.product;
    components.socialMetaTagParameters = socialParams;

    FIRDynamicLinkNavigationInfoParameters *navigationInfoParameters = [FIRDynamicLinkNavigationInfoParameters parameters];
    navigationInfoParameters.forcedRedirectEnabled = 0;
    components.navigationInfoParameters = navigationInfoParameters;

    [components shortenWithCompletion:^(NSURL *_Nullable shortURL,
                                        NSArray *_Nullable warnings,
                                        NSError *_Nullable error) {
        // Handle shortURL or error.
        if (error) {
            NSLog(@"Error generating short link: %@", error.description);
            return;
        }
        shortenURL = shortURL;

        NSString *noteStr = [NSString stringWithFormat:NSLocalizedString(@"Check out %@ %@ on Levooya ! %@", nil), product.brand, product.product, shortenURL];
        UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[noteStr] applicationActivities:nil];
        [self presentViewController:activityVC animated:YES completion:nil];
    }];
}
</code>```

答:
The page you mentioning is App preview page, see https://firebase.google.com/docs/dynamic-links/link-previews .

You can disable this page by specifying a dynamic link parameter efr=1. There is a checkbox when creating link in console to disable this page as well. In your code use navigationInfoParameters.forcedRedirectEnabled = YES;.

Something to keep in mind: If you see App Preview page when your App is already installed on iPhone, this means Universal Links failed to engage. This may happens when dynamic links was pasted to browser address bar. Or tap on link happened inside non-cooperative App (some Apps disallow engagement of Universal Links). Ensure you tested link behavior with App preview disabled and happy with it.

EDIT:
Just realized that your deep link is not correct.
Instead of

```<code>NSString *originalLink = [NSString stringWithFormat:@"https://pbu3y.app.goo.gl/?link=https://levooya.com/product?product_id=%u&isi=1221262097&ibi=com.levooya.LeVooya&product_id=%u", productID, productID];
</code>```

you should use your deep link, like this:

```<code>NSString *originalLink = [NSString stringWithFormat:@"https://levooya.com/product?product_id=%u", productID];
</code>```

Body:
According to Firebase document, I create Dynamic Link in Firebase console, then include the Dynamic Links SDK in my app.

Everything is good, but when I click share link (which is my dynamic link) from facebook or messenger, it popps up a page with a open-app button and ask me if I want to open my app or not.

And I didn't make this page. I want to remove this.

But I click the link from Memorandum, it opens my app and go to the right page directly.  I want the same way with the share links.

Here is my code, I use Xcode with Objective-c to develop iOS app. Thanks!

Appdelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    [FIROptions defaultOptions].deepLinkURLScheme = @"com.levooya.LeVooya";
    [FIRApp configure];
    return YES;
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray * _Nullable))restorationHandler{
    NSURL *url = userActivity.webpageURL;
    NSLog(@"continueUserActivity url.absoluteString:%@",url.absoluteString);

    BOOL handled = [[FIRDynamicLinks dynamicLinks] handleUniversalLink:userActivity.webpageURL completion:^(FIRDynamicLink *dynamicLink, NSError *error){
        if(dynamicLink.url){
            NSLog(@"okokokokokok");
            NSLog(@"dynamicLink.url:%@",dynamicLink.url);

            NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:dynamicLink.url
                                                      resolvingAgainstBaseURL:NO];

            for(NSURLQueryItem *item in urlComponents.queryItems){
                if([item.name isEqualToString:@"product_id"]){
                    NSLog(@"item.value:%@",item.value);
                    NSString *productID = item.value;

                    NSDictionary *urlSchemeDict = [[NSDictionary alloc] init];

                    urlSchemeDict = [NSDictionary dictionaryWithObject:productID forKey:@"product_id"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"URLSchemeShowProduct" object:nil userInfo:urlSchemeDict];

                    leData = [LevooyaData getInstance];
                    leData.urlSchemeDict = nil;
                    leData.urlSchemeDict = urlSchemeDict;
                }
            }
        }
    }];
    return YES;
}

ProductView.m

(This is the page which display product in my app, and here is the function I click share button to generate dynamic link.)

- (void)share{
    NSString *originalLink = [NSString stringWithFormat:@"https://pbu3y.app.goo.gl/?link=https://levooya.com/product?product_id=%u&isi=1221262097&ibi=com.levooya.LeVooya&product_id=%u", productID, productID];
    NSURL *link = [NSURL URLWithString:originalLink];
    FIRDynamicLinkComponents *components =
    [FIRDynamicLinkComponents componentsWithLink:link
                                          domain:@"pbu3y.app.goo.gl"];

    FIRDynamicLinkSocialMetaTagParameters *socialParams = [FIRDynamicLinkSocialMetaTagParameters parameters];
    socialParams.title = product.brand;
    socialParams.descriptionText = product.product;
    components.socialMetaTagParameters = socialParams;

    FIRDynamicLinkNavigationInfoParameters *navigationInfoParameters = [FIRDynamicLinkNavigationInfoParameters parameters];
    navigationInfoParameters.forcedRedirectEnabled = 0;
    components.navigationInfoParameters = navigationInfoParameters;

    [components shortenWithCompletion:^(NSURL *_Nullable shortURL,
                                        NSArray *_Nullable warnings,
                                        NSError *_Nullable error) {
        // Handle shortURL or error.
        if (error) {
            NSLog(@"Error generating short link: %@", error.description);
            return;
        }
        shortenURL = shortURL;

        NSString *noteStr = [NSString stringWithFormat:NSLocalizedString(@"Check out %@ %@ on Levooya ! %@", nil), product.brand, product.product, shortenURL];
        UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[noteStr] applicationActivities:nil];
        [self presentViewController:activityVC animated:YES completion:nil];
    }];
}

Body:
The page you mentioning is App preview page, see https://firebase.google.com/docs/dynamic-links/link-previews .

You can disable this page by specifying a dynamic link parameter efr=1. There is a checkbox when creating link in console to disable this page as well. In your code use navigationInfoParameters.forcedRedirectEnabled = YES;.

Something to keep in mind: If you see App Preview page when your App is already installed on iPhone, this means Universal Links failed to engage. This may happens when dynamic links was pasted to browser address bar. Or tap on link happened inside non-cooperative App (some Apps disallow engagement of Universal Links). Ensure you tested link behavior with App preview disabled and happy with it.

EDIT:
Just realized that your deep link is not correct.
Instead of

NSString *originalLink = [NSString stringWithFormat:@"https://pbu3y.app.goo.gl/?link=https://levooya.com/product?product_id=%u&isi=1221262097&ibi=com.levooya.LeVooya&product_id=%u", productID, productID];

you should use your deep link, like this:

NSString *originalLink = [NSString stringWithFormat:@"https://levooya.com/product?product_id=%u", productID];


问:
How to do for loop through all items of a list except the first
Imagine I have a list of balls objects as follows:

```<code>balls = [container,ball1,ball2,ball3,ball4]
</code>```

I want to do a for loop that will go through ball1, ball2, ball3, ball4 but not the first item container.

What is a method for doing it?

答:
Use list slices:</p>

```<code>for i in balls[1:]:
    print(i)
</code>```

Body:
Imagine I have a list of balls objects as follows:

balls = [container,ball1,ball2,ball3,ball4]

I want to do a for loop that will go through ball1, ball2, ball3, ball4 but not the first item container.

What is a method for doing it?

Body:
Use list slices:

for i in balls[1:]:
    print(i)


问:
How Do I Make Hidden Property In Base Class Get Only
I have the following situation and I want to know how I can make the property SomeNumber to be read only from instances of class A? BTW, I am using C# latest stable build, or not 7.2 c#, so I can't use private protected modifier.

So I don't want to be able to set SomeNumber on accident from class A. I know it can be written in another way to achieve it but can I make the setter in class A's property only visible to class B's property setter? So you can still read SomeNumber from instances of A. Thanks.

I want to to this because I have multiple classes, not only B, derived from class A that hides the base property and they all need to run their own methods when setting SomeNumber.

```<code>class A
{
    private int someNumber;
    internal int SomeNumber
    {
        get { return someNumber; }
        set
        {
            someNumber = value;
            SomethingNotSpecificForDerivedClasses();//I prefer not to move this to each derived setter! There are more derived classes than just B, fyi
        }//I NEED TO MODIFY THE ACCESS OF THIS
    }

    private void SomethingNotSpecificForDerivedClasses()
    {
        ...
    }
}
class B : A
{
    new internal int SomeNumber//hides base member
    {
        get { return base.SomeNumber; }
        set
        {
            base.SomeNumber = value;//ONLY THIS SETTER SHOULD BE ALLOWED TO DO THIS
            SomethingINeedToRunWhenSettingSomeNumber();
        }
    }

    private void SomethingINeedToRunWhenSettingSomeNumber()
    {
        ...
    }
}
</code>```

答:
If you want to run a particular method in the setter perhaps you can simply declare a virtual method?</p>

```<code>public class A
{
    private int _someNumber;

    internal int SomeNumber
    {
        get { return _someNumber; }
        set
        {
            _someNumber = value;
            SomethingINeedToRunWhenSettingSomeNumber();
        }
    }

    protected virtual void SomethingINeedToRunWhenSettingSomeNumber()
    {
        // Do something generic to A.
    }
}

public class B : A
{
    protected override void SomethingINeedToRunWhenSettingSomeNumber()
    {
        base.SomethingINeedToRunWhenSettingSomeNumber();

        // Do something specific to B.
    }
}
</code>```

Body:
I have the following situation and I want to know how I can make the property SomeNumber to be read only from instances of class A? BTW, I am using C# latest stable build, or not 7.2 c#, so I can't use private protected modifier.

So I don't want to be able to set SomeNumber on accident from class A. I know it can be written in another way to achieve it but can I make the setter in class A's property only visible to class B's property setter? So you can still read SomeNumber from instances of A. Thanks.

I want to to this because I have multiple classes, not only B, derived from class A that hides the base property and they all need to run their own methods when setting SomeNumber.

class A
{
    private int someNumber;
    internal int SomeNumber
    {
        get { return someNumber; }
        set
        {
            someNumber = value;
            SomethingNotSpecificForDerivedClasses();//I prefer not to move this to each derived setter! There are more derived classes than just B, fyi
        }//I NEED TO MODIFY THE ACCESS OF THIS
    }

    private void SomethingNotSpecificForDerivedClasses()
    {
        ...
    }
}
class B : A
{
    new internal int SomeNumber//hides base member
    {
        get { return base.SomeNumber; }
        set
        {
            base.SomeNumber = value;//ONLY THIS SETTER SHOULD BE ALLOWED TO DO THIS
            SomethingINeedToRunWhenSettingSomeNumber();
        }
    }

    private void SomethingINeedToRunWhenSettingSomeNumber()
    {
        ...
    }
}

Body:
If you want to run a particular method in the setter perhaps you can simply declare a virtual method?

public class A
{
    private int _someNumber;

    internal int SomeNumber
    {
        get { return _someNumber; }
        set
        {
            _someNumber = value;
            SomethingINeedToRunWhenSettingSomeNumber();
        }
    }

    protected virtual void SomethingINeedToRunWhenSettingSomeNumber()
    {
        // Do something generic to A.
    }
}

public class B : A
{
    protected override void SomethingINeedToRunWhenSettingSomeNumber()
    {
        base.SomethingINeedToRunWhenSettingSomeNumber();

        // Do something specific to B.
    }
}


问:
How to check if a Keyword exists in an Access Query
My question is quite simple but my access database have multiple queries and I want to write an automate process to check if certain keyword exists in any of the queries. This automate process can either be a query or a VBA. Can someone please give me an idea where to start?

Thanks in advance!

答:
I wrote this for a completely different purpose - but it may give you a place to start.  It lookps through all queries, looking for a specific string and replacing it with a different one.</p>

```<code>Function MassChange(F_string, T_string)
Dim DB As Database
Dim QD As QueryDef
Dim S As String

Set DB = CurrentDb
For Each QD In DB.QueryDefs
    S = QD.SQL
    If InStr(S, F_string) > 0 Then
        S = Replace(S, F_string, T_string)
        QD.SQL = S
    End If
Next QD
MsgBox ("done")

End Function
</code>```

Body:
I wrote this for a completely different purpose - but it may give you a place to start.  It lookps through all queries, looking for a specific string and replacing it with a different one.

Function MassChange(F_string, T_string)
Dim DB As Database
Dim QD As QueryDef
Dim S As String

Set DB = CurrentDb
For Each QD In DB.QueryDefs
    S = QD.SQL
    If InStr(S, F_string) > 0 Then
        S = Replace(S, F_string, T_string)
        QD.SQL = S
    End If
Next QD
MsgBox ("done")

End Function


问:
Is Logging Module's thread safety, thread safe on the network as well?
We are dumping log's into a single file with timestamps from multiple computers (500) and each entry is less than 4KB's. Python's logging module apparently handles the locking and guarantees Thread-Safety. https://docs.python.org/2/library/logging.html#thread-safety

Thanks @user2357112 for your feedback, here are some more information:

Are you using some sort of network-attached storage?

The storage is a network disk, which shares a writable logfile.txt that can be read/written.

Are the computers logging things locally and synchronizing their log files somehow?

The computers not logging locally but ones they are finished, they are using the 'Logger' to write to the end of the logfile.txt that is shared

How are log records from different computers ending up in the same file?

All of the computers are appending to logfile.txt

So What can go wrong writing to a single file? Or is it safe to use?

答:
So What can go wrong writing to a single file? Or is it safe to use?

At best, the driver handling file access will lock the file exclusively to one process/user.  At worst, just because you're appending doesn't mean it will be sequential.  for example You mangled lines up with could end  like this.

Perhaps a better/safer approach is just something like /myNas/logs/MMDDYYHH/workerPID.log and then have a daily cleaner script merge all of these into a master.log file.  In an intermediate processing step, you could read each log, put it into a :memory: sqlite database, sort entries by date & time, and dump it into a consolidated master.log.

Alternatively if real time log monitoring is necessary, I believe Windows has equivalent tools like watch which can follow each file as it is written to disk.