问:
how to show a dialog after 1 or 2 min after opning app for first time
I want to show a custom XML dialog  dialogue that will appear after a specific time in the first run, let's say after a min

how can I do it

but I'm confused about what should I do in a situation like below

if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the app completely

Just as a note - I have already implemented a one time show dialog(directly in main activity without any layout file ) when the app runs for the first time already

Code

To view the already implemented dialog(shows up on the first run) please
go to the  // Caution dialog (showDialog method)

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    MediaPlayer player1;
    MediaPlayer player2;
    SeekBar seekBar1;
    SeekBar seekBar2;
    TextView elapsedTimeLable1;
    TextView elapsedTimeLable2;
    TextView remainingTimeLable1;
    TextView remainingTimeLable2;
    ImageView play1;
    ImageView play2;
    int totalTime1;
    @SuppressLint("HandlerLeak")
    private final Handler handler1 = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition1 = msg.what;
            //Update SeekBar
            seekBar1.setProgress(currentPosition1);
            // Update Timelable
            String elapsedTime1 = createTimerLable1(currentPosition1);
            elapsedTimeLable1.setText(elapsedTime1);
            String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
            remainingTimeLable1.setText("- " + remainingTime1);

        }
    };
    int totalTime2;
    @SuppressLint("HandlerLeak")
    private final Handler handler2 = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition2 = msg.what;
            // Update SeekBar
            seekBar2.setProgress(currentPosition2);
            // Update Timelable
            String elapsedTime2 = createTimerLable2(currentPosition2);
            elapsedTimeLable2.setText(elapsedTime2);
            String remainingTime2 = createTimerLable2(totalTime2 - currentPosition2);
            remainingTimeLable2.setText("- " + remainingTime2);

        }
    };

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("ObsoleteSdkInt")
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window w = getWindow();
            // clear FLAG_TRANSLUCENT_STATUS flag:
            w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

            // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
            w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            // finally change the color
            w.setStatusBarColor(ContextCompat.getColor(this, R.color.Card_Elevation_Color));
        }

        // PlayButton    *  The ButtonClick is in the last if you want to jump directly there  *

        play1 = findViewById(R.id.playbtn1);
        play2 = findViewById(R.id.playbtn2);

        // TimeLables

        elapsedTimeLable1 = findViewById(R.id.cTime1);
        elapsedTimeLable2 = findViewById(R.id.cTime2);
        remainingTimeLable1 = findViewById(R.id.tTime1);
        remainingTimeLable2 = findViewById(R.id.tTime2);

        // MediaPlayer

        player1 = MediaPlayer.create(this, R.raw.dog_howl);
        player1.setLooping(true);
        player1.seekTo(0);
        totalTime1 = player1.getDuration();
        player2 = MediaPlayer.create(this, R.raw.dog_bark);
        player2.setLooping(true);
        player2.seekTo(0);
        totalTime2 = player2.getDuration();

        //SeekBar

        seekBar1 = findViewById(R.id.seekbar1);
        seekBar2 = findViewById(R.id.seekbar2);
        seekBar1.setMax(totalTime1);
        seekBar2.setMax(totalTime2);

        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress1, boolean fromUser1) {
                if (fromUser1) {
                    player1.seekTo(progress1);
                    seekBar1.setProgress(progress1);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress2, boolean fromUser2) {
                if (fromUser2) {
                    player2.seekTo(progress2);
                    seekBar2.setProgress(progress2);
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        // Thread (Update SeekBar & TimeLabel)
        new Thread(() -> {
            while (player1 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player1.getCurrentPosition();
                    handler1.sendMessage(msg);
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {

                }
            }
        }).start();

        new Thread(() -> {
            while (player2 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player2.getCurrentPosition();
                    handler2.sendMessage(msg);
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {

                }
            }
        }).start();

        // Admob Banner Ad

        MobileAds.initialize(this, initializationStatus -> {
        });

        AdView mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        // Caution dialog

        SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
        boolean firstStart = preferences.getBoolean("firstStart", true);
        if (firstStart) {

            showDialog();
        }

    }

    // Caution dialog
    private void showDialog() {
        new AlertDialog.Builder(this)
                .setTitle("Caution!")
                .setMessage("In case you're wearing any kind of headphones please remove it before playing the ' Howl ' audio")
                .setPositiveButton("ok", (dialogInterface, i) -> dialogInterface.dismiss())
                .create().show();
        SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("firstStart", false);
        editor.apply();
    }

    public String createTimerLable1(int duration) {
        String timerLabel1 = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel1 += min + ":";
        if (sec < 10) timerLabel1 += "0";
        timerLabel1 += sec;
        return timerLabel1;

    }

    public String createTimerLable2(int duration) {
        String timerLabel2 = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel2 += min + ":";
        if (sec < 10) timerLabel2 += "0";
        timerLabel2 += sec;
        return timerLabel2;

    }

    public void playBtnClick1(View view) {

        if (player2.isPlaying()) {
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

        if (!player1.isPlaying()) {
            // Stoping
            player1.start();
            play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

    public void playBtnClick2(View view) {

        if (player1.isPlaying()) {
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

        if (!player2.isPlaying()) {
            // Stoping
            player2.start();
            play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();

        if (player1 != null) {
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }
        if (player2 != null) {
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }
    }

}
</code>```

答:
but I'm confused about what should I do in a situation like below

if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the
app completely

This is impossible to do if your app is closed.My suggestion would be to create a service on another process that does this dialog such that even if the app process is closed,the service process will still be running unless it is stopped explicitly.
Defining a Process of a Service

The android:process field defines the name of the process where the
service is to run. Normally, all components of an application run in
the default process created for the application. However, a component
can override the default with its own process attribute, allowing you
to spread your application across multiple processes.

If the name assigned to this attribute begins with a colon (':'), the
service will run in its own separate process.

```<code><service   android:name="com.example.appName"   android:process=":externalProcess" />
</code>```

This is of course in the manifest file .
You might also need to show a system dialog thus you will need a system Alert Window permission i your manifest and request for the permision on runtime.

```<code><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
</code>```

Then on runtime request like this:

```<code>  public static void openOverlaySettings(Activity activity) {
        final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + activity.getPackageName()));
        try {
            activity.startActivityForResult(intent, 6);
        } catch (ActivityNotFoundException e) {
            Log.e("Drawers permission :", e.getMessage());
        }
    }
</code>```

To check if granted use :

```<code>if(!Settings.canDrawOverlays(context)) {
            openOverlaySettings(context);
            ok=false;
        }
</code>```

Then in your service you should create the dialog like below

```<code>View aldv= LayoutInflater.from(act).inflate(R.layout.your_layout,null);
        ald=new AlertDialog.Builder(act,R.style.AppTheme)
                .setView(aldv)
                .setCancelable(true)
                .create();
                ald.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

</code>```

Body:
I want to show a custom XML dialog  dialogue that will appear after a specific time in the first run, let's say after a min

how can I do it

but I'm confused about what should I do in a situation like below

if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the app completely

Just as a note - I have already implemented a one time show dialog(directly in main activity without any layout file ) when the app runs for the first time already

Code

To view the already implemented dialog(shows up on the first run) please
go to the  // Caution dialog (showDialog method)

MainActivity.java

public class MainActivity extends AppCompatActivity {
    MediaPlayer player1;
    MediaPlayer player2;
    SeekBar seekBar1;
    SeekBar seekBar2;
    TextView elapsedTimeLable1;
    TextView elapsedTimeLable2;
    TextView remainingTimeLable1;
    TextView remainingTimeLable2;
    ImageView play1;
    ImageView play2;
    int totalTime1;
    @SuppressLint("HandlerLeak")
    private final Handler handler1 = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition1 = msg.what;
            //Update SeekBar
            seekBar1.setProgress(currentPosition1);
            // Update Timelable
            String elapsedTime1 = createTimerLable1(currentPosition1);
            elapsedTimeLable1.setText(elapsedTime1);
            String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
            remainingTimeLable1.setText("- " + remainingTime1);

        }
    };
    int totalTime2;
    @SuppressLint("HandlerLeak")
    private final Handler handler2 = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition2 = msg.what;
            // Update SeekBar
            seekBar2.setProgress(currentPosition2);
            // Update Timelable
            String elapsedTime2 = createTimerLable2(currentPosition2);
            elapsedTimeLable2.setText(elapsedTime2);
            String remainingTime2 = createTimerLable2(totalTime2 - currentPosition2);
            remainingTimeLable2.setText("- " + remainingTime2);

        }
    };

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("ObsoleteSdkInt")
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window w = getWindow();
            // clear FLAG_TRANSLUCENT_STATUS flag:
            w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

            // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
            w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            // finally change the color
            w.setStatusBarColor(ContextCompat.getColor(this, R.color.Card_Elevation_Color));
        }

        // PlayButton    *  The ButtonClick is in the last if you want to jump directly there  *

        play1 = findViewById(R.id.playbtn1);
        play2 = findViewById(R.id.playbtn2);

        // TimeLables

        elapsedTimeLable1 = findViewById(R.id.cTime1);
        elapsedTimeLable2 = findViewById(R.id.cTime2);
        remainingTimeLable1 = findViewById(R.id.tTime1);
        remainingTimeLable2 = findViewById(R.id.tTime2);

        // MediaPlayer

        player1 = MediaPlayer.create(this, R.raw.dog_howl);
        player1.setLooping(true);
        player1.seekTo(0);
        totalTime1 = player1.getDuration();
        player2 = MediaPlayer.create(this, R.raw.dog_bark);
        player2.setLooping(true);
        player2.seekTo(0);
        totalTime2 = player2.getDuration();

        //SeekBar

        seekBar1 = findViewById(R.id.seekbar1);
        seekBar2 = findViewById(R.id.seekbar2);
        seekBar1.setMax(totalTime1);
        seekBar2.setMax(totalTime2);

        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress1, boolean fromUser1) {
                if (fromUser1) {
                    player1.seekTo(progress1);
                    seekBar1.setProgress(progress1);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress2, boolean fromUser2) {
                if (fromUser2) {
                    player2.seekTo(progress2);
                    seekBar2.setProgress(progress2);
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        // Thread (Update SeekBar & TimeLabel)
        new Thread(() -> {
            while (player1 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player1.getCurrentPosition();
                    handler1.sendMessage(msg);
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {

                }
            }
        }).start();

        new Thread(() -> {
            while (player2 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player2.getCurrentPosition();
                    handler2.sendMessage(msg);
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {

                }
            }
        }).start();

        // Admob Banner Ad

        MobileAds.initialize(this, initializationStatus -> {
        });

        AdView mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        // Caution dialog

        SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
        boolean firstStart = preferences.getBoolean("firstStart", true);
        if (firstStart) {

            showDialog();
        }

    }

    // Caution dialog
    private void showDialog() {
        new AlertDialog.Builder(this)
                .setTitle("Caution!")
                .setMessage("In case you're wearing any kind of headphones please remove it before playing the ' Howl ' audio")
                .setPositiveButton("ok", (dialogInterface, i) -> dialogInterface.dismiss())
                .create().show();
        SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("firstStart", false);
        editor.apply();
    }

    public String createTimerLable1(int duration) {
        String timerLabel1 = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel1 += min + ":";
        if (sec < 10) timerLabel1 += "0";
        timerLabel1 += sec;
        return timerLabel1;

    }

    public String createTimerLable2(int duration) {
        String timerLabel2 = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel2 += min + ":";
        if (sec < 10) timerLabel2 += "0";
        timerLabel2 += sec;
        return timerLabel2;

    }

    public void playBtnClick1(View view) {

        if (player2.isPlaying()) {
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

        if (!player1.isPlaying()) {
            // Stoping
            player1.start();
            play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

    public void playBtnClick2(View view) {

        if (player1.isPlaying()) {
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

        if (!player2.isPlaying()) {
            // Stoping
            player2.start();
            play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();

        if (player1 != null) {
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }
        if (player2 != null) {
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }
    }

}

Body:
but I'm confused about what should I do in a situation like below

if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the
app completely

This is impossible to do if your app is closed.My suggestion would be to create a service on another process that does this dialog such that even if the app process is closed,the service process will still be running unless it is stopped explicitly.
Defining a Process of a Service

The android:process field defines the name of the process where the
service is to run. Normally, all components of an application run in
the default process created for the application. However, a component
can override the default with its own process attribute, allowing you
to spread your application across multiple processes.

If the name assigned to this attribute begins with a colon (':'), the
service will run in its own separate process.

<service   android:name="com.example.appName"   android:process=":externalProcess" />

This is of course in the manifest file .
You might also need to show a system dialog thus you will need a system Alert Window permission i your manifest and request for the permision on runtime.

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

Then on runtime request like this:

  public static void openOverlaySettings(Activity activity) {
        final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + activity.getPackageName()));
        try {
            activity.startActivityForResult(intent, 6);
        } catch (ActivityNotFoundException e) {
            Log.e("Drawers permission :", e.getMessage());
        }
    }

To check if granted use :

if(!Settings.canDrawOverlays(context)) {
            openOverlaySettings(context);
            ok=false;
        }

Then in your service you should create the dialog like below

View aldv= LayoutInflater.from(act).inflate(R.layout.your_layout,null);
        ald=new AlertDialog.Builder(act,R.style.AppTheme)
                .setView(aldv)
                .setCancelable(true)
                .create();
                ald.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);


来源: stackexchange

问:
Best way to handle an empty ref in Vue 3 with TypeScript?
Variable starts off with an empty ref, for example it might be one of these:

```<code>const myString = ref();
const myString = ref('');
const myString = ref<string>();
const myString = ref<string | null>();
const myString = ref<string | null>(null);
const myString = ref<string | undefined>();
const myString = ref<string | undefined>(undefined);
const myString = ref<string | null | undefined>();
</code>```

Then later it's given a value:

```<code>myString.value = "I am a string";
</code>```

The ref is then assigned an empty value again, for example it might be one of these:

```<code>myString.value = '';
myString.value = null;
myString.value = undefined;
</code>```

Which combination of these is best to use in Vue 3?

Or maybe you do something else?

When used in the wild I'm looking for maximum compatibility with Vue 3, TypeScript type safety, and no Eslint errors.

答:
As the documentation shows, no ref argument results in inferred union type and requires less code to achieve the result:

```<code>// inferred type: Ref<number | undefined>
const n = ref<number>()
</code>```

The difference between undefined and null in this case is mostly semantic. It may be beneficial to use ref<string | null>(null) if it's necessary to determine whether a value is intentionally or accidentally empty, this may be beneficial for debugging purposes. Also they behave differently in JSON, if a value is supposed to be serialized, null is a preferable choice.

ref('') can be used if it doesn't matter whether a value is initialized or just empty, and there are string method calls that require to take care of optional chaining for null or undefined values, e.g. myString.value?.toLowerCase().

ContentLicense: CC BY-SA 4.0

Body:
Variable starts off with an empty ref, for example it might be one of these:

const myString = ref();
const myString = ref('');
const myString = ref<string>();
const myString = ref<string | null>();
const myString = ref<string | null>(null);
const myString = ref<string | undefined>();
const myString = ref<string | undefined>(undefined);
const myString = ref<string | null | undefined>();

Then later it's given a value:

myString.value = "I am a string";

The ref is then assigned an empty value again, for example it might be one of these:

myString.value = '';
myString.value = null;
myString.value = undefined;

Which combination of these is best to use in Vue 3?

Or maybe you do something else?

When used in the wild I'm looking for maximum compatibility with Vue 3, TypeScript type safety, and no Eslint errors.

Body:
As the documentation shows, no ref argument results in inferred union type and requires less code to achieve the result:

// inferred type: Ref<number | undefined>
const n = ref<number>()

The difference between undefined and null in this case is mostly semantic. It may be beneficial to use ref<string | null>(null) if it's necessary to determine whether a value is intentionally or accidentally empty, this may be beneficial for debugging purposes. Also they behave differently in JSON, if a value is supposed to be serialized, null is a preferable choice.

ref('') can be used if it doesn't matter whether a value is initialized or just empty, and there are string method calls that require to take care of optional chaining for null or undefined values, e.g. myString.value?.toLowerCase().


问:
Pandas return column data as list without duplicates
This is just an oversimplification but I have this large categorical data.

```<code>Name   Age Gender
John    12 Male
Ana     24 Female
Dave    16 Female
Cynthia 17 Non-Binary
Wayne   26 Male
Hebrew  29 Non-Binary
</code>```

Suppose that it is assigned as df and I want it to return as a list with non-duplicate values:

```<code>'Male','Female','Non-Binary'
</code>```

I tried it with this code, but this returns the gender with duplicates

```<code>list(df['Gender'])
</code>```

How can I code it in pandas so that it can return values without duplicates?

答:
In these cases you have to remember that df["Gender"] is a Pandas Series so you could use .drop_duplicates() to retrieve another Pandas Series with the duplicated values removed or use .unique() to retrieve a Numpy Array containing the unique values.

```<code>>> df["Gender"].drop_duplicates()
0         Male
1        Female
3    Non-Binary
4          Male
Name: Gender, dtype: object

>> df["Gender"].unique()
['Male ' 'Female' 'Non-Binary' 'Male']
</code>```

Body:
This is just an oversimplification but I have this large categorical data.

Name   Age Gender
John    12 Male
Ana     24 Female
Dave    16 Female
Cynthia 17 Non-Binary
Wayne   26 Male
Hebrew  29 Non-Binary

Suppose that it is assigned as df and I want it to return as a list with non-duplicate values:

'Male','Female','Non-Binary'

I tried it with this code, but this returns the gender with duplicates

list(df['Gender'])

How can I code it in pandas so that it can return values without duplicates?

Body:
In these cases you have to remember that df["Gender"] is a Pandas Series so you could use .drop_duplicates() to retrieve another Pandas Series with the duplicated values removed or use .unique() to retrieve a Numpy Array containing the unique values.

>> df["Gender"].drop_duplicates()
0         Male
1        Female
3    Non-Binary
4          Male
Name: Gender, dtype: object

>> df["Gender"].unique()
['Male ' 'Female' 'Non-Binary' 'Male']


问:
Need to rasterize odd-sized SVG files for a thermal receipt printer in python
Need to rasterize odd-sized SVG files for a thermal receipt printer in python.

I have a thermal printer is 384px across, and "unlimited" in length. I am currently generating SVG files that could easily be rendered (at 200px/in) to 73152 x 384 pixels (that's the full width of the printer, 30 feet long).

I've tried using cairosvg (aka svglib) and unsurprisingly get a CAIRO_STATUS_INVALID_SIZE memory error. I suspect that even if cairosvg could handle it, when I pass it to PIL to rasterize it, PIL would likely have problems also. I could render at a far lower resolution, but it quickly gets chunky when I scale up to 200px/in.

I've also looked around for other svg python modules, but nothing looks like they'd work.

It would be best if I "chunked" the input anyway because that's what the printer needs i.e., render 384x1024 chunks of the SVG file at a time with some kind of "window" that I could pan through the rendered SVG file... somehow.

Any ideas?

thx, tom.c

答:
Here's what works so far. It's very hackish, but for this project, I'm ok w/ it.

This is prototype code, not the real thing. It does show how to "chunk" a very large SVG file into pieces that a small printer can handle. For brevity, I'm just doing an img.show() instead of the reams of code to format it for the printer.

```<code>!/usr/bin/env python3

import copy
import vpype
import vpype_viewer

ifile = "VertWideExample.svg"

lcO, w, h = vpype.read_svg(ifile, quantization=.1, crop=True)

for I in range(0, 400, 100):
  print(I)
  lc = copy.copy(lcO)
  lc.crop(I, 0, I + 100, 13.2283536)
  v = vpype_viewer.ImageRenderer((640,480))
  doc = vpype.Document(lc)
  v.engine.document = doc
  v.engine.fit_to_viewport()
  img=v.render()
  img.show()
  V = None         # Segfaults w/o explicitly deleting
</code>```

Body:
Here's what works so far. It's very hackish, but for this project, I'm ok w/ it.

This is prototype code, not the real thing. It does show how to "chunk" a very large SVG file into pieces that a small printer can handle. For brevity, I'm just doing an img.show() instead of the reams of code to format it for the printer.

!/usr/bin/env python3

import copy
import vpype
import vpype_viewer

ifile = "VertWideExample.svg"

lcO, w, h = vpype.read_svg(ifile, quantization=.1, crop=True)

for I in range(0, 400, 100):
  print(I)
  lc = copy.copy(lcO)
  lc.crop(I, 0, I + 100, 13.2283536)
  v = vpype_viewer.ImageRenderer((640,480))
  doc = vpype.Document(lc)
  v.engine.document = doc
  v.engine.fit_to_viewport()
  img=v.render()
  img.show()
  V = None         # Segfaults w/o explicitly deleting


问:
How do I observe a resource leak with Statement, PreparedStatement, and ResultSet?
I am trying to put together small samples that demonstrates that you MUST close Statement, PreparedStatement, and ResultSet.

However, I have not been able to reproduce a resource leak with them. Memory grows for a little bit, but the GC eventually kicks in and cleans everything up. The is no resource leak on the database side either, just CPU util for executing the queries. My guess is that when the GC finally determines to remove those objects, it calls finalized and the JDBC implementation removes them. But I'm not confident in this explanation because the same thing doesn't happen for Connection. Leaking Connection objects will eventually run out of connections.

How do I create and observe a resource leak with Statement, PreparedStatement, and ResultSet? This question is different from existing questions discussion jdbc resource leaks because in those they ask if a resource leak is made by forgetting to close. Here, I'm intentionally trying to create and observe the leak.

Statement runs forever without any issue:

    final String url = "jdbc:" + dbType + "://" + hostname + ":" + port + "/";
    try(Connection conn = DriverManager.getConnection(url, username, password)) {
      while (true) {
        try {
          Statement statement = conn.createStatement();
          statement.executeQuery("select 1");
          throw new IgnoredException("Does this cause a leak?");
        } catch (IgnoredException e) {
          // do nothing and keep leaking resources
        }
      }
    }
```
<p>PreparedStatement runs forever without any issue:</p>
<pre class="lang-java prettyprint-override"><code>  private void javaSqlPreparedStatementLeak() throws Exception {
    final String url = "jdbc:" + dbType + "://" + hostname + ":" + port + "/";
    try(Connection conn = DriverManager.getConnection(url, username, password)) {
      int i = 0;
      while (true) {
        try {
          PreparedStatement statement = conn.prepareStatement("select 1");
          statement.execute();
          throw new IgnoredException("Does this cause a leak?");
        } catch (IgnoredException e) {
          // do nothing and keep leaking resources
        }
      }
    }
  }
</code>```

ResultSet runs forever without any issue:

  private void javaSqlResultSetLeak() throws Exception {
    final String url = "jdbc:" + dbType + "://" + hostname + ":" + port + "/";
    try(Connection conn = DriverManager.getConnection(url, username, password)) {
      while (true) {
        try {
          Statement statement = conn.createStatement();
          statement.setFetchSize(1);
          ResultSet resultSet = statement.executeQuery("SELECT 1, 2"
                  + " UNION SELECT 'a', 'b'"
                  + " UNION SELECT '3', '4'");
          throw new IgnoredException("Does this cause a leak?");
        } catch (IgnoredException e) {
          // do nothing and keep leaking resources
        }
      }
    }
  }
```
<p>Connection Leak throws <code>java.sql.SQLException: Too many connections</code> as expected:</p>
<pre class="lang-java prettyprint-override"><code>  private void javaSqlConnectionLeak() throws Exception {
    final String url = "jdbc:" + dbType + "://" + hostname + ":" + port + "/";

    while (true) {
      try {
        Connection conn = DriverManager.getConnection(url, username, password);
        throw new IgnoredException("Does this cause a leak?");
      } catch (IgnoredException e) {
        // do nothing and keep leaking resources
      }
    }
  }
</code>```

Copy of the exception thrown:

```<code>   * java.sql.SQLNonTransientConnectionException: Could not connect to HostAddress{host='localhost', port=3306, type='master'}. Too many connections
   *     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException (ExceptionFactory.java:73)
   *     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create (ExceptionFactory.java:188)
   *     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy (AbstractConnectProtocol.java:1402)
   *     at org.mariadb.jdbc.internal.util.Utils.retrieveProxy (Utils.java:635)
   *     at org.mariadb.jdbc.MariaDbConnection.newConnection (MariaDbConnection.java:150)
   *     at org.mariadb.jdbc.Driver.connect (Driver.java:89)
   *     at java.sql.DriverManager.getConnection (DriverManager.java:677)
   *     at java.sql.DriverManager.getConnection (DriverManager.java:228)
   *     at Main.javaSqlConnectionLeak (Main.java:181)
   *     at Main.run (Main.java:74)
   *     at Main.main (Main.java:194)
   *     at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:254)
   *     at java.lang.Thread.run (Thread.java:831)
   * Caused by: java.sql.SQLException: Too many connections
   *     at org.mariadb.jdbc.internal.com.read.ReadInitialHandShakePacket.<init> (ReadInitialHandShakePacket.java:92)
   *     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.createConnection (AbstractConnectProtocol.java:527)
   *     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy (AbstractConnectProtocol.java:1389)
   *     at org.mariadb.jdbc.internal.util.Utils.retrieveProxy (Utils.java:635)
   *     at org.mariadb.jdbc.MariaDbConnection.newConnection (MariaDbConnection.java:150)
   *     at org.mariadb.jdbc.Driver.connect (Driver.java:89)
   *     at java.sql.DriverManager.getConnection (DriverManager.java:677)
   *     at java.sql.DriverManager.getConnection (DriverManager.java:228)
   *     at Main.javaSqlConnectionLeak (Main.java:181)
   *     at Main.run (Main.java:74)
   *     at Main.main (Main.java:194)
   *     at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:254)
   *     at java.lang.Thread.run (Thread.java:831)
</code>```

IgnoredException for reference:

class IgnoredException extends Exception {

  IgnoredException(String s) {
    super(s);
  }
}
```

Link to working source: https://github.com/josephmate/java-by-experiments/blob/0212f36950e33cd0d9c67cd2b057a8c523707c14/resource_leaks/src/main/java/Main.java

答:
Not explicitly closing resources may not necessarily result in a memory leak in your Java application. Depending on the exact implementation details of the JDBC driver, it is entirely possible the garbage collector will remove those objects just fine.

However, not all JDBC drivers implement finalize, or the implementation may only close the socket, and not cleanly close the database-side. This may result in resource leaks in the database server. This may vary from stuck transactions, unnecessary retention of handles for statement, connections, result set buffers, etc., as demonstrated by that "Too many connections" exception.

In addition, re-executing a statement will close any previous result set generated by that statement. Similarly, in auto-commit mode, executing any statement, will (or should, not all drivers actually do) close any previous result set (of any statement of that connection). So your examples - probably - don't leak result sets.

All this can vary by driver, configuration of the driver and other factors. For example, some drivers may not even use a database-side statement handle for java.sql.Statement, but do use one for java.sql.PreparedStatement. That you cannot see the effects of a resource leak, doesn't mean they aren't there, though it could also mean the implementation of the driver or database is good at detecting and correcting such leaks, or uses strategies that avoid leaks. For example, the MySQL driver defaults to fetching the entire result in memory, so there won't be a server-side buffer left around to leak.

However, all that isn't relevant: just follow the simple rule to open resources in a try-with-resources and you don't have to worry about the absence or presence of resource leaks, or reliance on the garbage collector to clean up your mess.

Body:
I am trying to put together small samples that demonstrates that you MUST close Statement, PreparedStatement, and ResultSet.

However, I have not been able to reproduce a resource leak with them. Memory grows for a little bit, but the GC eventually kicks in and cleans everything up. The is no resource leak on the database side either, just CPU util for executing the queries. My guess is that when the GC finally determines to remove those objects, it calls finalized and the JDBC implementation removes them. But I'm not confident in this explanation because the same thing doesn't happen for Connection. Leaking Connection objects will eventually run out of connections.

How do I create and observe a resource leak with Statement, PreparedStatement, and ResultSet? This question is different from existing questions discussion jdbc resource leaks because in those they ask if a resource leak is made by forgetting to close. Here, I'm intentionally trying to create and observe the leak.

Statement runs forever without any issue:

    final String url = "jdbc:" + dbType + "://" + hostname + ":" + port + "/";
    try(Connection conn = DriverManager.getConnection(url, username, password)) {
      while (true) {
        try {
          Statement statement = conn.createStatement();
          statement.executeQuery("select 1");
          throw new IgnoredException("Does this cause a leak?");
        } catch (IgnoredException e) {
          // do nothing and keep leaking resources
        }
      }
    }

PreparedStatement runs forever without any issue:

  private void javaSqlPreparedStatementLeak() throws Exception {
    final String url = "jdbc:" + dbType + "://" + hostname + ":" + port + "/";
    try(Connection conn = DriverManager.getConnection(url, username, password)) {
      int i = 0;
      while (true) {
        try {
          PreparedStatement statement = conn.prepareStatement("select 1");
          statement.execute();
          throw new IgnoredException("Does this cause a leak?");
        } catch (IgnoredException e) {
          // do nothing and keep leaking resources
        }
      }
    }
  }

ResultSet runs forever without any issue:

  private void javaSqlResultSetLeak() throws Exception {
    final String url = "jdbc:" + dbType + "://" + hostname + ":" + port + "/";
    try(Connection conn = DriverManager.getConnection(url, username, password)) {
      while (true) {
        try {
          Statement statement = conn.createStatement();
          statement.setFetchSize(1);
          ResultSet resultSet = statement.executeQuery("SELECT 1, 2"
                  + " UNION SELECT 'a', 'b'"
                  + " UNION SELECT '3', '4'");
          throw new IgnoredException("Does this cause a leak?");
        } catch (IgnoredException e) {
          // do nothing and keep leaking resources
        }
      }
    }
  }

Connection Leak throws java.sql.SQLException: Too many connections as expected:

  private void javaSqlConnectionLeak() throws Exception {
    final String url = "jdbc:" + dbType + "://" + hostname + ":" + port + "/";

    while (true) {
      try {
        Connection conn = DriverManager.getConnection(url, username, password);
        throw new IgnoredException("Does this cause a leak?");
      } catch (IgnoredException e) {
        // do nothing and keep leaking resources
      }
    }
  }

Copy of the exception thrown:

   * java.sql.SQLNonTransientConnectionException: Could not connect to HostAddress{host='localhost', port=3306, type='master'}. Too many connections
   *     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException (ExceptionFactory.java:73)
   *     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create (ExceptionFactory.java:188)
   *     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy (AbstractConnectProtocol.java:1402)
   *     at org.mariadb.jdbc.internal.util.Utils.retrieveProxy (Utils.java:635)
   *     at org.mariadb.jdbc.MariaDbConnection.newConnection (MariaDbConnection.java:150)
   *     at org.mariadb.jdbc.Driver.connect (Driver.java:89)
   *     at java.sql.DriverManager.getConnection (DriverManager.java:677)
   *     at java.sql.DriverManager.getConnection (DriverManager.java:228)
   *     at Main.javaSqlConnectionLeak (Main.java:181)
   *     at Main.run (Main.java:74)
   *     at Main.main (Main.java:194)
   *     at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:254)
   *     at java.lang.Thread.run (Thread.java:831)
   * Caused by: java.sql.SQLException: Too many connections
   *     at org.mariadb.jdbc.internal.com.read.ReadInitialHandShakePacket.<init> (ReadInitialHandShakePacket.java:92)
   *     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.createConnection (AbstractConnectProtocol.java:527)
   *     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy (AbstractConnectProtocol.java:1389)
   *     at org.mariadb.jdbc.internal.util.Utils.retrieveProxy (Utils.java:635)
   *     at org.mariadb.jdbc.MariaDbConnection.newConnection (MariaDbConnection.java:150)
   *     at org.mariadb.jdbc.Driver.connect (Driver.java:89)
   *     at java.sql.DriverManager.getConnection (DriverManager.java:677)
   *     at java.sql.DriverManager.getConnection (DriverManager.java:228)
   *     at Main.javaSqlConnectionLeak (Main.java:181)
   *     at Main.run (Main.java:74)
   *     at Main.main (Main.java:194)
   *     at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:254)
   *     at java.lang.Thread.run (Thread.java:831)

IgnoredException for reference:

class IgnoredException extends Exception {

  IgnoredException(String s) {
    super(s);
  }
}

Link to working source: https://github.com/josephmate/java-by-experiments/blob/0212f36950e33cd0d9c67cd2b057a8c523707c14/resource_leaks/src/main/java/Main.java


问:
How to sum all Object using index with an arrays
how can I search duplicate data using index key object here is my object :

```<code> const obj = {
        product1: { name: 'paper', price: 4 },
        product2: { name: 'ball', price: 2 },
        product3: { name: 'ice-cream', price: 9 }
        product1: { name: 'paper', price: 2 }
    }
</code>```

and I have an arrays

```<code>const arr = ["product1", "product2" ]
</code>```

I want to get only product1 and product2 data then sum price together my output shold look like this 4+2+2 = 8

Here is what I try to do

```<code>const newArr = _.map(arr, (name:string) => {
    return obj[name]
})

then I sum

    const sum = newArr.reduce((data, obj)=> data + obj.price, 0);

</code>```

the problem is in _.map when I map data if I return like this it will get only 1 product1 I want to get all of product name in arr

### UPDATE ####

I changed my object to unique but I still want to use arr to find some word not sure Can I use includes or indexOf in and Objects?

```<code> const obj = {
        "product1 Hello": { name: 'paper', price: 4 },
        "product2 test": { name: 'ball', price: 2 },
        "product3 Hello3": { name: 'ice-cream', price: 9 }
        "product1 Hello4": { name: 'paper', price: 2 }
    }
</code>```

答:
JSON object can't hold duplicate keys. If so, it gets replaced by the last record.

In your case, the input becomes:

```<code>const obj = {
  product1: { name: 'paper', price: 2 },
  product2: { name: 'ball', price: 2 },
  product3: { name: 'ice-cream', price: 9 }
}
</code>```

Your possible input will be like thes:

```<code>const obj = {
  product1: [{ name: 'paper', price: 4 }, { name: 'paper', price: 2 }],
  product2: [{ name: 'ball', price: 2 }],
  product3: [{ name: 'ice-cream', price: 9 }]
}
</code>```
```<code>const obj = [
  {key: 'product1', name: 'paper', price: 4},
  {key: 'product2', name: 'ball', price: 2},
  {key: 'product3', name: 'ice-cream', price: 9},
  {key: 'product1', name: 'paper', price: 2},
]
</code>```

Updated answer as updated code:

```<code>const obj = {
  "product1 Hello": {name: 'paper', price: 4},
  "product2 test": {name: 'ball', price: 2},
  "product3 Hello3": {name: 'ice-cream', price: 9},
  "product1 Hello4": {name: 'paper', price: 2}
}
const arr = ["product1", "product2"]

let keys = Object.keys(obj).filter(x => arr.some(y => x.includes(y)))
keys.map(x => obj[x].price).reduce((x, y) => x + y, 0)
</code>```

Body:
how can I search duplicate data using index key object here is my object :

 const obj = {
        product1: { name: 'paper', price: 4 },
        product2: { name: 'ball', price: 2 },
        product3: { name: 'ice-cream', price: 9 }
        product1: { name: 'paper', price: 2 }
    }

and I have an arrays

const arr = ["product1", "product2" ]

I want to get only product1 and product2 data then sum price together my output shold look like this 4+2+2 = 8

Here is what I try to do

const newArr = _.map(arr, (name:string) => {
    return obj[name]
})

then I sum

    const sum = newArr.reduce((data, obj)=> data + obj.price, 0);

the problem is in _.map when I map data if I return like this it will get only 1 product1 I want to get all of product name in arr

### UPDATE ####

I changed my object to unique but I still want to use arr to find some word not sure Can I use includes or indexOf in and Objects?

 const obj = {
        "product1 Hello": { name: 'paper', price: 4 },
        "product2 test": { name: 'ball', price: 2 },
        "product3 Hello3": { name: 'ice-cream', price: 9 }
        "product1 Hello4": { name: 'paper', price: 2 }
    }

Body:
JSON object can't hold duplicate keys. If so, it gets replaced by the last record.

In your case, the input becomes:

const obj = {
  product1: { name: 'paper', price: 2 },
  product2: { name: 'ball', price: 2 },
  product3: { name: 'ice-cream', price: 9 }
}

Your possible input will be like thes:

const obj = {
  product1: [{ name: 'paper', price: 4 }, { name: 'paper', price: 2 }],
  product2: [{ name: 'ball', price: 2 }],
  product3: [{ name: 'ice-cream', price: 9 }]
}

const obj = [
  {key: 'product1', name: 'paper', price: 4},
  {key: 'product2', name: 'ball', price: 2},
  {key: 'product3', name: 'ice-cream', price: 9},
  {key: 'product1', name: 'paper', price: 2},
]

Updated answer as updated code:

const obj = {
  "product1 Hello": {name: 'paper', price: 4},
  "product2 test": {name: 'ball', price: 2},
  "product3 Hello3": {name: 'ice-cream', price: 9},
  "product1 Hello4": {name: 'paper', price: 2}
}
const arr = ["product1", "product2"]

let keys = Object.keys(obj).filter(x => arr.some(y => x.includes(y)))
keys.map(x => obj[x].price).reduce((x, y) => x + y, 0)


问:
Is there a Javascript function similar to the Python Counter function?
I am attempting to change a program of mine from Python to Javascript and I was wondering if there was a JS function like the Counter function from the collections module in Python.

Syntax for Counter

```<code>from collection import Counter
list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a']
counter = Counter(list)
print counter
</code>```

output

```<code>Counter({'a':5, 'b':3, 'c':2})
</code>```

答:
In Python, the Counter also has add and update methods, which are used quite commonly. So a better solution would be this:

function Counter(array) {
    this.add = (val) => {
        this[val] = (this[val] || 0) + 1;
    };
    this.update = (array) => {
        array.forEach((val) => this.add(val));
    };
    this.update(array);
}

// Example usage
let myCounter = new Counter([1, 2, 2])
myCounter.update([3, 3, 3])
myCounter.add(4)
console.log(myCounter)```

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to change a program of mine from Python to Javascript and I was wondering if there was a JS function like the Counter function from the collections module in Python.

Syntax for Counter

from collection import Counter
list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a']
counter = Counter(list)
print counter

output

Counter({'a':5, 'b':3, 'c':2})


问:
Javascript: How to remove empty string values from an array?
I have this array of objects:

const data = [{
    "_id": "plastic",
    "countries": ['Egypt','','Iran','',''],
    "likelihood": [1,2,3,4,5],
    "relevance": [1,2,3,4,5],
    "intensity": [1,2,3,4,5]
},
{
    "_id": "peak oil",
    "countries": ['USA','Russia',''],
    "likelihood": [1,2,3],
    "relevance": [1,2,3],
    "intensity": [1,2,3]
 }]```
</div>
</div>
</p>
<p>I want to remove empty strings in the countries array. Now here's the catch, I want to remove the same index in likelihood,relevance and intensity as well.</p>
<p>I tried this:</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>// replacement for splice, array.remove(index)
Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
      };

data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.remove(index)
            obj.relevance.remove(index)
            obj.intensity.remove(index)
          }
        })
      })</code>```

Example output on the above data:

[{
        "_id": "plastic",
        "countries": ['Egypt','Iran'],
        "likelihood": [1,3],
        "relevance": [1,3],
        "intensity": [1,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia'],
        "likelihood": [1,2],
        "relevance": [1,2],
        "intensity": [1,2]
 }]```

As you can see the index which was empty in the countries array was removed along with likelihood,relevance,intensity.

How can I achieve this ?

UPDATE

I want multiple strings to be removed.

答:
Edited::

if your data be like this :

let data = [{
    "_id": "plastic",
    "countries": ['Egypt', '', 'Iran'],
    "likelihood": [1, 2, 3],
    "relevance": [1, 2, 3],
    "intensity": [1, 2, 3]
  },
  {
    "_id": "plastic",
    "countries": ['Egypt', '', 'Iran', ''],
    "likelihood": [1, 2, 3, 4],
    "relevance": [1, 2, 3, 5],
    "intensity": [1, 2, 3, 6]
  },
  {
    "_id": "peak oil",
    "countries": ['USA', 'Russia', ''],
    "likelihood": [1, 2, 3],
    "relevance": [1, 2, 3],
    "intensity": [1, 2, 3]
  }
]

for (let i = 0; i < data.length; i++) {
  let indexes = []
  let j = 0
  while ((j = data[i].countries.indexOf("", j + 1)) != -1) {
    indexes.push(j);
  }
  for (const key of ["countries", "likelihood", "relevance", "intensity"]) {
    for (let k = 0; k < indexes.length; k++) {
      data[i][key].splice(indexes[k] - k, 1)
    }
  }
}```
</div>
</div>
</p>
<p>you can do something like this :</p>
```for(let i=0;i<data.length;i++){
     let indexes=[]
     let j=0
while ((j = data[i].countries.indexOf("", j+1)) != -1){
        indexes.push(j);
    }

  for(let k =0 ; k< indexes.length;k++){
       for (const key of ["countries","likelihood", "relevance","intensity"]){
        data[i][key].splice(indexes[k],1)
    }
  }
}
```

Body:
I have this array of objects:

const data = [{
    "_id": "plastic",
    "countries": ['Egypt','','Iran','',''],
    "likelihood": [1,2,3,4,5],
    "relevance": [1,2,3,4,5],
    "intensity": [1,2,3,4,5]
},
{
    "_id": "peak oil",
    "countries": ['USA','Russia',''],
    "likelihood": [1,2,3],
    "relevance": [1,2,3],
    "intensity": [1,2,3]
 }]

I want to remove empty strings in the countries array. Now here's the catch, I want to remove the same index in likelihood,relevance and intensity as well.

I tried this:

// replacement for splice, array.remove(index)
Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
      };

data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.remove(index)
            obj.relevance.remove(index)
            obj.intensity.remove(index)
          }
        })
      })

Example output on the above data:

[{
        "_id": "plastic",
        "countries": ['Egypt','Iran'],
        "likelihood": [1,3],
        "relevance": [1,3],
        "intensity": [1,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia'],
        "likelihood": [1,2],
        "relevance": [1,2],
        "intensity": [1,2]
 }]

As you can see the index which was empty in the countries array was removed along with likelihood,relevance,intensity.

How can I achieve this ?

UPDATE

I want multiple strings to be removed.

Body:
Edited::

if your data be like this :

let data = [{
    "_id": "plastic",
    "countries": ['Egypt', '', 'Iran'],
    "likelihood": [1, 2, 3],
    "relevance": [1, 2, 3],
    "intensity": [1, 2, 3]
  },
  {
    "_id": "plastic",
    "countries": ['Egypt', '', 'Iran', ''],
    "likelihood": [1, 2, 3, 4],
    "relevance": [1, 2, 3, 5],
    "intensity": [1, 2, 3, 6]
  },
  {
    "_id": "peak oil",
    "countries": ['USA', 'Russia', ''],
    "likelihood": [1, 2, 3],
    "relevance": [1, 2, 3],
    "intensity": [1, 2, 3]
  }
]

for (let i = 0; i < data.length; i++) {
  let indexes = []
  let j = 0
  while ((j = data[i].countries.indexOf("", j + 1)) != -1) {
    indexes.push(j);
  }
  for (const key of ["countries", "likelihood", "relevance", "intensity"]) {
    for (let k = 0; k < indexes.length; k++) {
      data[i][key].splice(indexes[k] - k, 1)
    }
  }
}

you can do something like this :

for(let i=0;i<data.length;i++){
     let indexes=[]
     let j=0
while ((j = data[i].countries.indexOf("", j+1)) != -1){
        indexes.push(j);
    }

  for(let k =0 ; k< indexes.length;k++){
       for (const key of ["countries","likelihood", "relevance","intensity"]){
        data[i][key].splice(indexes[k],1)
    }
  }
}


问:
Help with "Collection was modified; enumeration operation might not execute."
When I use the following code, I'm getting a "Collection was modified; enumeration operation might not execute" error.  If I understand this correctly, I think it means that I can't enumerate over this datatable and delete rows from it at the same time.  My question is, what else can I do to achieve the result of deleting certain rows from my datatable?
Here's my code:</p>

```<code>        // Now let's loop through the datatable and find any account with no
        // LYSMKWh value and less than 4000 KWh current usage.  We'll remove those
        // from the datatable.
        currentRow = 0;
        foreach (DataRow row in resultsDT.Rows)
        {
            if ((string)resultsDT.Rows[currentRow]["LYSMKWh"] == "0")
            {
                int intKWh = Convert.ToInt32(resultsDT.Rows[currentRow]["KWH"]);
                if (intKWh < 5000)
                {
                    resultsDT.Rows[currentRow].Delete();
                }
            }
            resultsDT.AcceptChanges();
            currentRow++;
        }
</code>```

答:
You can do one of two things:

1) You can iterate over the collection in reverse order using a for loop and remove the rows inline:

```<code>for(int i = resultsDT.Rows.Count - 1; i >= 0; i--)
{
    if ((string)resultsDT.Rows[i]["LYSMKWh"] == "0")
    {
        int intKWh = Convert.ToInt32(resultsDT.Rows[i]["KWH"]);
        if (intKWh < 5000)
        {
            resultsDT.Rows[i].Delete();
        }
    }
    resultsDT.AcceptChanges();
}
</code>```

2) You can add the rows you want to remove to a separate collection and then remove them after you iterate over the entire original collection. This is obviously less efficient so I'm not going to worry about a sample.

Body:
When I use the following code, I'm getting a "Collection was modified; enumeration operation might not execute" error.  If I understand this correctly, I think it means that I can't enumerate over this datatable and delete rows from it at the same time.  My question is, what else can I do to achieve the result of deleting certain rows from my datatable?
Here's my code:

        // Now let's loop through the datatable and find any account with no
        // LYSMKWh value and less than 4000 KWh current usage.  We'll remove those
        // from the datatable.
        currentRow = 0;
        foreach (DataRow row in resultsDT.Rows)
        {
            if ((string)resultsDT.Rows[currentRow]["LYSMKWh"] == "0")
            {
                int intKWh = Convert.ToInt32(resultsDT.Rows[currentRow]["KWH"]);
                if (intKWh < 5000)
                {
                    resultsDT.Rows[currentRow].Delete();
                }
            }
            resultsDT.AcceptChanges();
            currentRow++;
        }

Body:
You can do one of two things:

1) You can iterate over the collection in reverse order using a for loop and remove the rows inline:

for(int i = resultsDT.Rows.Count - 1; i >= 0; i--)
{
    if ((string)resultsDT.Rows[i]["LYSMKWh"] == "0")
    {
        int intKWh = Convert.ToInt32(resultsDT.Rows[i]["KWH"]);
        if (intKWh < 5000)
        {
            resultsDT.Rows[i].Delete();
        }
    }
    resultsDT.AcceptChanges();
}

2) You can add the rows you want to remove to a separate collection and then remove them after you iterate over the entire original collection. This is obviously less efficient so I'm not going to worry about a sample.


问:
Stopping Page Loading - Selenium Python
I unfortunately can not stop a page from loading using Selenium in Python.

I have tried:

driver.execute_script("window.stop();")

driver.set_page_load_timeout(10)

webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()

The page is a .cgi that constantly loads. I would like to either scrape data from a class on the page or the page title, however neither works with the 3 methods above.

When I try to manually press ESC, or click the cross, it works perfectly.

Thank you for reading.

答:
You didn't share your code and a page you are working on, so we can only guess.

So, in case you really tried all the above correctly and it still not helped try adding Eager page loading strategy to your driver options.

Eager page loading strategy will make WebDriver wait until the initial HTML document has been completely loaded and parsed, and discards loading of stylesheets, images and subframes (DOMContentLoaded event fire is returned).

With it your code will look something like this:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.page_load_strategy = 'eager'
driver = webdriver.Chrome(options=options)
# Navigate to url
driver.get(your_page_url)
</code>```

UPD

You are trying to upload a file with Selenium and doing it wrong.

To upload the file with Selenium you need to send a full file path to that element.

So, if the file you want to upload is located by C:/Model.lp your code should be:

driver.find_element_by_xpath("//input[@name='field.1']").send_keys("C:/Model.lp")
```

Title: Stopping Page Loading - Selenium Python

Body:
You didn't share your code and a page you are working on, so we can only guess.

So, in case you really tried all the above correctly and it still not helped try adding Eager page loading strategy to your driver options.

Eager page loading strategy will make WebDriver wait until the initial HTML document has been completely loaded and parsed, and discards loading of stylesheets, images and subframes (DOMContentLoaded event fire is returned).

With it your code will look something like this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.page_load_strategy = 'eager'
driver = webdriver.Chrome(options=options)
# Navigate to url
driver.get(your_page_url)

UPD

You are trying to upload a file with Selenium and doing it wrong.

To upload the file with Selenium you need to send a full file path to that element.

So, if the file you want to upload is located by C:/Model.lp your code should be:

driver.find_element_by_xpath("//input[@name='field.1']").send_keys("C:/Model.lp")


问:
Vec<Vec<T>> into Vec<T>
```<code>let a = vec![ vec![1, 2], vec![3, 4], vec![5, 6] ];
</code>```

How can I gather into a single Vec all the values contained in all the Vecs in a ?

答:
flat_map also flattens a vector of vectors.

```<code>let a = vec![vec![1, 2], vec![3, 4], vec![5, 6]];
let merged = a.into_iter().flat_map(|s| s).collect::<Vec<i32>>();
println!("{:?}", merged);

[1, 2, 3, 4, 5, 6]
</code>```

Rust Playground

Title: Vec<Vec<T>> into Vec<T>

Body:
let a = vec![ vec![1, 2], vec![3, 4], vec![5, 6] ];

How can I gather into a single Vec all the values contained in all the Vecs in a ?

Body:
flat_map also flattens a vector of vectors.

let a = vec![vec![1, 2], vec![3, 4], vec![5, 6]];
let merged = a.into_iter().flat_map(|s| s).collect::<Vec<i32>>();
println!("{:?}", merged);

[1, 2, 3, 4, 5, 6]

Rust Playground


问:
jQuery index on each function
I am curious why I need this index

```<code>$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });
        });
    });
</code>```

Why do I need the "[0]" in "var buttonId = $(this)[0]…"  Without it, I get an attributes["id"] is null error..

答:
```<code>$(".divToggle").each(function(index, element){
    var buttonId = element.id,
        idParts = buttonId.split('_'),
        uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";

    $(element).click(function() {
         $("#" + uniquePart).toggle("slow");
    });
});
</code>```

Title: jQuery index on each function

Body:
I am curious why I need this index

$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });
        });
    });

Why do I need the "[0]" in "var buttonId = $(this)[0]…"  Without it, I get an attributes["id"] is null error..


问:
My male and female toggle button is not working in bmi calculator
Since i had moved my Gesturedetector widgit into reusable_child.dart file my app became non functional. Please someone help me to fix the issue of male female toggle

Previously when then entire code was in one file(i.e BODY.dart) it was working properly this issue came after i created sepearte dart files for each

BODY.dart

```<code>import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'reusable_card.dart';
import 'reusable_child.dart';
import 'AppDrawer.dart';

const double bottomContainerHeight = 80.0;
const Color containerColours = Color(0xFF1D1E33);
const Color inactiveContainerColor = Color(0xFF111328);

enum GenderType {
  MALE,
  FEMALE,
}

class BODY extends StatefulWidget {
  const BODY({Key? key}) : super(key: key);

  @override
  _BODYState createState() => _BODYState();
}

class _BODYState extends State<BODY> {
  GenderType selectedGender = GenderType.MALE;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: AppDrawer(),
      appBar: AppBar(
          title: Padding(
          padding: const EdgeInsets.all(50.0),
          child: Text('BMI Calculator'),
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                Expanded(
                  child: ReusableCard(
                    colour: selectedGender == GenderType.MALE
                        ? containerColours
                        : inactiveContainerColor,
                    cardChild: ReusableChild(
                      containerIcon: FontAwesomeIcons.mars,
                      txt: 'MALE',
                    ),
                    onPress: () {
                      setState(() {
                        selectedGender = GenderType.MALE;
                      });
                    },
                  ),
                ),
                Expanded(
                  child: ReusableCard(
                    cardChild: ReusableChild(
                      containerIcon: FontAwesomeIcons.venus,
                      txt: 'FEMALE',
                    ),
                    colour: selectedGender == GenderType.FEMALE
                        ? containerColours
                        : inactiveContainerColor,
                    onPress: () {
                      selectedGender = GenderType.FEMALE;
                    },
                  ),
                )
              ],
            ),
          ),
          Expanded(
            child: ReusableCard(
              onPress: () {},
              colour: containerColours,
            ),
          ),
          Expanded(
            child: Row(
              children: [
                Expanded(
                  child: ReusableCard(
                    onPress: () {},
                    colour: containerColours,
                  ),
                ),
                Expanded(
                  child: ReusableCard(
                    onPress: () {},
                    colour: containerColours,
                  ),
                ),
              ],
            ),
          ),
          Container(
            color: Colors.pink.shade400,
            width: double.infinity,
            height: bottomContainerHeight,
            margin: EdgeInsets.only(top: 10.0),
            child: Padding(
              padding: const EdgeInsets.all(17.0),
              child: Text(
                'Calculate',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 30,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
</code>```

resuable_card.dart

```<code>import 'package:flutter/material.dart';

class ReusableCard extends StatelessWidget {
  ReusableCard({
    required this.colour,
    this.cardChild,
    this.onPress,
  });
  final Color colour;
  final Widget? cardChild;
  final VoidCallback? onPress;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onPress,
      child: Container(
        child: cardChild,
        margin: EdgeInsets.all(15.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.0),
          color: colour,
        ),
      ),
    );
  }
}
</code>```

resuable_child.dart

```<code>import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class ReusableChild extends StatelessWidget {
  final containerIcon;
  final String txt;
  ReusableChild({this.containerIcon = FontAwesomeIcons.amazon, this.txt = ''});
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(
          containerIcon,
          color: Color(0xFFffffff),
          size: 80.0,
        ),
        SizedBox(
          height: 10,
        ),
        Text(
          txt,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 18.0,
            color: Colors.grey.shade500,
          ),
        )
      ],
    );
  }
}
</code>```

答:
the issue is in your FEMALE ReusableCard's onPress

onPress: () {
  selectedGender = GenderType.FEMALE;
},
```
<p>you forgot to add <code>setState</code> here as well</p>
<pre class="lang-dart prettyprint-override"><code>onPress: () {
  setState(() {
    selectedGender = GenderType.FEMALE;
  });
},
</code>```

Body:
Since i had moved my Gesturedetector widgit into reusable_child.dart file my app became non functional. Please someone help me to fix the issue of male female toggle

Previously when then entire code was in one file(i.e BODY.dart) it was working properly this issue came after i created sepearte dart files for each

BODY.dart

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'reusable_card.dart';
import 'reusable_child.dart';
import 'AppDrawer.dart';

const double bottomContainerHeight = 80.0;
const Color containerColours = Color(0xFF1D1E33);
const Color inactiveContainerColor = Color(0xFF111328);

enum GenderType {
  MALE,
  FEMALE,
}

class BODY extends StatefulWidget {
  const BODY({Key? key}) : super(key: key);

  @override
  _BODYState createState() => _BODYState();
}

class _BODYState extends State {
  GenderType selectedGender = GenderType.MALE;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: AppDrawer(),
      appBar: AppBar(
          title: Padding(
          padding: const EdgeInsets.all(50.0),
          child: Text('BMI Calculator'),
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                Expanded(
                  child: ReusableCard(
                    colour: selectedGender == GenderType.MALE
                        ? containerColours
                        : inactiveContainerColor,
                    cardChild: ReusableChild(
                      containerIcon: FontAwesomeIcons.mars,
                      txt: 'MALE',
                    ),
                    onPress: () {
                      setState(() {
                        selectedGender = GenderType.MALE;
                      });
                    },
                  ),
                ),
                Expanded(
                  child: ReusableCard(
                    cardChild: ReusableChild(
                      containerIcon: FontAwesomeIcons.venus,
                      txt: 'FEMALE',
                    ),
                    colour: selectedGender == GenderType.FEMALE
                        ? containerColours
                        : inactiveContainerColor,
                    onPress: () {
                      selectedGender = GenderType.FEMALE;
                    },
                  ),
                )
              ],
            ),
          ),
          Expanded(
            child: ReusableCard(
              onPress: () {},
              colour: containerColours,
            ),
          ),
          Expanded(
            child: Row(
              children: [
                Expanded(
                  child: ReusableCard(
                    onPress: () {},
                    colour: containerColours,
                  ),
                ),
                Expanded(
                  child: ReusableCard(
                    onPress: () {},
                    colour: containerColours,
                  ),
                ),
              ],
            ),
          ),
          Container(
            color: Colors.pink.shade400,
            width: double.infinity,
            height: bottomContainerHeight,
            margin: EdgeInsets.only(top: 10.0),
            child: Padding(
              padding: const EdgeInsets.all(17.0),
              child: Text(
                'Calculate',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 30,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

resuable_card.dart

import 'package:flutter/material.dart';

class ReusableCard extends StatelessWidget {
  ReusableCard({
    required this.colour,
    this.cardChild,
    this.onPress,
  });
  final Color colour;
  final Widget? cardChild;
  final VoidCallback? onPress;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onPress,
      child: Container(
        child: cardChild,
        margin: EdgeInsets.all(15.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.0),
          color: colour,
        ),
      ),
    );
  }
}

resuable_child.dart

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class ReusableChild extends StatelessWidget {
  final containerIcon;
  final String txt;
  ReusableChild({this.containerIcon = FontAwesomeIcons.amazon, this.txt = ''});
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(
          containerIcon,
          color: Color(0xFFffffff),
          size: 80.0,
        ),
        SizedBox(
          height: 10,
        ),
        Text(
          txt,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 18.0,
            color: Colors.grey.shade500,
          ),
        )
      ],
    );
  }
}

Body:
the issue is in your FEMALE ReusableCard's onPress

onPress: () {
  selectedGender = GenderType.FEMALE;
},

you forgot to add setState here as well

onPress: () {
  setState(() {
    selectedGender = GenderType.FEMALE;
  });
},


问:
Angular: Cyclic Dependency
Why is currentdate in this.currentdate.getTime() coming back as undefined?

```<code>newlisting = this.formBuilder.group({
    availabledate: new FormGroup({
      xyz: new FormControl()
    },[this.mainservice.getcurrenttime.bind(this)])
})
</code>```
```<code>@Injectable({providedIn: 'root'})
export class MainService {

  constructor(){}

  currentdate: Date = new Date();

  getcurrenttime(control: FormGroup){

    console.log(this.currentdate.getTime())  <~~ Generates Error!!!

    if(condition){
      return {date: true};
    }
    return null;
  }

}
</code>```

答:
When you do something like this.mainservice.getcurrenttime.bind(this), it creates a bound function.

Due to the above created bound function, in your case within getcurrenttime() method this would be referred to as YourComponent instance.

Since the component doesn't have any property named currentdate declared, this.currentdate will result in undefined and trying to read getTime() on it will result in an error.

Below are few of the alternatives you can use:

Bind it to the mainservice instance

this.mainservice.getcurrenttime.bind(this.mainservice)
```
<ol start="2">
<li>Return a ValidatorFn from <code>getcurrenttime</code> as below, so that you don't lose the <code>this</code> context. <em>(I would recommend this approach)</em></li>
</ol>
<pre class="lang-ts prettyprint-override"><code>// Within MainService
getcurrenttime(): ValidatorFn {
  return (control: AbstractControl) => {
    console.log(this.currentdate.getTime());
    // Your logic
    return null;
  }
}

// Within YourComponent
this.mainservice.getcurrenttime()
</code>```

Define getcurrenttime as an arrow function and then you don't need to use bind.

// Within MainService
getcurrenttime = (control: AbstractControl) => {
  console.log(this.currentdate.getTime());
  // Your logic
  return null;
}

// Within YourComponent
this.mainservice.getcurrenttime  // No need to use .bind(...)
```

Should I write methods as arrow functions in Angular class

Title: Angular: Cyclic Dependency

Body:
Why is currentdate in this.currentdate.getTime() coming back as undefined?

newlisting = this.formBuilder.group({
    availabledate: new FormGroup({
      xyz: new FormControl()
    },[this.mainservice.getcurrenttime.bind(this)])
})

@Injectable({providedIn: 'root'})
export class MainService {

  constructor(){}

  currentdate: Date = new Date();

  getcurrenttime(control: FormGroup){

    console.log(this.currentdate.getTime())  <~~ Generates Error!!!

    if(condition){
      return {date: true};
    }
    return null;
  }

}

Body:
When you do something like this.mainservice.getcurrenttime.bind(this), it creates a bound function.

Due to the above created bound function, in your case within getcurrenttime() method this would be referred to as YourComponent instance.

Since the component doesn't have any property named currentdate declared, this.currentdate will result in undefined and trying to read getTime() on it will result in an error.

Below are few of the alternatives you can use:

Bind it to the mainservice instance

this.mainservice.getcurrenttime.bind(this.mainservice)

Return a ValidatorFn from getcurrenttime as below, so that you don't lose the this context. (I would recommend this approach)

// Within MainService
getcurrenttime(): ValidatorFn {
  return (control: AbstractControl) => {
    console.log(this.currentdate.getTime());
    // Your logic
    return null;
  }
}

// Within YourComponent
this.mainservice.getcurrenttime()

Define getcurrenttime as an arrow function and then you don't need to use bind.

// Within MainService
getcurrenttime = (control: AbstractControl) => {
  console.log(this.currentdate.getTime());
  // Your logic
  return null;
}

// Within YourComponent
this.mainservice.getcurrenttime  // No need to use .bind(...)

Should I write methods as arrow functions in Angular class


答:
to remove, you can use splice

const datas=[{
        "_id": "plastic",
        "countries": ['Egypt','','Iran'],
        "likelihood": [1,2,3],
        "relevance": [1,2,3],
        "intensity": [1,2,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia',''],
        "likelihood": [1,2,3],
        "relevance": [1,2,3],
        "intensity": [1,2,3]
 }];

for (const i in datas){
    const rmIdx=datas[i]["countries"].findIndex(val=>val==="");
    for (const key of ["countries","likelihood", "relevance","intensity"]){
        datas[i][key].splice(rmIdx,1)
    }
}

console.log(datas)
```

Title: Javascript: How to remove empty string values from an array?


问:
regex for Iraninan ID Serial number
I need a regex expression to match Iranian ID serial number(سریال شماره شناسنامه) which first char is a non-latin letter in range of ب-ی or one non-latin word الف.

The texts we need to validate should be in a format like:

```<code>الف/12 123456
ب/25 123456
ج/11 123456
</code>```

ps: the expressions start with a letter. (StackOverflow isn't supporting RTL)

My attempt so far:

```<code>(\bالف\b|[ب-ی]{1})[\/][0-9]{2}\s{1}[0-9]{6}
</code>```

https://regex101.com/r/FsZFN5/1

Title: regex for Iraninan ID Serial number

Body:
I need a regex expression to match Iranian ID serial number(سریال شماره شناسنامه) which first char is a non-latin letter in range of ب-ی or one non-latin word الف.

The texts we need to validate should be in a format like:

الف/12 123456
ب/25 123456
ج/11 123456

ps: the expressions start with a letter. (StackOverflow isn't supporting RTL)

My attempt so far:

(\bالف\b|[ب-ی]{1})[\/][0-9]{2}\s{1}[0-9]{6}

https://regex101.com/r/FsZFN5/1

Body:
new series like : الف/12 123456

{char} {2 digit} / {6 digit}

solution:

 [\u0600-\u06FF]{1,3}[0-9]{2}\/[0-9]{6}


答:
Your code works. Can't say it's the cleanest approach, but it correctly removes the values.

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

const data = [{
        "_id": "plastic",
        "countries": ['Egypt','','Iran'],
        "likelihood": [1,2,3],
        "relevance": [1,2,3],
        "intensity": [1,2,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia',''],
        "likelihood": [1,2,3],
        "relevance": [1,2,3],
        "intensity": [1,2,3]
 }]

data.forEach(obj => {
  obj.countries.forEach((country, index) => {
    if (country === "") {
      obj.countries.remove(index)
      obj.likelihood.remove(index)
      obj.relevance.remove(index)
      obj.intensity.remove(index)
    }
  })
})

console.log(data);```
</div>
</div>
</p>
<p>However, in your code, you are directly editing <code>Array.prototype</code>. This is a bad practice and can cause issues in the future. Instead, you can directly use <code>Array.splice</code> to remove the items.</p>
<p><strong>EDIT:</strong> This now remove all instances of empty strings</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>const data = [{
    "_id": "plastic",
    "countries": ['Egypt', '', 'Iran', ''],
    "likelihood": [1, 2, 3, 4],
    "relevance": [1, 2, 3, 4],
    "intensity": [1, 2, 3, 4]
  },
  {
    "_id": "peak oil",
    "countries": ['', 'USA', 'Russia', ''],
    "likelihood": [1, 2, 3, 4],
    "relevance": [1, 2, 3, 4],
    "intensity": [1, 2, 3, 4]
  }
]

const cleaned = data.map(thing => {
  while (thing.countries.includes('')) {
    const index = thing.countries.indexOf('');
    thing.countries.splice(index, 1);
    thing.likelihood.splice(index, 1);
    thing.relevance.splice(index, 1);
    thing.intensity.splice(index, 1);
  }
  return thing;
})

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

Body:
Your code works. Can't say it's the cleanest approach, but it correctly removes the values.

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

const data = [{
        "_id": "plastic",
        "countries": ['Egypt','','Iran'],
        "likelihood": [1,2,3],
        "relevance": [1,2,3],
        "intensity": [1,2,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia',''],
        "likelihood": [1,2,3],
        "relevance": [1,2,3],
        "intensity": [1,2,3]
 }]

data.forEach(obj => {
  obj.countries.forEach((country, index) => {
    if (country === "") {
      obj.countries.remove(index)
      obj.likelihood.remove(index)
      obj.relevance.remove(index)
      obj.intensity.remove(index)
    }
  })
})

console.log(data);

However, in your code, you are directly editing Array.prototype. This is a bad practice and can cause issues in the future. Instead, you can directly use Array.splice to remove the items.

EDIT: This now remove all instances of empty strings

const data = [{
    "_id": "plastic",
    "countries": ['Egypt', '', 'Iran', ''],
    "likelihood": [1, 2, 3, 4],
    "relevance": [1, 2, 3, 4],
    "intensity": [1, 2, 3, 4]
  },
  {
    "_id": "peak oil",
    "countries": ['', 'USA', 'Russia', ''],
    "likelihood": [1, 2, 3, 4],
    "relevance": [1, 2, 3, 4],
    "intensity": [1, 2, 3, 4]
  }
]

const cleaned = data.map(thing => {
  while (thing.countries.includes('')) {
    const index = thing.countries.indexOf('');
    thing.countries.splice(index, 1);
    thing.likelihood.splice(index, 1);
    thing.relevance.splice(index, 1);
    thing.intensity.splice(index, 1);
  }
  return thing;
})

console.log(cleaned);


问:
Django 404 error-page not found & No CSS renders
New-ish coder and first time stack overflow poster. I've made a django project with 3 pages. Sometimes no pages are found, sometimes the index page loads without 404 error but I can't link to other pages and the css files I've pointed it to doesn't render.

Errors I'm getting is:

404 error

I have slept on the problem, looked up file formats to make sure my project and app url.py is correct. added app to settings. imported correct classes.  I have also tried clearing my browser data on chrome and using a different browser.

If anyone could take a look at my small project on github that would be amazing. https://github.com/Connell-L/portfolio_website is the link or if anyone wants me to post code files on codepen or something I'm more than happy to do it.

Edit: https://github.com/Connell-L/portfolio_website/tree/branch1 it's here sorry lol

答:
You need to add STATICFILES_DIRS and STATIC_ROOT to your project settings.py

like this:

 BASE_DIR = Path(__file__).resolve().parent.
```
<p>the above line of code has to be at the bigining of your settings.py file</p>
```STATIC_URL = "static/"
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
```

Body:
You need to add STATICFILES_DIRS and STATIC_ROOT to your project settings.py

like this:

 BASE_DIR = Path(__file__).resolve().parent.

the above line of code has to be at the bigining of your settings.py file

STATIC_URL = "static/"
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")


问:
Dart: How to map CSV data to a list of a model?
Let's say, In a file crops.csv, I have a simple dataset in a format like this:

```<code>id,cropType,cropName
1,food,rice
2,cash,sugarcane
3,horticulture,orange
</code>```

And I have a Model Class named as foodCrops:

```<code>class foodCrops {
  int id;
  String cropType;
  String cropName;

  foodCrops(this.id, this.cropType, this.cropName);
}
</code>```

How do I convert those data from csv file to a List of class foodCrops ?

```<code>List<foodCrops>
</code>```

答:
Another way to do that.

import 'package:fast_csv/fast_csv.dart' as _fast_csv;

void main(List<String> args) {
  final data = _fast_csv.parse(_source);
  final list = data.skip(1).map((e) => FoodCrops(int.parse(e[0]), e[1], e[2]));
  print(list.join('\n'));
}

const _source = '''
id,cropType,cropName
1,food,rice
2,cash,sugarcane
3,horticulture,orange
''';

class FoodCrops {
  int id;
  String cropType;
  String cropName;

  FoodCrops(this.id, this.cropType, this.cropName);

  @override
  String toString() {
    return '$id $cropType $cropName';
  }
}

```
<p>Output:</p>
```1 food rice
2 cash sugarcane
3 horticulture orange
```

Body:
Let's say, In a file crops.csv, I have a simple dataset in a format like this:

id,cropType,cropName
1,food,rice
2,cash,sugarcane
3,horticulture,orange

And I have a Model Class named as foodCrops:

class foodCrops {
  int id;
  String cropType;
  String cropName;

  foodCrops(this.id, this.cropType, this.cropName);
}

How do I convert those data from csv file to a List of class foodCrops ?

List<foodCrops>

Body:
Another way to do that.

import 'package:fast_csv/fast_csv.dart' as _fast_csv;

void main(List<String> args) {
  final data = _fast_csv.parse(_source);
  final list = data.skip(1).map((e) => FoodCrops(int.parse(e[0]), e[1], e[2]));
  print(list.join('\n'));
}

const _source = '''
id,cropType,cropName
1,food,rice
2,cash,sugarcane
3,horticulture,orange
''';

class FoodCrops {
  int id;
  String cropType;
  String cropName;

  FoodCrops(this.id, this.cropType, this.cropName);

  @override
  String toString() {
    return '$id $cropType $cropName';
  }
}

Output:

1 food rice
2 cash sugarcane
3 horticulture orange


问:
How to reset router-link id in Vuejs?
HelloWorld.vue

<template>

    Vuejs dynamic routing

      {{ item.id }}.
      <router-link :to="{ name: 'UserWithID', params: { id: item.id } }">
        {{ item.kk }}
      </router-link>

    <User />

</template>

```
</div>
</div>
</p>
<p><strong>datalist.vue</strong></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-html lang-html prettyprint-override"><code>export const datalist = [
  { id: 1, val: "11", kk: "potter" },
  { id: 2, val: "22", kk: "james" },
  { id: 3, val: "55", kk: "limda" },
  { id: 4, val: "77", kk: "stepen" }
];
 </code>```

main.js

import VueRouter from "vue-router";
import HelloWorld from "./components/HelloWorld.vue";
import Vuex from "vuex"
import createPersistedState from "vuex-persistedstate";

Vue.use(VueRouter);

const store = new Vuex.Store(
  {
    plugins: [createPersistedState({

      storage: window.sessionStorage,
    })],
    state: {

    },
    mutations: {
      // setAuthentication(state, status) {
      //   state.authenticated = status;
      // }
    }
  }
);```
</div>
</div>
</p>
<p>I want to reset the <code>router-link</code> id. the issue is like, When I click on router-link, in the URL section, I can see pathname/component name followed by id.</p>
<p>When I click on the back button every time I can see my action like:</p>
```/1../2 .../3
```

In the URL section. I want to reset the value when clicking on the back button. and on page refresh array from v-for is getting cleared.

Working code:- https://codesandbox.io/s/autumn-cherry-p5s9b?file=/src/main.js

答:
The problem with your code is that you did not use history mode for the router, I highly recommend this mode because it resets the router, you cannot do anything about it in the helloworld vue, you have to go to your router file and add/change this code:

```<code>const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});
</code>```

I hope this will work for you, this will also remove the # in your route.

If this still does not work, you can try creating a new vue project with the router set to history mode.

Title: How to reset router-link id in Vuejs?

Body:
HelloWorld.vue

<template>

    Vuejs dynamic routing

      {{ item.id }}.
      <router-link :to="{ name: 'UserWithID', params: { id: item.id } }">
        {{ item.kk }}
      </router-link>

    <User />

</template>

datalist.vue

export const datalist = [
  { id: 1, val: "11", kk: "potter" },
  { id: 2, val: "22", kk: "james" },
  { id: 3, val: "55", kk: "limda" },
  { id: 4, val: "77", kk: "stepen" }
];

main.js

import VueRouter from "vue-router";
import HelloWorld from "./components/HelloWorld.vue";
import Vuex from "vuex"
import createPersistedState from "vuex-persistedstate";

Vue.use(VueRouter);

const store = new Vuex.Store(
  {
    plugins: [createPersistedState({

      storage: window.sessionStorage,
    })],
    state: {

    },
    mutations: {
      // setAuthentication(state, status) {
      //   state.authenticated = status;
      // }
    }
  }
);

I want to reset the router-link id. the issue is like, When I click on router-link, in the URL section, I can see pathname/component name followed by id.

When I click on the back button every time I can see my action like:

/1../2 .../3

In the URL section. I want to reset the value when clicking on the back button. and on page refresh array from v-for is getting cleared.

Working code:- https://codesandbox.io/s/autumn-cherry-p5s9b?file=/src/main.js

Body:
The problem with your code is that you did not use history mode for the router, I highly recommend this mode because it resets the router, you cannot do anything about it in the helloworld vue, you have to go to your router file and add/change this code:

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

I hope this will work for you, this will also remove the # in your route.

If this still does not work, you can try creating a new vue project with the router set to history mode.


问:
Encode String to HEX
i have my function to convert string to hex:

```<code>function encode(str){
    str = encodeURIComponent(str).split('%').join('');
    return str.toLowerCase();
}
</code>```

example:

守护村子

alert(encode('守护村子'));

the output would be:

e5ae88e68aa4e69d91e5ad90

It works on Chinese characters. But when i do it with English letters

alert(encode('Hello World'));

it outputs:

hello20world

I have tried this for converting string to hex:

```<code>function String2Hex(tmp) {
    var str = '';
    for(var i = 0; i < tmp.length; i++) {
        str += tmp[i].charCodeAt(0).toString(16);
    }
    return str;
}
</code>```

then tried it on the  Chinese characters above, but it outputs the UTF-8 HEX:

5b8862a467515b50

not the ANSI Hex:

e5ae88e68aa4e69d91e5ad90

I also have searched converting UFT8 to ANSI but no luck.
Anyone could help me? Thanks!

答:
Another way to do it

function toHex(txt){
    const encoder = new TextEncoder();
    return Array
        .from(encoder.encode(txt))
        .map(b => b.toString(16).padStart(2, '0'))
        .join('')
}
```

Title: Encode String to HEX

Body:
i have my function to convert string to hex:

function encode(str){
    str = encodeURIComponent(str).split('%').join('');
    return str.toLowerCase();
}

example:

守护村子

alert(encode('守护村子'));

the output would be:

e5ae88e68aa4e69d91e5ad90

It works on Chinese characters. But when i do it with English letters

alert(encode('Hello World'));

it outputs:

hello20world

I have tried this for converting string to hex:

function String2Hex(tmp) {
    var str = '';
    for(var i = 0; i < tmp.length; i++) {
        str += tmp[i].charCodeAt(0).toString(16);
    }
    return str;
}

then tried it on the  Chinese characters above, but it outputs the UTF-8 HEX:

5b8862a467515b50

not the ANSI Hex:

e5ae88e68aa4e69d91e5ad90

I also have searched converting UFT8 to ANSI but no luck.
Anyone could help me? Thanks!


问:
I want to access the products with total amount
I have 2 tables. One is product(id, name). another is In(id, amount, products_id).
I am trying to get product name with total amount.
Example:
Aerobat-34
God of war-3
Rs537-15

I Joined the tables. Now output is

```<code>[{"name":"Aerobat","amount":"10"},{"name":"Aerobat","amount":null},{"name":"Aerobat","amount":null},{"name":"Aerobat","amount":null},{"name":"Aerobat","amount":"2"},{"name":"Aerobat","amount":"56"},{"name":"Aerobat","amount":"56"},{"name":"god of war","amount":"7"},{"name":"god of war","amount":"23"},{"name":"Rs537","amount":null},{"name":"Rs537","amount":null},{"name":"Rs537","amount":null}]
</code>```
```<code>public function index()
    {
        $product = DB::table('Products')
            ->join('ins', 'products.id', '=', 'ins.products_id')
            ->select('Products.name', 'ins.amount')
            ->get();
        echo $product;
    }
</code>```

How to find the expected result?

答:
you should use Model relations
first, create a function in the Product model that is called ins()

```<code>public function ins()
{
    return $this->hasMany('App\Models\Ins', 'product_id');
}
</code>```

and also you can declare a virtual column for product that executes the total amount of this product.
Notice, you should set name with "get" as prefix and "Attribute" as postfix

```<code>public function getTotalAmountAttribute()
{
    $totalAmount=0;
    foreach($this->ins as $item){
         $totalAmount+=$item->amount??0
    }
    return $totalAmount;
}
</code>```

and finally, you can use both fields like name & total amount

Body:
I have 2 tables. One is product(id, name). another is In(id, amount, products_id).
I am trying to get product name with total amount.
Example:
Aerobat-34
God of war-3
Rs537-15

I Joined the tables. Now output is

[{"name":"Aerobat","amount":"10"},{"name":"Aerobat","amount":null},{"name":"Aerobat","amount":null},{"name":"Aerobat","amount":null},{"name":"Aerobat","amount":"2"},{"name":"Aerobat","amount":"56"},{"name":"Aerobat","amount":"56"},{"name":"god of war","amount":"7"},{"name":"god of war","amount":"23"},{"name":"Rs537","amount":null},{"name":"Rs537","amount":null},{"name":"Rs537","amount":null}]

public function index()
    {
        $product = DB::table('Products')
            ->join('ins', 'products.id', '=', 'ins.products_id')
            ->select('Products.name', 'ins.amount')
            ->get();
        echo $product;
    }

How to find the expected result?

Body:
you should use Model relations
first, create a function in the Product model that is called ins()

public function ins()
{
    return $this->hasMany('App\Models\Ins', 'product_id');
}

and also you can declare a virtual column for product that executes the total amount of this product.
Notice, you should set name with "get" as prefix and "Attribute" as postfix

public function getTotalAmountAttribute()
{
    $totalAmount=0;
    foreach($this->ins as $item){
         $totalAmount+=$item->amount??0
    }
    return $totalAmount;
}

and finally, you can use both fields like name & total amount