问:
Android Studio Soundboard: How to start a loop with a mediaplayer button?
I am trying to use a switch to turn on or off a loop for each button when it plays its sounds.
When the switch is toggled, i want any button i press after that to loop until the switch is toggled off.

I have about 30 buttons and they all have their own setOnClickListener with an mp3 in raw folder.
Initially, i was using soundPool but it stopped working so I switched to MediaPlayer but I haven't had any real success.

My latest change was to use Try and Catch instead of using if but I don't know if it really helped.

```<code>package com.goatman.soundboard;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;

public class MainActivity extends Activity {

public static MediaPlayer mp;

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

    Button playBruh1 = (Button) findViewById(R.id.bruhonebutton);
    Button playBruh2 = (Button) findViewById(R.id.bruhtwobutton);
    Button playBruh3 = (Button) findViewById(R.id.bruhthreebutton);
    Button playNani = (Button) findViewById(R.id.nanibutton);
    Button playYes = (Button) findViewById(R.id.yesbutton);
    Button playAyaya = (Button) findViewById(R.id.ayayabutton);
    Button playTop5BruhMoments = (Button) findViewById(R.id.topfivebruhmomentsbutton);
    Button playTop10NWords = (Button) findViewById(R.id.toptennwordsbutton);
    Button playTop10FunnyWoman = (Button) findViewById(R.id.toptenfunnywomanbutton);
    Button playArab1 = (Button) findViewById(R.id.arabonebutton);
    Button playArab2 = (Button) findViewById(R.id.arabtwobutton);
    Button playArab3 = (Button) findViewById(R.id.arabthreebutton);
    Button playHell1 = (Button) findViewById(R.id.hellonebutton);
    Button playHell2 = (Button) findViewById(R.id.helltwobutton);
    Button playHell3 = (Button) findViewById(R.id.hellthreebutton);
    Button playNWord1 = (Button) findViewById(R.id.nwordonebutton);
    Button playNWord2 = (Button) findViewById(R.id.nwordtwobutton);
    Button playNWord3 = (Button) findViewById(R.id.nwordthreebutton);
    Button playWindows1 = (Button) findViewById(R.id.windowsonebutton);
    Button playWindows2 = (Button) findViewById(R.id.windowstwobutton);
    Button playWindows3 = (Button) findViewById(R.id.windowsthreebutton);
    Button playGun1 = (Button) findViewById(R.id.gunonebutton);
    Button playGun2 = (Button) findViewById(R.id.guntwobutton);
    Button playGun3 = (Button) findViewById(R.id.gunthreebutton);
    Button playFrench1 = (Button) findViewById(R.id.frenchonebutton);
    Button playFrench2 = (Button) findViewById(R.id.frenchtwobutton);
    Button playFrench3 = (Button) findViewById(R.id.frenchthreebutton);
    Button playCBT = (Button) findViewById(R.id.cbtbutton);
    Button playChicken = (Button) findViewById(R.id.chickenbutton);
    Switch playLoop = (Switch) findViewById(R.id.loop);

        playLoop.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.setLooping(true);
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp.start();
            }
        });

        playBruh1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.bruh1);
                mp.start();
            }
        });
        playBruh2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.bruh2);
                mp.start();
            }
        });
        playBruh3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.bruh3);
                mp.start();
            }
        });
        playArab1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.arab1);
                mp.start();
            }
        });
        playArab2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.arab2);
                mp.start();
            }
        });
        playArab3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.arab3);
                mp.start();
            }
        });
        playNani.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.nani);
                mp.start();
            }
        });
        playYes.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.yes);
                mp.start();
            }
        });
        playAyaya.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.ayaya);
                mp.start();
            }
        });
        playTop5BruhMoments.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.top5bruhmoments);
                mp.start();
            }
        });

        playTop10NWords.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    try {
                        mp.stop();
                        mp.release();
                        mp=null;
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    mp = MediaPlayer.create(MainActivity.this, R.raw.top10nwords);
                    mp.start();
                }
            });

        playTop10FunnyWoman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.top10funnywoman);
                mp.start();
            }
        });

        playHell1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.arab2);
                mp.start();
            }
        });

        playHell2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.hell2);
                mp.start();
            }
        });

        playHell3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.hell3);
                mp.start();
            }
        });

        playNWord1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.nword1);
                mp.start();
            }
        });

        playNWord2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.nword2);
                mp.start();
            }
        });

        playNWord3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.nword3);
                mp.start();
            }
        });

        playWindows1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.windows1);
                mp.start();
            }
        });

        playWindows2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.windows2);
                mp.start();
            }
        });

        playWindows3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.arab2);
                mp.start();
            }
        });

        playGun1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.gun1);
                mp.start();
            }
        });

        playGun2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.gun2);
                mp.start();
            }
        });

        playGun3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.gun3);
                mp.start();
            }
        });

        playFrench1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.french1);
                mp.start();
            }
        });

        playFrench2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.french2);
                mp.start();
            }
        });

        playFrench3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.arab2);
                mp.start();
            }
        });

        playCBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.cbt);
                mp.start();
            }
        });

        playChicken.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.chicken);
                mp.start();
            }
        });
    }
}
</code>```

答:
mp.setLooping(true);

Call this before starting a new sound everytime.
I hope this helps :D

Body:
I am trying to use a switch to turn on or off a loop for each button when it plays its sounds.
When the switch is toggled, i want any button i press after that to loop until the switch is toggled off.

I have about 30 buttons and they all have their own setOnClickListener with an mp3 in raw folder.
Initially, i was using soundPool but it stopped working so I switched to MediaPlayer but I haven't had any real success.

My latest change was to use Try and Catch instead of using if but I don't know if it really helped.

package com.goatman.soundboard;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;

public class MainActivity extends Activity {

public static MediaPlayer mp;

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

    Button playBruh1 = (Button) findViewById(R.id.bruhonebutton);
    Button playBruh2 = (Button) findViewById(R.id.bruhtwobutton);
    Button playBruh3 = (Button) findViewById(R.id.bruhthreebutton);
    Button playNani = (Button) findViewById(R.id.nanibutton);
    Button playYes = (Button) findViewById(R.id.yesbutton);
    Button playAyaya = (Button) findViewById(R.id.ayayabutton);
    Button playTop5BruhMoments = (Button) findViewById(R.id.topfivebruhmomentsbutton);
    Button playTop10NWords = (Button) findViewById(R.id.toptennwordsbutton);
    Button playTop10FunnyWoman = (Button) findViewById(R.id.toptenfunnywomanbutton);
    Button playArab1 = (Button) findViewById(R.id.arabonebutton);
    Button playArab2 = (Button) findViewById(R.id.arabtwobutton);
    Button playArab3 = (Button) findViewById(R.id.arabthreebutton);
    Button playHell1 = (Button) findViewById(R.id.hellonebutton);
    Button playHell2 = (Button) findViewById(R.id.helltwobutton);
    Button playHell3 = (Button) findViewById(R.id.hellthreebutton);
    Button playNWord1 = (Button) findViewById(R.id.nwordonebutton);
    Button playNWord2 = (Button) findViewById(R.id.nwordtwobutton);
    Button playNWord3 = (Button) findViewById(R.id.nwordthreebutton);
    Button playWindows1 = (Button) findViewById(R.id.windowsonebutton);
    Button playWindows2 = (Button) findViewById(R.id.windowstwobutton);
    Button playWindows3 = (Button) findViewById(R.id.windowsthreebutton);
    Button playGun1 = (Button) findViewById(R.id.gunonebutton);
    Button playGun2 = (Button) findViewById(R.id.guntwobutton);
    Button playGun3 = (Button) findViewById(R.id.gunthreebutton);
    Button playFrench1 = (Button) findViewById(R.id.frenchonebutton);
    Button playFrench2 = (Button) findViewById(R.id.frenchtwobutton);
    Button playFrench3 = (Button) findViewById(R.id.frenchthreebutton);
    Button playCBT = (Button) findViewById(R.id.cbtbutton);
    Button playChicken = (Button) findViewById(R.id.chickenbutton);
    Switch playLoop = (Switch) findViewById(R.id.loop);

        playLoop.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.setLooping(true);
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp.start();
            }
        });

        playBruh1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.bruh1);
                mp.start();
            }
        });
        playBruh2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.bruh2);
                mp.start();
            }
        });
        playBruh3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.bruh3);
                mp.start();
            }
        });
        playArab1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.arab1);
                mp.start();
            }
        });
        playArab2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.arab2);
                mp.start();
            }
        });
        playArab3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.arab3);
                mp.start();
            }
        });
        playNani.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.nani);
                mp.start();
            }
        });
        playYes.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.yes);
                mp.start();
            }
        });
        playAyaya.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.ayaya);
                mp.start();
            }
        });
        playTop5BruhMoments.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.top5bruhmoments);
                mp.start();
            }
        });

        playTop10NWords.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    try {
                        mp.stop();
                        mp.release();
                        mp=null;
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    mp = MediaPlayer.create(MainActivity.this, R.raw.top10nwords);
                    mp.start();
                }
            });

        playTop10FunnyWoman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.top10funnywoman);
                mp.start();
            }
        });

        playHell1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.arab2);
                mp.start();
            }
        });

        playHell2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.hell2);
                mp.start();
            }
        });

        playHell3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.hell3);
                mp.start();
            }
        });

        playNWord1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.nword1);
                mp.start();
            }
        });

        playNWord2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.nword2);
                mp.start();
            }
        });

        playNWord3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.nword3);
                mp.start();
            }
        });

        playWindows1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.windows1);
                mp.start();
            }
        });

        playWindows2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.windows2);
                mp.start();
            }
        });

        playWindows3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.arab2);
                mp.start();
            }
        });

        playGun1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.gun1);
                mp.start();
            }
        });

        playGun2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.gun2);
                mp.start();
            }
        });

        playGun3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.gun3);
                mp.start();
            }
        });

        playFrench1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.french1);
                mp.start();
            }
        });

        playFrench2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.french2);
                mp.start();
            }
        });

        playFrench3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.arab2);
                mp.start();
            }
        });

        playCBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.cbt);
                mp.start();
            }
        });

        playChicken.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mp.stop();
                    mp.release();
                    mp=null;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                mp = MediaPlayer.create(MainActivity.this, R.raw.chicken);
                mp.start();
            }
        });
    }
}


来源: stackexchange

问:
Input.GetButtonDown("Fire1") working on touch but not with the controllers
I want to rotate an object using a Bluetooth controller in unity scene for Google cardboard. Please tell me how to make controllers work in this case.

```<code> void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            transform.Rotate(transform.rotation.eulerAngles +new Vector3(0f, 0.1f, 0f));
        }
    }
</code>```

Above is the simple code that must work when a 'Down button' in a controller is pressed. This function is working good but only with the touch on the mobile screen not with the controllers.

答: Try by changing type to joystick</p>

ContentLicense: CC BY-SA 4.0

Body:
I want to rotate an object using a Bluetooth controller in unity scene for Google cardboard. Please tell me how to make controllers work in this case.

 void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            transform.Rotate(transform.rotation.eulerAngles +new Vector3(0f, 0.1f, 0f));
        }
    }

Above is the simple code that must work when a 'Down button' in a controller is pressed. This function is working good but only with the touch on the mobile screen not with the controllers.

Body: Try by changing type to joystick


问:
Support for X509PKIPathv1 in xws-security for Spring-WS
I'm trying to send a request to an existing webservice. This webservice is not governed by me. The security policy of this webservice requires me to send my complete certificate chain in my SOAP request. My certificate chain contains 3 certificates. There are no issues with the setup of the certificate chain, as I'm able to test it's validity (and have done so).

The security configuration for this setup (= sending the complete certificate chain in the request), is:

```<code><xwss:Sign id="signature">
   <xwss:X509Token
        certificateAlias="alias"
        keyReferenceType="Direct"
        valueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509PKIPathv1" />
</xwss:Sign>
</code>```

I'm trying to achieve this through Spring-WS. Spring-WS uses spring-ws-security for security. Spring-ws-security delegates to xws-security.

```<code>    <dependency>
        <groupId>org.springframework.ws</groupId>
        <artifactId>spring-ws-security</artifactId>
        <version>2.1.0.RELEASE</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.ws.security</groupId>
                <artifactId>wss4j</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.xml.wsit</groupId>
                <artifactId>xws-security</artifactId>
            </exclusion>
        </exclusions>
     </dependency>
</code>```

Xws-security comes in 2 flavors:

```<code>    <dependency>
        <groupId>com.sun.xml.wsit</groupId>
        <artifactId>xws-security</artifactId>
        <version>1.3.1</version>
    </dependency>
</code>```

and

```<code>    <dependency>
        <groupId>com.sun.xml.wss</groupId>
        <artifactId>xws-security</artifactId>
        <version>3.0</version>
    </dependency>
</code>```

The first one is used by Spring WS Security. The second is legacy.

Applying my XWSS configuration in xws-security is done in a class called BinarySecurityToken. BinarySecurityToken has a field called

```<code>valueType
</code>```

The JavaDoc of valueType says it has support for X509PKIPathv1 (among others). However, it does not, as stated by this setter:

```<code>    protected void setValueType(String valueType) {
    if (!(MessageConstants.X509v3_NS.equals(valueType)||MessageConstants.X509v1_NS.equals(valueType))) {
        log.log(Level.SEVERE,"WSS0342.valtype.invalid");
        throw new RuntimeException("Unsupported value type: " + valueType);
    }
    this.valueType = valueType;
}
</code>```

The class MessageConstants does not (even) have a static for X509PKIPathv1. When I run my code, I get the expected result:

```<code>Unsupported value type: http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509PKIPathv1
</code>```

I was able to look at the source code of the legacy com.sun.xml.wss.xws-security:3.0. Despite my efforts, I have not found the source code of com.sun.xml.wsit.xws-security-1.3.1. However I believe the code is the same. I tried both libraries and both give me the same exception. I tried it, using the default spring-ws-security and using explicit dependency declarations to both libraries (one at a time).

My questions:

Has anyone been able to use xws-security for generating an X509 signature with a valueType of X509PKIPathv1 and a keyReferenceType that is Direct?

Do other xws-security implementations exist that offer this? Or should I look at a completely different approach like Wss4j?

I have considered re-writing BinarySecurityToken, but that would probably also imply rewriting the X509 signing of SignatureProcessor in DSIG.

答: This pull request will enable the ability to use X509PKIPathv1.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to send a request to an existing webservice. This webservice is not governed by me. The security policy of this webservice requires me to send my complete certificate chain in my SOAP request. My certificate chain contains 3 certificates. There are no issues with the setup of the certificate chain, as I'm able to test it's validity (and have done so).

The security configuration for this setup (= sending the complete certificate chain in the request), is:

<xwss:Sign id="signature">
   <xwss:X509Token
        certificateAlias="alias"
        keyReferenceType="Direct"
        valueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509PKIPathv1" />
</xwss:Sign>

I'm trying to achieve this through Spring-WS. Spring-WS uses spring-ws-security for security. Spring-ws-security delegates to xws-security.

    <dependency>
        <groupId>org.springframework.ws</groupId>
        <artifactId>spring-ws-security</artifactId>
        <version>2.1.0.RELEASE</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.ws.security</groupId>
                <artifactId>wss4j</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.xml.wsit</groupId>
                <artifactId>xws-security</artifactId>
            </exclusion>
        </exclusions>
     </dependency>

Xws-security comes in 2 flavors:

    <dependency>
        <groupId>com.sun.xml.wsit</groupId>
        <artifactId>xws-security</artifactId>
        <version>1.3.1</version>
    </dependency>

and

    <dependency>
        <groupId>com.sun.xml.wss</groupId>
        <artifactId>xws-security</artifactId>
        <version>3.0</version>
    </dependency>

The first one is used by Spring WS Security. The second is legacy.

Applying my XWSS configuration in xws-security is done in a class called BinarySecurityToken. BinarySecurityToken has a field called

valueType

The JavaDoc of valueType says it has support for X509PKIPathv1 (among others). However, it does not, as stated by this setter:

    protected void setValueType(String valueType) {
    if (!(MessageConstants.X509v3_NS.equals(valueType)||MessageConstants.X509v1_NS.equals(valueType))) {
        log.log(Level.SEVERE,"WSS0342.valtype.invalid");
        throw new RuntimeException("Unsupported value type: " + valueType);
    }
    this.valueType = valueType;
}

The class MessageConstants does not (even) have a static for X509PKIPathv1. When I run my code, I get the expected result:

Unsupported value type: http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509PKIPathv1

I was able to look at the source code of the legacy com.sun.xml.wss.xws-security:3.0. Despite my efforts, I have not found the source code of com.sun.xml.wsit.xws-security-1.3.1. However I believe the code is the same. I tried both libraries and both give me the same exception. I tried it, using the default spring-ws-security and using explicit dependency declarations to both libraries (one at a time).

My questions:

Has anyone been able to use xws-security for generating an X509 signature with a valueType of X509PKIPathv1 and a keyReferenceType that is Direct?

Do other xws-security implementations exist that offer this? Or should I look at a completely different approach like Wss4j?

I have considered re-writing BinarySecurityToken, but that would probably also imply rewriting the X509 signing of SignatureProcessor in DSIG.


问:
Unable to open PDF file through intent programmatically in android
I have an app where on button click, access should be provided to browse and open the PDF files stored in the internal memory of the device.I tried various codes but i get an toast saying "Cannot display PDF". I don't get any errors in logs. I use android version 7.0 device. Attached my code below: please help:

```<code>File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
</code>```

I have included this in Oncreate:

```<code>StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
</code>```

This is how called the method:

```<code>  linear_pdf.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pdf.setTextColor(getActivity().getResources().getColor(R.color.colorWhite));

                            openPdf(getContext(), Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");

                            communication.dismiss();
                        }
                    });
</code>```

答:
For opening pdf file from local storage add prefix in url.</p>

```<code>private void openPdf(File file) {

        try {

            String url = file.getAbsolutePath();

            String u = "file:///" + url;

            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(u));
            startActivity(i);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
</code>```

Body:
I have an app where on button click, access should be provided to browse and open the PDF files stored in the internal memory of the device.I tried various codes but i get an toast saying "Cannot display PDF". I don't get any errors in logs. I use android version 7.0 device. Attached my code below: please help:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);

I have included this in Oncreate:

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

This is how called the method:

  linear_pdf.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            pdf.setTextColor(getActivity().getResources().getColor(R.color.colorWhite));

                            openPdf(getContext(), Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");

                            communication.dismiss();
                        }
                    });

Body:
For opening pdf file from local storage add prefix in url.

private void openPdf(File file) {

        try {

            String url = file.getAbsolutePath();

            String u = "file:///" + url;

            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(u));
            startActivity(i);

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


问:
Call dynamic data in Wordpress
I am trying to populate a value depending on the user role.

There are two ways to do this:

Add 600 lines in functions.PHP with then statements, (if user role=1 echo 1..... if user role=600 echo 600)

OR

Add a new meta value in the SQL database for the user upon registration and request this value from the data base.

I think the second option is more logical (unless the first option will bring a faster loading speed?)

Can anyone advice how can I request a parameter from a database in-line with the current user.

答:
Hope this help you.</p>

```<code>$user = wp_get_current_user();
$user_id = $user->ID;
$get_portal_number = get_user_meta($user_id, 'portal_number', true);
print_r($get_portal_number);
</code>```

Title: Call dynamic data in Wordpress

Body:
Hope this help you.

$user = wp_get_current_user();
$user_id = $user->ID;
$get_portal_number = get_user_meta($user_id, 'portal_number', true);
print_r($get_portal_number);


问:
Is there a risk that Apple will not accept me as an applied iPhone Developer (with paid membership)?
What does it mean that I have to "apply"? Can day say: "No, we don't like your nose. Do something else!"? Did they do that in the past?

I've been investing now two full months worth about 20.000 USD on learning for iPhone programming, and I didn't apply yet...

答: Apple has a right to not accept your app at their wish, so you have to take a risk.</p>

OwnerDisplayName: Unknown Individual

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Stephen Pape

OwnerDisplayName: Marko


问:
big dotted geom_line, but dots closer together
I am curious if it is possible to increase the size of dots on a dotted line within geom_line but keep the dots closer together. The R code below produces a basic reproducible example of what I see, and then I include another chart showing what I would like to see.

```<code>library(dplyr)
library(ggplot2)
set.seed(5223)
myDF <- data.frame(x=rnorm(20,0,1),
                   y=runif(20,0,20))
myDF <- myDF %>%
  mutate(From8to12 = y>=8 & y<=12)

ggplot(myDF,aes(x=x,y=y,col=From8to12)) +
  geom_point() +
  geom_hline(yintercept=8,lty="dotted") +
  geom_hline(yintercept=12,lty="dotted",size=1.5)
</code>```

Unedited Image

(Manually) Edited Image (In Paint)

I would like to make the dots bigger, but closer together. Is this possible? I've found nothing online.

答:
Edit
I thought it wasn't possible without some severe hacking of the underlying draw functions - @StupidWolf's answer proved me wrong. My suggestion was to draw every single point with geom_point and shape = 15 (filled square). It is then a matter of your final plot size, what parameters you chose (i.e., the distance between the 'dots' and their size)

P.S. It's impressive that you have actually managed to produce your image in paint.

library(tidyverse)
set.seed(5223)
myDF <- data.frame(x = rnorm(20, 0, 1), y = runif(20, 0, 20))

dot_dis <- 0.05
x_line <- seq(min(myDF$x), max(myDF$x), dot_dis)
y_line <- 12

ggplot() +
  geom_point(aes(x, y), data = myDF) +
  geom_point(aes(x_line, y_line), shape = 15, size = 1.5)
```

Created on 2020-02-18 by the reprex package (v0.3.0)

Body:
I am curious if it is possible to increase the size of dots on a dotted line within geom_line but keep the dots closer together. The R code below produces a basic reproducible example of what I see, and then I include another chart showing what I would like to see.

library(dplyr)
library(ggplot2)
set.seed(5223)
myDF <- data.frame(x=rnorm(20,0,1),
                   y=runif(20,0,20))
myDF <- myDF %>%
  mutate(From8to12 = y>=8 & y<=12)

ggplot(myDF,aes(x=x,y=y,col=From8to12)) +
  geom_point() +
  geom_hline(yintercept=8,lty="dotted") +
  geom_hline(yintercept=12,lty="dotted",size=1.5)

Unedited Image

(Manually) Edited Image (In Paint)

I would like to make the dots bigger, but closer together. Is this possible? I've found nothing online.

Body:
Edit
I thought it wasn't possible without some severe hacking of the underlying draw functions - @StupidWolf's answer proved me wrong. My suggestion was to draw every single point with geom_point and shape = 15 (filled square). It is then a matter of your final plot size, what parameters you chose (i.e., the distance between the 'dots' and their size)

P.S. It's impressive that you have actually managed to produce your image in paint.

library(tidyverse)
set.seed(5223)
myDF <- data.frame(x = rnorm(20, 0, 1), y = runif(20, 0, 20))

dot_dis <- 0.05
x_line <- seq(min(myDF$x), max(myDF$x), dot_dis)
y_line <- 12

ggplot() +
  geom_point(aes(x, y), data = myDF) +
  geom_point(aes(x_line, y_line), shape = 15, size = 1.5)

Created on 2020-02-18 by the reprex package (v0.3.0)


问:
My JQuery is running in a loop. Uncaught RangeError: Maximum call stack size exceeded
Here is my code,

```<code> $('#code').change(function() {
     $('select[name="country_code"]').on('change', function() {
        var countryCode = $('#code').val();
        console.log(countryCode);
      $('select[name="country"]').prop("disabled", false);
        $('select[name="country"]').val(countryCode).trigger('change');

    });
 });

$('#country').change(function() {
     $('select[name="country"]').on('change', function() {
      var countryName = $('#country').val();
      console.log(countryName);
      $('select[name="country_code"]').prop("disabled", false);
      $('select[name="country_code"]').val(countryName).trigger('change');
    });
 });
</code>```

The country should automatically get fetched and show in select option when I change the Country code. This is working perfectly, but When I console this is running endlessly and an error "Uncaught RangeError: Maximum call stack size exceeded" coming.

Thanks in Advance!!!

答:
try to put this event outside:

$('select[name="country"]').on('change', function() {
      var countryName = $('#country').val();
      console.log(countryName);
      $('select[name="country_code"]').prop("disabled", false);
      $('select[name="country_code"]').val(countryName).trigger('change');
    });```
</div>
</div>
</p>

<p>after that use trigger function to call the event:</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>$('#country').change(function() {
     $('select[name="country"]').trigger('change');
});</code>```

Body:
Here is my code,

 $('#code').change(function() {
     $('select[name="country_code"]').on('change', function() {
        var countryCode = $('#code').val();
        console.log(countryCode);
      $('select[name="country"]').prop("disabled", false);
        $('select[name="country"]').val(countryCode).trigger('change');

    });
 });

$('#country').change(function() {
     $('select[name="country"]').on('change', function() {
      var countryName = $('#country').val();
      console.log(countryName);
      $('select[name="country_code"]').prop("disabled", false);
      $('select[name="country_code"]').val(countryName).trigger('change');
    });
 });

The country should automatically get fetched and show in select option when I change the Country code. This is working perfectly, but When I console this is running endlessly and an error "Uncaught RangeError: Maximum call stack size exceeded" coming.

Thanks in Advance!!!

Body:
try to put this event outside:

$('select[name="country"]').on('change', function() {
      var countryName = $('#country').val();
      console.log(countryName);
      $('select[name="country_code"]').prop("disabled", false);
      $('select[name="country_code"]').val(countryName).trigger('change');
    });

after that use trigger function to call the event:

$('#country').change(function() {
     $('select[name="country"]').trigger('change');
});


问:
Select two different Items if they meet different condition
I have a select problem with mssql which is;

```<code>Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123
3               C           123

Table A (All Invoices)
ItemUniqueNo   ItemName   InvoceNo
1               A           123
2               B           235
3               C           123

Table B (Item List)
ItemUniqueNo    ItemName    ItemGroup
1               A           XXX
2               B           YYY
3               C           ZZZ
</code>```

I want to select every items (from Table A) If an invoice has both type of product which is; ItemUniqueNo=3 and ItemGroup = XXX, in same invoice. Here is my code:

```<code>SELECT
*
FROM
TABLE_A
WHERE
(ItemUniqueNo IN (SELECT ItemUniqueNo FROM TABLE_B WHERE ItemGroup='XXX') OR ItemUniqueNo = 3)
</code>```

with this code, I've listed all items which has either ItemGroup = XXX and ItemUniqueNo=3 BUT
I want to meet both condition in same invoice, like:

```<code>Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123  --->  This meets 'XXX' ItemGroup condition
3               C           123  --->  This meets '3' ItemUniqueNo condition
</code>```

This invoice meet both 2 condition, so i want to list this two item with InvoceNo.
AND all other items which meet this condition.

答:
If you want to fulfill both conditions at once use AND keyword.  If you want to fulfill only one condition out of two, use OR keyword. </p>

```<code>SELECT *
FROM TABLE_A
WHERE ItemUniqueNo IN
(SELECT ItemUniqueNo
FROM TABLE_B
WHERE ItemGroup='XXX' AND ItemUniqueNo = 3)
</code>```

Body:
I have a select problem with mssql which is;

Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123
3               C           123

Table A (All Invoices)
ItemUniqueNo   ItemName   InvoceNo
1               A           123
2               B           235
3               C           123

Table B (Item List)
ItemUniqueNo    ItemName    ItemGroup
1               A           XXX
2               B           YYY
3               C           ZZZ

I want to select every items (from Table A) If an invoice has both type of product which is; ItemUniqueNo=3 and ItemGroup = XXX, in same invoice. Here is my code:

SELECT
*
FROM
TABLE_A
WHERE
(ItemUniqueNo IN (SELECT ItemUniqueNo FROM TABLE_B WHERE ItemGroup='XXX') OR ItemUniqueNo = 3)

with this code, I've listed all items which has either ItemGroup = XXX and ItemUniqueNo=3 BUT
I want to meet both condition in same invoice, like:

Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123  --->  This meets 'XXX' ItemGroup condition
3               C           123  --->  This meets '3' ItemUniqueNo condition

This invoice meet both 2 condition, so i want to list this two item with InvoceNo.
AND all other items which meet this condition.

Body:
If you want to fulfill both conditions at once use AND keyword.  If you want to fulfill only one condition out of two, use OR keyword.

SELECT *
FROM TABLE_A
WHERE ItemUniqueNo IN
(SELECT ItemUniqueNo
FROM TABLE_B
WHERE ItemGroup='XXX' AND ItemUniqueNo = 3)


问:
Azure DevOps set MultiLine Row parameter
Is it possible to set the multiLine row parameter in the task.json file for a custom task?

```<code>{
    "name":  "Include",
    "type":  "multiLine",
    "label":  "Include",
    "defaultValue":  "@(\"*.sln\")",
    "required":  false,
    "helpMarkDown":  "example help"
}
</code>```

I recocnize, that the only difference between a multiLine textbox and inline textbox (PowerShell Task) is the amount of rows:

The default amount of rows of a multiLine textbox is 2.

So it would be create to define the amount a rows in a multiLine control.

答:
Is it possible to set the multiLine row parameter in the task.json
  file for a custom task?

It's possible. Use .net core task have a textbox Path to projects:

Corresponding html see here:

Which is default rows of MultiLine type.

So I compared the source of Use .net core task and PS task here and found:

```<code>       {
            "name": "projects",
            "type": "multiLine",
            "label": "Path to project(s)",
            "defaultValue": "",
            "visibleRule": "command = build || command = restore || command = run || command = test || command = custom || publishWebProjects = false",
            "required": false,
            "helpMarkDown": "The path to the csproj file(s) to use. You can use wildcards (e.g. **/*.csproj for all .csproj files in all subfolders)."
        }
</code>```

and this:

```<code>        {
            "name": "script",
            "type": "multiLine",
            "label": "Script",
            "visibleRule": "targetType = inline",
            "required": true,
            "defaultValue": "# Write your PowerShell commands here.\n\nWrite-Host \"Hello World\"\n",
            "properties": {
                "resizable": "true",
                "rows": "10",
                "maxLength": "20000"
            },
            "helpMarkDown": ""
        }
</code>```

The first script comes from dotnet task and second one comes from PS task. They both use MultiLine type.

According to the difference between these two scripts I think you can get what you want by setting the rows element in properties element. Something like this:

```<code>    "properties": {
        ...,
        "rows": "xxx",
        ...
    }
</code>```

Hope it helps and if I misunderstand anything, feel free to correct me :)

Body:
Is it possible to set the multiLine row parameter in the task.json file for a custom task?

{
    "name":  "Include",
    "type":  "multiLine",
    "label":  "Include",
    "defaultValue":  "@(\"*.sln\")",
    "required":  false,
    "helpMarkDown":  "example help"
}

I recocnize, that the only difference between a multiLine textbox and inline textbox (PowerShell Task) is the amount of rows:

The default amount of rows of a multiLine textbox is 2.

So it would be create to define the amount a rows in a multiLine control.

Body:
Is it possible to set the multiLine row parameter in the task.json
  file for a custom task?

It's possible. Use .net core task have a textbox Path to projects:

Corresponding html see here:

Which is default rows of MultiLine type.

So I compared the source of Use .net core task and PS task here and found:

       {
            "name": "projects",
            "type": "multiLine",
            "label": "Path to project(s)",
            "defaultValue": "",
            "visibleRule": "command = build || command = restore || command = run || command = test || command = custom || publishWebProjects = false",
            "required": false,
            "helpMarkDown": "The path to the csproj file(s) to use. You can use wildcards (e.g. **/*.csproj for all .csproj files in all subfolders)."
        }

and this:

        {
            "name": "script",
            "type": "multiLine",
            "label": "Script",
            "visibleRule": "targetType = inline",
            "required": true,
            "defaultValue": "# Write your PowerShell commands here.\n\nWrite-Host \"Hello World\"\n",
            "properties": {
                "resizable": "true",
                "rows": "10",
                "maxLength": "20000"
            },
            "helpMarkDown": ""
        }

The first script comes from dotnet task and second one comes from PS task. They both use MultiLine type.

According to the difference between these two scripts I think you can get what you want by setting the rows element in properties element. Something like this:

    "properties": {
        ...,
        "rows": "xxx",
        ...
    }

Hope it helps and if I misunderstand anything, feel free to correct me :)


问:
Can't resolve module (not found) in React.js
I can't believe that I'm asking an obvious question, but I still get the error in console log.

Console says that it can't find the module in the directory, but I've checked at least 10 times for typos. Anyways, here's the component code.

I want to render Header in root

```<code>import React, { Component } from 'react'
import Header from './src/components/header/header'
import logo from './logo.svg'
import './App.css'

class App extends Component {
  render() {
    return (
      <Header/>
    );
  }
}

export default App;
</code>```

This is the Header component

```<code>import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import navBar from './src/components/header/navBar'
import './src/css/header.css'

class Header extends Component {
    render() {
        return {
            <div>
             <div id="particles-js"></div>
             <navBar/>
             <Title/>
          </div>
        };
    }
}

ReactDOM.render(<Header/>, document.getElementById('header'));
</code>```

I've checked at least 10 times that the module is at this location ./src/components/header/header, and it is (folder "header" contains "header.js").

Yet, React still throws this error:

Failed to compile

./src/App.js
Module not found: Can't resolve './src/components/header/header' in '/home/wiseman/Desktop/React_Components/github-portfolio/src'

npm test says the same thing.

答:
Deleted the package-lock.json file & then ran

```<code>npm install
</code>```

Read further

Body:
I can't believe that I'm asking an obvious question, but I still get the error in console log.

Console says that it can't find the module in the directory, but I've checked at least 10 times for typos. Anyways, here's the component code.

I want to render Header in root

import React, { Component } from 'react'
import Header from './src/components/header/header'
import logo from './logo.svg'
import './App.css'

class App extends Component {
  render() {
    return (

    );
  }
}

export default App;

This is the Header component

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import navBar from './src/components/header/navBar'
import './src/css/header.css'

class Header extends Component {
    render() {
        return {

             <navBar/>
             <Title/>

        };
    }
}

ReactDOM.render(, document.getElementById('header'));

I've checked at least 10 times that the module is at this location ./src/components/header/header, and it is (folder "header" contains "header.js").

Yet, React still throws this error:

Failed to compile

./src/App.js
Module not found: Can't resolve './src/components/header/header' in '/home/wiseman/Desktop/React_Components/github-portfolio/src'

npm test says the same thing.

Body:
Deleted the package-lock.json file & then ran

npm install

Read further


问:
Safari iframe's service worker loops infinitely and iframe is a white screen (not in other browsers, not in a new tab)
I have 2 webapplications build in vue. One application is some sort of wrapper for all the applications a company has and it loads several projects via an iframe (And one of them is the other web-application build in vue).

Both projects have the vue-pwa plugin installed.
When opening the wrapper project in the safari browser on a mac and browsing to the iframe with the other vue application the screen is blank and i'm seeing that there are an unlimited count of console.logs: Service worker has been registered. from the register hook in the registerServiceWorker.js

The moment i open the contents of that iframe in a seccond tab of safari, these console.logs stop and the page is normally loaded and functioning.

Does anyone have an idea for a solution, or how to debug what the issue is?

答:
The issue was that i needed to set the header X-Frame-Options: ALLOW-FROM https://example.com/
Weird thing is that the code was executed, it was just not visible. And other browsers don't seem to bother that since there was no X-Frame-Options that blocked it.


问:
Differentiate two Angular components created by the same parent
I have a modal component that only shows a message and an accept button.

The accept button will perform a function depending on who has called you.

The same component could create several modals (showed in diferent moments).

The problem I have is that to open the modal I have to call it by its id, but all modals are created with the same id. I had thought of creating a unique id for each one by passing it through the @Input decorator, but because it is a large application, two developers may call it in the same way and create conflicts.

How could I create a unique id for each element without having to pass it on as @Input?

I try to do an exemple, but have problems with jquery.

In any case here is the attempt

https://stackblitz.com/edit/angular-gvqdzc

答:
I have found a solution although it seems some confusing.

In the directive I add an ngif so that it is available only if a certain value.

```<code><confirmation-modal *ngIf="expression == 'roles'" [header]="'ARE_YOU_SURE'" [message]="'SENDED_MESSAGE'" (launchAction)="modal1Accepted()">
</code>```

And then in the modal opening function, I have to put the opening function in a setTimeout() because otherwise it cannot be found.

```<code>openRolesModal() {
this.expression = 'roles';
let modal = '#selectAttributtesModal';
setTimeout(() => $(modal).modal('show'), 100);
}
</code>```

Body:
I have found a solution although it seems some confusing.

In the directive I add an ngif so that it is available only if a certain value.

<confirmation-modal *ngIf="expression == 'roles'" [header]="'ARE_YOU_SURE'" [message]="'SENDED_MESSAGE'" (launchAction)="modal1Accepted()">

And then in the modal opening function, I have to put the opening function in a setTimeout() because otherwise it cannot be found.

openRolesModal() {
this.expression = 'roles';
let modal = '#selectAttributtesModal';
setTimeout(() => $(modal).modal('show'), 100);
}


问:
Qt could not find the platform plugin cocoa
I'm experimenting a little bit with Qt. I have successfully written a small app which works fine on my Windows 8.1 Laptop. Now I installed XCode and Qt and copied the project folder to my MacBook. The application compiles fine on my Mac but when I wan't to run it via Qt Creator I'm getting the following errors:

```<code>[qt.qpa.plugin] Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstall application may fix this problem.
</code>```

I have read that the tool macdeployqt is needed when I want to deploy the app to other PCs. But shouldn't my application run without macdeployqt when I execute it directly with the Qt Creator?

I'm using MacOS X 10.14 with Qt 5.11.3. Xcode 10 and the MacOSX SDK 10.13 is installed and setted up correctly (at least it compiles with this SDK and without any error).

Does anyone has an idea?

答:
If you are on Mac, go to the Terminal and paste the following:

pip3 install opencv-python-headless
```

The Qt platform plugin requires this library to be installed.

Thanks!

Body:
I'm experimenting a little bit with Qt. I have successfully written a small app which works fine on my Windows 8.1 Laptop. Now I installed XCode and Qt and copied the project folder to my MacBook. The application compiles fine on my Mac but when I wan't to run it via Qt Creator I'm getting the following errors:

[qt.qpa.plugin] Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstall application may fix this problem.

I have read that the tool macdeployqt is needed when I want to deploy the app to other PCs. But shouldn't my application run without macdeployqt when I execute it directly with the Qt Creator?

I'm using MacOS X 10.14 with Qt 5.11.3. Xcode 10 and the MacOSX SDK 10.13 is installed and setted up correctly (at least it compiles with this SDK and without any error).

Does anyone has an idea?

Body:
If you are on Mac, go to the Terminal and paste the following:

pip3 install opencv-python-headless

The Qt platform plugin requires this library to be installed.

Thanks!


问:
Displaying XML in human readable format
I have some medical records files which have this in the header:

ClinicalDocument xsi:schemaLocation="urn:hl7-org:v3 CDA.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:voc="urn:hl7-org:v3/voc" xmlns:sdtc="urn:hl7-org:sdtc" xmlns="urn:hl7-org:v3">

I would like to view them in a human readable format, in any of PDF, Word, or even in Excel.

I can't figure out how to get the appropriate "stylesheet", assuming this is what I am missing.

This is what I have tried:

1) If I open the file in a browser, I get the formatted XML with a message that says
"This XML file does not appear to have any style information associated with it. The document tree is shown below."

2) I have tried googling for the file CDA.xsd and I went through this page http://motorcycleguy.blogspot.com/2010/07/where-is-xsd-for-ccd.html which had a couple of links which gave me some large tar files which I couldn't figure out how to use.  One of them had a C32_CDA.xsd but when I rename that to CDA.xsd and put it in the same folder as my XML and then try to open it via Excel I cannot get it to display properly.

Any assistance would be most appreciated.

答:
To display an XML document in human-readable format you need (typically) an XSLT stylesheet. It seems your XML is in a vocabulary called HL7 (health level 7?). I don't know much about HL7 except that it has a reputation for being very complex, so it's quite likely that the stylesheets needed will also be very complex.

A quick google showed a project for creating HL7 stylesheets here:

https://wiki.hl7.org/index.php?title=CDA_R2.1_Stylesheet_Project

You might find something there that is useful to you.

Title: Displaying XML in human readable format


问:
User form combo box size - VBA
I have a user form which includes many combo boxes and i m wondering if there is a way to decrease the size of each line in a drop down list.  As you can see in the image below the size of the row are very big in comparison with the word size and the top part of the combo box. after change Listwidth property a scroll bar appears in the combo box.

Combo box values are imported using loop. Any suggestions?

Combo Box

After changing Listwidth propert

答:
You can use the .ListWidth property. The units it uses are pt.

You can either set this at design time in the properties pane, or at run-time using code:

```<code>ComboBox1.ListWidth = 20
</code>```

You can also change the .ColumnWidths property if you do not want the horizontal scrollbar to display.

Title: User form combo box size - VBA

Body:
You can use the .ListWidth property. The units it uses are pt.

You can either set this at design time in the properties pane, or at run-time using code:

ComboBox1.ListWidth = 20

You can also change the .ColumnWidths property if you do not want the horizontal scrollbar to display.


问:
pushing multi dimentional array within array js
I have declared an array variable and I want to push new data but it doesn't work. below is my code

```<code>let locations = [
  [2.4333,4.45333],
  [3.45454,5.222325]
]
</code>```

here is the code pushing to locations variable

```<code> for (var j=0;j<res.length;j++) {
    locations.push([res[j]['lat'], res[j]['long']])
    //4.3333, 4.33444
 }
</code>```

and this is the code to display

```<code>for (i = 0; i < locations.length; i++) {
  position: new google.maps.LatLng(locations[i][0], locations[i][1])
}
</code>```

This is what I'm getting in console log

```<code>> Array[]
console.log(locations.length)// 0
</code>```

Thanks

答:
With some assumptions.

var res = [{ lat: 1234, long: 4567 }, { lat: 2234, long: 5567 }];
var locations = [
    [2.4333, 4.45333],
    [3.45454, 5.222325]
];
for (var j = 0; j < res.length; j++) {
    locations.push([res[j]['lat'], res[j]['long']])
}
console.log(locations);```

Body:
I have declared an array variable and I want to push new data but it doesn't work. below is my code

let locations = [
  [2.4333,4.45333],
  [3.45454,5.222325]
]

here is the code pushing to locations variable

 for (var j=0;j<res.length;j++) {
    locations.push([res[j]['lat'], res[j]['long']])
    //4.3333, 4.33444
 }

and this is the code to display

for (i = 0; i < locations.length; i++) {
  position: new google.maps.LatLng(locations[i][0], locations[i][1])
}

This is what I'm getting in console log

> Array[]
console.log(locations.length)// 0

Thanks


问:
Mongo DB Limit with aggregate
I have one document show below data have status with Item name

```<code>{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9d4"),
    "item" : "Item_1",
    "status" : 1
}
{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9d5"),
    "item" : "Item_2",
    "status" : 1
}
{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9d6"),
    "item" : "Item_3",
    "status" : 1
}

.....

{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9de"),
    "item" : "Item_11",
    "status" : 3
}
{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9df"),
    "item" : "Item_12",
    "status" : 3
}
</code>```

I need to select all data with below condition.
 1. Display all unique status.
 2. every unique Status have data array of their own data with 2 data limit.

```<code>{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9d7"),
    "status" : 1,
    "data" : [
        {
            "_id" : ObjectId("5e4aaf6f9588116a6b36e9d4"),
            "item" : "Item_1",
            "status" : 1
        },
        {
            "_id" : ObjectId("5e4aaf6f9588116a6b36e9d5"),
            "item" : "Item_2",
            "status" : 1
        }
    ]
},
........
{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9dd"),
    "status" : 3,
    "data" : [
        {
            "_id" : ObjectId("5e4aaf6f9588116a6b36e9dd"),
            "item" : "Item_10",
            "status" : 3
        },
        {
            "_id" : ObjectId("5e4aaf6f9588116a6b36e9de"),
            "item" : "Item_11",
            "status" : 3
        }
    ]
}
</code>```

Please help me. I'm new in mongoDB.

Thanks,

答:
You need to use $group

```<code>db.collection.aggregate([
  {
    "$group": {
      _id: "$status",
      status: { "$first": "$status" },
      data: { $push: "$$ROOT" } }
  },
  { "$addFields": { data: { $slice: [ "$data", 2 ] } } }
])
</code>```

Mongo Playground

Title: Mongo DB Limit with aggregate

Body:
I have one document show below data have status with Item name

{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9d4"),
    "item" : "Item_1",
    "status" : 1
}
{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9d5"),
    "item" : "Item_2",
    "status" : 1
}
{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9d6"),
    "item" : "Item_3",
    "status" : 1
}

.....

{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9de"),
    "item" : "Item_11",
    "status" : 3
}
{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9df"),
    "item" : "Item_12",
    "status" : 3
}

I need to select all data with below condition.
 1. Display all unique status.
 2. every unique Status have data array of their own data with 2 data limit.

{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9d7"),
    "status" : 1,
    "data" : [
        {
            "_id" : ObjectId("5e4aaf6f9588116a6b36e9d4"),
            "item" : "Item_1",
            "status" : 1
        },
        {
            "_id" : ObjectId("5e4aaf6f9588116a6b36e9d5"),
            "item" : "Item_2",
            "status" : 1
        }
    ]
},
........
{
    "_id" : ObjectId("5e4aaf6f9588116a6b36e9dd"),
    "status" : 3,
    "data" : [
        {
            "_id" : ObjectId("5e4aaf6f9588116a6b36e9dd"),
            "item" : "Item_10",
            "status" : 3
        },
        {
            "_id" : ObjectId("5e4aaf6f9588116a6b36e9de"),
            "item" : "Item_11",
            "status" : 3
        }
    ]
}

Please help me. I'm new in mongoDB.

Thanks,

Body:
You need to use $group

db.collection.aggregate([
  {
    "$group": {
      _id: "$status",
      status: { "$first": "$status" },
      data: { $push: "$$ROOT" } }
  },
  { "$addFields": { data: { $slice: [ "$data", 2 ] } } }
])

Mongo Playground


问:
Is it forbidden to use static methods in factory pattern?
I got told that using static methods when implementing the factory-method-pattern is wrong and should be avoided. Because I wasn't really familiar with the pattern I accepted that answer.

After reading articles and getting deeper into it, I couldn't find any source which supports this statement.

Can someone help me out with this situation. Should I avoid the static-keyword in factory-methods and if so, when are they useful?

答:
An increasingly popular definition of factory method is: a static method of a class that returns an object of that class' type. But unlike a constructor, the actual object it returns might be an instance of a subclass.

source: https://sourcemaking.com/design_patterns/factory_method

As far as I know, Its ok to use static on factory method. But @Serge Ballesta* has a good point in the comment.


问:
Using orWhere in a multiple where query builder Laravel
I want to select from database pads with 4 conditions, with 1 condition have to use "or". I wrote this query builder, it works. But I want to know if i can use a shorter query. Like use 3 conditions in a "where" brackets, and 1 in "orWhere" bracket. This is my query:</p>

```<code>$pads = DB::table('pads')
    ->join('languages', 'pads.language_id', '=', 'languages.id')
    ->select('pads.id', 'pads.title', 'pads.status', 'pads.people', 'pads.created_at', 'languages.name as language')
    ->where([
        ['pads.user_id', Auth::user()->id],
        ['pads.title', 'LIKE', "%{$request->search}%"],
        ['pads.status', $request->status],
        ['pads.language_id', $request->lg_id]
    ])
    ->orWhere([
        ['pads.user_id', Auth::user()->id],
        ['pads.people', 'LIKE', "%{$request->search}%"],
        ['pads.status', $request->status],
        ['pads.language_id', $request->lg_id]
    ])
    ->orderBy('created_at', 'desc')
    ->get();
</code>```

答:
You have to group your conditions within the OR within a orWhere() with a function as the argument.

```<code>->where([
        ['pads.user_id', Auth::user()->id],
        ['pads.status', $request->status],
        ['pads.language_id', $request->lg_id]
    ])
->where(function ($query) use ($request) {
    $query->where('pads.title', 'LIKE', "%{$request->search}%")
          ->orWhere('pads.people', 'LIKE', "%{$request->search}%");
})
</code>```

This will produce a query similar to

WHERE pads.user_id = ?
  AND pads.status = ?
  AND pads.language_id = ?
  AND (
       pads.title LIKE ?
       OR pads.people LIKE ?
   )
```

Body:
I want to select from database pads with 4 conditions, with 1 condition have to use "or". I wrote this query builder, it works. But I want to know if i can use a shorter query. Like use 3 conditions in a "where" brackets, and 1 in "orWhere" bracket. This is my query:

$pads = DB::table('pads')
    ->join('languages', 'pads.language_id', '=', 'languages.id')
    ->select('pads.id', 'pads.title', 'pads.status', 'pads.people', 'pads.created_at', 'languages.name as language')
    ->where([
        ['pads.user_id', Auth::user()->id],
        ['pads.title', 'LIKE', "%{$request->search}%"],
        ['pads.status', $request->status],
        ['pads.language_id', $request->lg_id]
    ])
    ->orWhere([
        ['pads.user_id', Auth::user()->id],
        ['pads.people', 'LIKE', "%{$request->search}%"],
        ['pads.status', $request->status],
        ['pads.language_id', $request->lg_id]
    ])
    ->orderBy('created_at', 'desc')
    ->get();

Body:
You have to group your conditions within the OR within a orWhere() with a function as the argument.

->where([
        ['pads.user_id', Auth::user()->id],
        ['pads.status', $request->status],
        ['pads.language_id', $request->lg_id]
    ])
->where(function ($query) use ($request) {
    $query->where('pads.title', 'LIKE', "%{$request->search}%")
          ->orWhere('pads.people', 'LIKE', "%{$request->search}%");
})

This will produce a query similar to

WHERE pads.user_id = ?
  AND pads.status = ?
  AND pads.language_id = ?
  AND (
       pads.title LIKE ?
       OR pads.people LIKE ?
   )


问:
Replace multiple characters in a string with different characters
I am converting a list to string and I am wondering if there is a more simplified way to replace multiple characters w/ different characters. I'm coding in C# and this is what my list looks like:

```<code>[0]: [Key1, Value1]
[1]: [Key2, Value2]
[2]: [Key3, Value3]
...
</code>```

So basically, I wanted to replace ", " w/ "=" and both "[]" with "" to achieve this format:

```<code>Key1=Value1
Key2=Value2
Key3=Value3
...
</code>```

I already did get this format using the following code below and I am kinda worried I am overusing the Replace command.

```<code>string out = string.Join("\n", listOfLines).Replace(", ", "=").Replace("[", "").Replace("]","");
</code>```

I have found a similar question but it does specify that the characters are all replaced by "\n" only.

Any help would be greatly appreciated. Thanks!

答:
Since you mentioned in comment that the data originally came from dictionary, you could loop through the dictionary and format the data as you like.

Sample code with Dictionary<string, object>:

```<code>var dict = new Dictionary<string, object>();
dict.Add("key1", 1);
dict.Add("key2", "string");
dict.Add("key3", true);
dict.Add("key4", new DateTime(2020, 1, 1));

foreach (KeyValuePair<string, object> kv in dict) {
    Console.WriteLine(string.Format("{0}={1}", kv.Key, kv.Value.ToString()));
}
</code>```

Body:
I am converting a list to string and I am wondering if there is a more simplified way to replace multiple characters w/ different characters. I'm coding in C# and this is what my list looks like:

[0]: [Key1, Value1]
[1]: [Key2, Value2]
[2]: [Key3, Value3]
...

So basically, I wanted to replace ", " w/ "=" and both "[]" with "" to achieve this format:

Key1=Value1
Key2=Value2
Key3=Value3
...

I already did get this format using the following code below and I am kinda worried I am overusing the Replace command.

string out = string.Join("\n", listOfLines).Replace(", ", "=").Replace("[", "").Replace("]","");

I have found a similar question but it does specify that the characters are all replaced by "\n" only.

Any help would be greatly appreciated. Thanks!

Body:
Since you mentioned in comment that the data originally came from dictionary, you could loop through the dictionary and format the data as you like.

Sample code with Dictionary<string, object>:

var dict = new Dictionary<string, object>();
dict.Add("key1", 1);
dict.Add("key2", "string");
dict.Add("key3", true);
dict.Add("key4", new DateTime(2020, 1, 1));

foreach (KeyValuePair<string, object> kv in dict) {
    Console.WriteLine(string.Format("{0}={1}", kv.Key, kv.Value.ToString()));
}


问:
Filtering SQL rows based on values from other rows
Using a SQL Server 2016 SP1 database I have this data in table name AgentsTable:

SELECT * FROM AgentsTable;

```<code>user_id         first_name  last_name   agent_id   agent_status  agent_code
2003015038088   John        Brown       22307      Retired       12345
2003015038088   John        Brown       22307      Death         12399
4432442556456   Mary        Jane        24667      Active        32133
7746234737464   Harry       Smith       29981      Retired       42354
3455555657677   Mark        Aguy        29654      Active        34655
5436546674465   Sally       Sam         22584      Retired       45464
</code>```

The second row shows that 'John Brown' is dead (agent_status = 'Death'), so I would like to exclude all rows for that agent_id who is dead. (Note that John Brown has two different agent_codes, so there's one row for each agent_code. That's how the source data is...)

This query:

SELECT * FROM AgentsTable WHERE agent_status = 'Retired';

Will return this:

```<code>user_id          first_name   last_name    agent_id   agent_status  agent_code
2003015038088    John         Brown        22307      Retired       12345
7746234737464    Harry        Smith        29981      Retired       42354
5436546674465    Sally        Sam          22584      Retired       45464
</code>```

The result I want, where John Brown (22307) is excluded, is:

```<code>user_id          first_name   last_name    agent_id   agent_status  agent_code
7746234737464    Harry        Smith        29981      Retired       42354
5436546674465    Sally        Sam          22584      Retired       45464
</code>```

How can I achieve that? In other words, how can I exclude one row based on a value in another related row?

答:
You can use CTE and get agents who are not deceased as given below:</p>

```<code>;WITH CTE_deceasedagents AS
(
SELECT agent_id
FROM AgentsTable
WHERE agent_status = 'Death'
)
SELECT *
FROM AgentsTable as a
WHERE NOT EXISTS
(
SELECT agent_id
FROM CTE_deceasedagents as c
WHERE c.agent_id = a.agent_id
);
GO
</code>```

Body:
Using a SQL Server 2016 SP1 database I have this data in table name AgentsTable:

SELECT * FROM AgentsTable;

user_id         first_name  last_name   agent_id   agent_status  agent_code
2003015038088   John        Brown       22307      Retired       12345
2003015038088   John        Brown       22307      Death         12399
4432442556456   Mary        Jane        24667      Active        32133
7746234737464   Harry       Smith       29981      Retired       42354
3455555657677   Mark        Aguy        29654      Active        34655
5436546674465   Sally       Sam         22584      Retired       45464

The second row shows that 'John Brown' is dead (agent_status = 'Death'), so I would like to exclude all rows for that agent_id who is dead. (Note that John Brown has two different agent_codes, so there's one row for each agent_code. That's how the source data is...)

This query:

SELECT * FROM AgentsTable WHERE agent_status = 'Retired';

Will return this:

user_id          first_name   last_name    agent_id   agent_status  agent_code
2003015038088    John         Brown        22307      Retired       12345
7746234737464    Harry        Smith        29981      Retired       42354
5436546674465    Sally        Sam          22584      Retired       45464

The result I want, where John Brown (22307) is excluded, is:

user_id          first_name   last_name    agent_id   agent_status  agent_code
7746234737464    Harry        Smith        29981      Retired       42354
5436546674465    Sally        Sam          22584      Retired       45464

How can I achieve that? In other words, how can I exclude one row based on a value in another related row?

Body:
You can use CTE and get agents who are not deceased as given below:

;WITH CTE_deceasedagents AS
(
SELECT agent_id
FROM AgentsTable
WHERE agent_status = 'Death'
)
SELECT *
FROM AgentsTable as a
WHERE NOT EXISTS
(
SELECT agent_id
FROM CTE_deceasedagents as c
WHERE c.agent_id = a.agent_id
);
GO


问:
AS3 - How to find the position of an object relative to the stage?
If I have a rectangle on the stage, how do I find its top left tip (x,y) and the bottom right tip (x,y) in relation to the stage? It strange how I can't find this on google! </p>

答:
If your object is in one container then you can just subtract the containers's position from the objects's position.

```<code>var rawx:Number = x - parent.x;
var rawy:Number = y - parent.y;
</code>```

Else use localToGlobal() like above.

Finding the top left and bottom right points of an object is easy - but you need to know where the registration point of the symbol is.

If the registration point where in the centre of the symbol:

```<code>var left:Number = x - (width / 2);
var right:Number = x + (width / 2);
var top:Number = y - (height / 2);
var bottom:Number = y + (height / 2);
</code>```

If it were at the top left:

```<code>var left:Number = x;
var right:Number = x + width;
var top:Number = y;
var bottom:Number = y + height;
</code>```

Etc.

Body:
If your object is in one container then you can just subtract the containers's position from the objects's position.

var rawx:Number = x - parent.x;
var rawy:Number = y - parent.y;

Else use localToGlobal() like above.

Finding the top left and bottom right points of an object is easy - but you need to know where the registration point of the symbol is.

If the registration point where in the centre of the symbol:

var left:Number = x - (width / 2);
var right:Number = x + (width / 2);
var top:Number = y - (height / 2);
var bottom:Number = y + (height / 2);

If it were at the top left:

var left:Number = x;
var right:Number = x + width;
var top:Number = y;
var bottom:Number = y + height;

Etc.


问:
How to shrink dataset using the minimum and the maximum of columns? Can I use apply family of functions?
I have a data set in this form:

```<code>  species  date         start.time           end.time              remarks
  A        2020-02-01   2020-02-01 8:00:00   2020-02-01 12:00:00   slow
  A        2020-02-01   2020-02-01 9:00:00   2020-02-02 00:00:00   NA
  A        2020-02-02   2020-02-01 8:00:00   NA                    medium
  A        2020-02-02   NA                   2020-02-01 11:30:00    NA
</code>```

I have 20 different species and 200 different dates. The data pretty much behaves the same in every species.

How can I shrink the data to get the minimum start.time, maximum end.time and every unique remark for each species and date? The output is:

```<code>  species  date         start.time   end.time   remarks
  A        2020-02-01   8:00am       12:00am    slow
  A        2020-02-02   8:00am       11:30am    medium
</code>```

I need the codes to be done in BASE R to be able to use it in a computer without the internet.

答:
Here is a base R solution

```<code>f <- function(v) {
  data.frame(species = na.omit(unique(v$species)),
             date = na.omit(unique(v$date)),
             start.time = na.omit(sort(v$start.time)[1]),
             end.time = na.omit(sort(v$end.time,decreasing = T)[1]),
             remarks = na.omit(unique(v$remarks)))
}

dfout <- do.call(rbind, c(make.row.names = F,Map(f,split(df,df[c("species","date")]))))
</code>```

such that

```<code>> dfout
  species       date         start.time            end.time remarks
1       A 2020-02-01 2020-02-01 8:00:00 2020-02-02 00:00:00    slow
2       A 2020-02-02 2020-02-01 8:00:00 2020-02-01 11:30:00  medium
</code>```

Body:
I have a data set in this form:

  species  date         start.time           end.time              remarks
  A        2020-02-01   2020-02-01 8:00:00   2020-02-01 12:00:00   slow
  A        2020-02-01   2020-02-01 9:00:00   2020-02-02 00:00:00   NA
  A        2020-02-02   2020-02-01 8:00:00   NA                    medium
  A        2020-02-02   NA                   2020-02-01 11:30:00    NA

I have 20 different species and 200 different dates. The data pretty much behaves the same in every species.

How can I shrink the data to get the minimum start.time, maximum end.time and every unique remark for each species and date? The output is:

  species  date         start.time   end.time   remarks
  A        2020-02-01   8:00am       12:00am    slow
  A        2020-02-02   8:00am       11:30am    medium

I need the codes to be done in BASE R to be able to use it in a computer without the internet.

Body:
Here is a base R solution

f <- function(v) {
  data.frame(species = na.omit(unique(v$species)),
             date = na.omit(unique(v$date)),
             start.time = na.omit(sort(v$start.time)[1]),
             end.time = na.omit(sort(v$end.time,decreasing = T)[1]),
             remarks = na.omit(unique(v$remarks)))
}

dfout <- do.call(rbind, c(make.row.names = F,Map(f,split(df,df[c("species","date")]))))

such that

> dfout
  species       date         start.time            end.time remarks
1       A 2020-02-01 2020-02-01 8:00:00 2020-02-02 00:00:00    slow
2       A 2020-02-02 2020-02-01 8:00:00 2020-02-01 11:30:00  medium