问:
javascript: pause setTimeout();
If I have an active timeout running that was set through

```<code>var t = setTimeout("dosomething()", 5000)
</code>```

Is there anyway to pause and resume it?

Is there any way to get the time remaining on the current timeout?

or do I have to in a variable, when the timeout is set, store the current time, then we we pause, get the difference between now and then?

答:
You can do like below to make setTimeout pausable on server side (Node.js)

```<code>const PauseableTimeout = function(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        global.clearTimeout(timerId);
        remaining -= Date.now() - start;
    };

    this.resume = function() {
        start = Date.now();
        global.clearTimeout(timerId);
        timerId = global.setTimeout(callback, remaining);
    };

    this.resume();
};
</code>```

and you can check it as below

```<code>var timer = new PauseableTimeout(function() {
    console.log("Done!");
}, 3000);
setTimeout(()=>{
    timer.pause();
    console.log("setTimeout paused");
},1000);

setTimeout(()=>{
    console.log("setTimeout time complete");
},3000)

setTimeout(()=>{
    timer.resume();
    console.log("setTimeout resume again");
},5000)
</code>```

Title: javascript: pause setTimeout();

Body:
If I have an active timeout running that was set through

var t = setTimeout("dosomething()", 5000)

Is there anyway to pause and resume it?

Is there any way to get the time remaining on the current timeout?

or do I have to in a variable, when the timeout is set, store the current time, then we we pause, get the difference between now and then?

Body:
You can do like below to make setTimeout pausable on server side (Node.js)

const PauseableTimeout = function(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        global.clearTimeout(timerId);
        remaining -= Date.now() - start;
    };

    this.resume = function() {
        start = Date.now();
        global.clearTimeout(timerId);
        timerId = global.setTimeout(callback, remaining);
    };

    this.resume();
};

and you can check it as below

var timer = new PauseableTimeout(function() {
    console.log("Done!");
}, 3000);
setTimeout(()=>{
    timer.pause();
    console.log("setTimeout paused");
},1000);

setTimeout(()=>{
    console.log("setTimeout time complete");
},3000)

setTimeout(()=>{
    timer.resume();
    console.log("setTimeout resume again");
},5000)


来源: stackexchange

问:
Issue when using map function with conditions and NaN value
Now I have a column in data which looks like this:

```<code>Column
'Star Wars: Episode I The Phantom Menace'
'Star Wars: Episode I The Phantom Menace'
NaN
'Star Wars: Episode I The Phantom Menace'
NaN
....
</code>```

What I tried to do was to convert the string column into a boolean column i.e True for real value and False for NaN.

I tried to classify the value with the following command:

```<code>import numpy as np
star_wars[column] = star_wars[column].map(lambda x: True if (x != np.nan) else False)
star_wars[column].value_counts()
</code>```

It returned that all the rows, either with true value and with nan value, to be true, which should not be the case.

I also tried to get the result through truthy/falsey value:

```<code>import numpy as np
star_wars[column] = star_wars[column].map(lambda x: True if (x) else False)
star_wars[column].value_counts()
</code>```

But interestingly, when I use the hard code:

```<code>true_false = {
    "Star Wars: Episode I  The Phantom Menace": True,
    np.nan: False,
}

star_wars[column] = star_wars[column].map(true_false)
</code>```

Then it works.

What's the issue for my solution? Or is there any document that I should refer to regarding to this issue?
Thank you for your help in advance!

答:
You don't need map at all.

You can simply use df.Column.notna(), like this:

This is the df:

```<code>In [504]: df
Out[504]:
                                    Column
0  Star Wars: Episode I The Phantom Menace
1  Star Wars: Episode I The Phantom Menace
2                                      NaN
3  Star Wars: Episode I The Phantom Menace
4                                      NaN

In [506]: df = df.Column.notna()
In [507]: df
Out[507]:
0     True
1     True
2    False
3     True
4    False
Name: Column, dtype: bool
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Now I have a column in data which looks like this:

Column
'Star Wars: Episode I The Phantom Menace'
'Star Wars: Episode I The Phantom Menace'
NaN
'Star Wars: Episode I The Phantom Menace'
NaN
....

What I tried to do was to convert the string column into a boolean column i.e True for real value and False for NaN.

I tried to classify the value with the following command:

import numpy as np
star_wars[column] = star_wars[column].map(lambda x: True if (x != np.nan) else False)
star_wars[column].value_counts()

It returned that all the rows, either with true value and with nan value, to be true, which should not be the case.

I also tried to get the result through truthy/falsey value:

import numpy as np
star_wars[column] = star_wars[column].map(lambda x: True if (x) else False)
star_wars[column].value_counts()

But interestingly, when I use the hard code:

true_false = {
    "Star Wars: Episode I  The Phantom Menace": True,
    np.nan: False,
}

star_wars[column] = star_wars[column].map(true_false)

Then it works.

What's the issue for my solution? Or is there any document that I should refer to regarding to this issue?
Thank you for your help in advance!

Body:
You don't need map at all.

You can simply use df.Column.notna(), like this:

This is the df:

In [504]: df
Out[504]:
                                    Column
0  Star Wars: Episode I The Phantom Menace
1  Star Wars: Episode I The Phantom Menace
2                                      NaN
3  Star Wars: Episode I The Phantom Menace
4                                      NaN

In [506]: df = df.Column.notna()
In [507]: df
Out[507]:
0     True
1     True
2    False
3     True
4    False
Name: Column, dtype: bool


问:
Unable to build and run c++ code in visual studio code
I have setup the correct path for mingw and am successfully able to compile my code using terminal in vscode. But when I press ctrl+shift+b to build i get the following error in my terminal

```<code>Executing task: C:\MinGW\bin\g++.exe -g 'c:\Users\Ansh Kapoor\Desktop\cpp\main.cpp' -o 'c:\Users\Ansh
Kapoor\Desktop\cpp\main.exe'<
/usr/bin/bash: C:MinGWbing++.exe: command not found
The terminal process terminated with exit code: 127
</code>```

whereas the same code is successfully executed when I write

```<code>    g++ main.cpp -o 'main.exe'
</code>```

Now I have checked the path and environment variables and all those things are correct.

答: The error in finding the proper path was because of using git bash as the terminal rather than windows powershell or cmd.</p>

Body:
I have setup the correct path for mingw and am successfully able to compile my code using terminal in vscode. But when I press ctrl+shift+b to build i get the following error in my terminal

Executing task: C:\MinGW\bin\g++.exe -g 'c:\Users\Ansh Kapoor\Desktop\cpp\main.cpp' -o 'c:\Users\Ansh
Kapoor\Desktop\cpp\main.exe'<
/usr/bin/bash: C:MinGWbing++.exe: command not found
The terminal process terminated with exit code: 127

whereas the same code is successfully executed when I write

    g++ main.cpp -o 'main.exe'

Now I have checked the path and environment variables and all those things are correct.


问:
Getting full branch coverage in equals() method with EclEmma
This is tedious, but I've got an assignment where I need to achieve full coverage of the equals() method to earn all possible points. I'm having issues getting full statement/branch coverage due to the getClass() portion of the equals() method. So far I've gotten 1/2 branches covered, but I can't get my mind around how to get to the second.

Equals method below:

```<code>public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (getClass() != obj.getClass())
            return false;
        //Lots of other tests checking the functionality of the program that I've figured out already
        return true;
    }
</code>```

The unit test that is getting me 1/2 branches covered:

```<code>assertFalse(!s1.getClass().equals(s1.getClass()));
</code>```

Since I've gotten 1/2 branches covered I assume the second is possible. But idk.

Thanks

答:
if (getClass() != obj.getClass()) return false; considers two instances to be different if both are not instances of the same class. For example, when obj is an instance of a class that extends the class of this, even if all fields have the same value.

So you also have to compare s1 with a s2, that is an instance of a class that extends the class of s1 to get here the return false; branch executed.

Please note, that in assertFalse(!s1.getClass().equals(s1.getClass())); your equals method is not called, but java.lang.Class::equals and that assertFalse(!...) is the same as assertTrue(...).

Body:
This is tedious, but I've got an assignment where I need to achieve full coverage of the equals() method to earn all possible points. I'm having issues getting full statement/branch coverage due to the getClass() portion of the equals() method. So far I've gotten 1/2 branches covered, but I can't get my mind around how to get to the second.

Equals method below:

public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (getClass() != obj.getClass())
            return false;
        //Lots of other tests checking the functionality of the program that I've figured out already
        return true;
    }

The unit test that is getting me 1/2 branches covered:

assertFalse(!s1.getClass().equals(s1.getClass()));

Since I've gotten 1/2 branches covered I assume the second is possible. But idk.

Thanks


问:
Dividing one smaller number with the bigger one doesn't work without special decleration c#
This:

float a = 2 / 4;
return a;

Will output as 0, while this:

float a = 2;
float b = 4;
float c = a / b;
return c;

Will give a correct output 0.5.

Why am I getting this result?

答:
C# interprets 2 and 4 as plain integers, 2/4 is 0 using integer math (floor of 0.5).

Try using 2f and 4f instead to have floating point numbers. Refer to this documentation to see all possible number literals https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types#real-literals.

Code below works as expected:

public static void Main()
{
    float a = 2f / 4f;
    Console.WriteLine(a);
}
```


问:
Kotlin App Crash if back button pressed during fetching API
So i have the problem that the App will crash if the Back button is pressed during fetching service in a fragment. Currently I'm using Retrofit Library to do the service calling tasks. Below is the code snippet of the fragment :

ProductStockOutletListFragment.kt

```<code>override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    (activity as AppCompatActivity).supportActionBar?.title = "Product List"

    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_product_stock_outlet_list, container, false)

    //Show Progressbar While loading data
    binding.progressBar.visibility = View.VISIBLE

    //Apply layout manager
    binding.rvOutletList.layoutManager = LinearLayoutManager((activity as AppCompatActivity))

    NetworkConfig().getOutletListService()
        .getOutlets()
        .enqueue(object : Callback<OutletListPOJODataClasses> {

            override fun onFailure(call: Call<OutletListPOJODataClasses>, t: Throwable) {

                if(call.isCanceled){
                    Toast.makeText((activity as AppCompatActivity), "Request Aborted", Toast.LENGTH_SHORT).show()
                }else{
                    Toast.makeText((activity as AppCompatActivity), t.localizedMessage, Toast.LENGTH_SHORT).show()
                }

            }

            override fun onResponse(
                call: Call<OutletListPOJODataClasses>,
                response: Response<OutletListPOJODataClasses>
            ) {
                binding.progressBar.visibility = View.GONE
                binding.rvOutletList.adapter = response.body()?.let { OutletListAdapter(it, this@ProductStockOutletListFragment) }

                Toast.makeText((activity as AppCompatActivity), "Data retrieved!", Toast.LENGTH_SHORT).show() //It points out this line. This is where the error happened.
            }

        })

    // Declare that this fragment has menu
    setHasOptionsMenu(true)

    // Set action bar title to "Outlet List"
    (activity as AppCompatActivity).supportActionBar?.title = "Outlet List"

    return binding.root
}
</code>```

If back button is pressed, it'll crash and return the error

kotlin.TypeCastException: null cannot be cast to non-null type androidx.appcompat.app.AppCompatActivity

The error pointed out at the below line at OnResponse()

Toast.makeText((activity as AppCompatActivity), "Data retrieved!", Toast.LENGTH_SHORT).show()

Am I missing something ? Or maybe this is a lifecycle-related problem ? Let me know if there's anything Unclear.

Edit : As requested, This is the full error log.

答:
The exception is because the activity you used in Toast becomes null when you backpress (fragment is destroyed) but the api response is received later and toast is executed.

So just add a null check before toasting:

```<code>if(activity!=null){
    Toast.makeText((activity as AppCompatActivity), "Data retrieved!", Toast.LENGTH_SHORT).show()
}
</code>```

Body:
So i have the problem that the App will crash if the Back button is pressed during fetching service in a fragment. Currently I'm using Retrofit Library to do the service calling tasks. Below is the code snippet of the fragment :

ProductStockOutletListFragment.kt

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    (activity as AppCompatActivity).supportActionBar?.title = "Product List"

    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_product_stock_outlet_list, container, false)

    //Show Progressbar While loading data
    binding.progressBar.visibility = View.VISIBLE

    //Apply layout manager
    binding.rvOutletList.layoutManager = LinearLayoutManager((activity as AppCompatActivity))

    NetworkConfig().getOutletListService()
        .getOutlets()
        .enqueue(object : Callback<OutletListPOJODataClasses> {

            override fun onFailure(call: Call<OutletListPOJODataClasses>, t: Throwable) {

                if(call.isCanceled){
                    Toast.makeText((activity as AppCompatActivity), "Request Aborted", Toast.LENGTH_SHORT).show()
                }else{
                    Toast.makeText((activity as AppCompatActivity), t.localizedMessage, Toast.LENGTH_SHORT).show()
                }

            }

            override fun onResponse(
                call: Call<OutletListPOJODataClasses>,
                response: Response<OutletListPOJODataClasses>
            ) {
                binding.progressBar.visibility = View.GONE
                binding.rvOutletList.adapter = response.body()?.let { OutletListAdapter(it, this@ProductStockOutletListFragment) }

                Toast.makeText((activity as AppCompatActivity), "Data retrieved!", Toast.LENGTH_SHORT).show() //It points out this line. This is where the error happened.
            }

        })

    // Declare that this fragment has menu
    setHasOptionsMenu(true)

    // Set action bar title to "Outlet List"
    (activity as AppCompatActivity).supportActionBar?.title = "Outlet List"

    return binding.root
}

If back button is pressed, it'll crash and return the error

kotlin.TypeCastException: null cannot be cast to non-null type androidx.appcompat.app.AppCompatActivity

The error pointed out at the below line at OnResponse()

Toast.makeText((activity as AppCompatActivity), "Data retrieved!", Toast.LENGTH_SHORT).show()

Am I missing something ? Or maybe this is a lifecycle-related problem ? Let me know if there's anything Unclear.

Edit : As requested, This is the full error log.

Body:
The exception is because the activity you used in Toast becomes null when you backpress (fragment is destroyed) but the api response is received later and toast is executed.

So just add a null check before toasting:

if(activity!=null){
    Toast.makeText((activity as AppCompatActivity), "Data retrieved!", Toast.LENGTH_SHORT).show()
}


问:
Implementing collision check for classes derived from same base class
I have a base class MovingObject defined like this:

```<code>class MovingObject
{
protected:
    double x;
    double y;
    double speed;
    double damage;
    double distance(double x1, double y1, double x2, double y2)
    {
        return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
    }
public:
    MovingObject(double x, double y, double speed, double damage);
    virtual bool isCollide(MovingObject* Object);
    virtual void draw() {};
    virtual void move() {};
};
</code>```

And I have 2 inherited classes from MovingObject class, Zombie and Bullet :

```<code>class Bullet : public MovingObject
{
private:
    double dirX;
    double dirY;
public:
    Bullet(double x, double y, double speed, double damage, double dirX, double dirY);
    bool isCollide(Zombie* pZombie);
    void draw();
    void move();
};
</code>```

```<code>class Zombie : public MovingObject
{
private:
    double hpMax;
    double hpCurrent;
    double attackCD;
    double attackRate;
public:
    Zombie(double x, double y, double speed, double damage, double hpMax, double hpCurrent, double attackCD, double attackRate);
    bool isCollide(Bullet* pBullet);
    void draw();
    void move();
    void getHit();
    void drawHPBar();
    void decreaseAttackCD();
    void refreshAttackCD();
};
</code>```

For example, lets say I want to check collision between Bullet and Zombie objects in the game. I want to check this collision in Bullet class like follows:

```<code>bool Bullet::isCollide(Zombie* pZombie) {
    if (distance(x, y, pZombie->x, pZombie->y) < 10) {
        pZombie->getHit();
        return true;
    }
    else
        return false;
}

</code>```

But when I try to access the x and y attributes of Zombie in Bullet class, I can't access it. What I want to ask is, is it possible to check collision like this without using getX() and getY() functions ? I believe there is a flaw in my thinking because I am fairly new to C++ and OOP concepts. I do not want to full answer from you, I just want someone to point right path for me. Thank you in advanced.

答:
Bullet cannot access Zobmbies protected members because it is not derived from Zombie. If you only need read access to x and y, you need constant getters in the MovingObject class.

```<code>class MovingObject
{
public:
  double GetX() const { return x; }
  double GetY() const { return y; }
protected:
...
};
</code>```

and then use them in Bullet::isCollide()

```<code>if (distance(x, y, pZombie->GetX(), pZombie->GetY()) < 10) {
  pZombie->getHit();
  return true;
}
</code>```

Please avoid using friend. With growing number of subclasses you will have to make them all friends.

Body:
I have a base class MovingObject defined like this:

class MovingObject
{
protected:
    double x;
    double y;
    double speed;
    double damage;
    double distance(double x1, double y1, double x2, double y2)
    {
        return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
    }
public:
    MovingObject(double x, double y, double speed, double damage);
    virtual bool isCollide(MovingObject* Object);
    virtual void draw() {};
    virtual void move() {};
};

And I have 2 inherited classes from MovingObject class, Zombie and Bullet :

class Bullet : public MovingObject
{
private:
    double dirX;
    double dirY;
public:
    Bullet(double x, double y, double speed, double damage, double dirX, double dirY);
    bool isCollide(Zombie* pZombie);
    void draw();
    void move();
};

class Zombie : public MovingObject
{
private:
    double hpMax;
    double hpCurrent;
    double attackCD;
    double attackRate;
public:
    Zombie(double x, double y, double speed, double damage, double hpMax, double hpCurrent, double attackCD, double attackRate);
    bool isCollide(Bullet* pBullet);
    void draw();
    void move();
    void getHit();
    void drawHPBar();
    void decreaseAttackCD();
    void refreshAttackCD();
};

For example, lets say I want to check collision between Bullet and Zombie objects in the game. I want to check this collision in Bullet class like follows:

bool Bullet::isCollide(Zombie* pZombie) {
    if (distance(x, y, pZombie->x, pZombie->y) < 10) {
        pZombie->getHit();
        return true;
    }
    else
        return false;
}

But when I try to access the x and y attributes of Zombie in Bullet class, I can't access it. What I want to ask is, is it possible to check collision like this without using getX() and getY() functions ? I believe there is a flaw in my thinking because I am fairly new to C++ and OOP concepts. I do not want to full answer from you, I just want someone to point right path for me. Thank you in advanced.

Body:
Bullet cannot access Zobmbies protected members because it is not derived from Zombie. If you only need read access to x and y, you need constant getters in the MovingObject class.

class MovingObject
{
public:
  double GetX() const { return x; }
  double GetY() const { return y; }
protected:
...
};

and then use them in Bullet::isCollide()

if (distance(x, y, pZombie->GetX(), pZombie->GetY()) < 10) {
  pZombie->getHit();
  return true;
}

Please avoid using friend. With growing number of subclasses you will have to make them all friends.


问:
trying to create a div below a div css
I realize this is a a pretty basic question, and perhaps I'm taking advantage of you all while I should be sifting through some dense css books/materials. But I can't figure out why my code doesn't work.

I'm trying to create two divs on a page, one below the other and it seems like I should be able to give the lower and absolute position which is below the top div.

I've got to div box whose css layouts are all the same but they don't look anything like eachother. Why is it that the second one looks completely unlike the first, why can't I make a "copy" of the first and place it below the first?

Heres the code. the top is the desired scroller is the desired effect. http://jsfiddle.net/7YueC/

答:
since you are trying to achieve the exact same effect on both divs and all the contained elements - why not define a class that is applied to each div. div is a block level element, so they will stack on top of one another by default - no absolute positioning needed.

Here is your code, with the addition of the class eventimg and slightly modified CSS http://jsfiddle.net/ZXGUt/

ContentLicense: CC BY-SA 3.0

Title: trying to create a div below a div css


问:
Generating random samples from the data
I have 506 points in the data set. I have to generate random sample from this data such as i have to select 303 points without replacement and remaining 203 points i need to select from these 303 points.

I have written the following code.

```<code>def generating_samples(input_data, target_data):

    selected_rows = np.random.choice(len(input_data), 303)
    replacing_rows = np.random.choice(selected_rows,203)
    selected_columns = np.random.choice(3,13,1)
    sample_data = input_data[selected_rows[:,None],selected_columns]
    target_of_sample_data = target_data[selected_rows]

    #replicating data
    replicated_sample_data = sample_data[replacing_rows]
    target_of_replicated_sample_data = target_data[replacing_rows]

    #concatenating data
    sampled_input_data = np.vstack(sample_data, replicated_sample_data)
    target_of_sample_data = target_of_sample_data.reshape(-1,1)
    target_of_replicated_sample_data = target_of_replicated_sample_data.reshape(-1,1)
    sampled_target_data = np.vstack(target_of_sample_data,target_of_replicated_sample_data)

    return sampled_input_data , sampled_target_data, selected_rows,selected_columns

def grader_samples(a,b,c,d):
        length = (len(a)==506  and len(b)==506)
        sampled = (len(a)-len(set([str(i) for i in a]))==203)
        rows_length = (len(c)==303)
        column_length= (len(d)>=3)
        assert(length and sampled and rows_length and column_length)
        return True

a,b,c,d = generating_samples(x, y)
grader_samples(a,b,c,d)
</code>```

But am getting following error in this.

```<code>IndexError                                Traceback (most recent call last)
<ipython-input-14-ca772632e834> in <module>
      7     return True
      8
----> 9 a,b,c,d = generating_samples(x, y)
     10 grader_samples(a,b,c,d)

<ipython-input-13-bcf904f160e5> in generating_samples(input_data, target_data)
     13
     14     #replicating data
---> 15     replicated_sample_data = sample_data[replacing_rows]
     16     target_of_replicated_sample_data = target_data[replacing_rows]
     17

IndexError: index 391 is out of bounds for axis 0 with size 303
</code>```

答:
Use :replicated_sample_data = input_data[replacing_rows] because the replicating sample data comes from original dataset.
And sample data is already sampled from the original dataset , so it is a subset of our original dataset and results in out of index error

Title: Generating random samples from the data

Body:
I have 506 points in the data set. I have to generate random sample from this data such as i have to select 303 points without replacement and remaining 203 points i need to select from these 303 points.

I have written the following code.

def generating_samples(input_data, target_data):

    selected_rows = np.random.choice(len(input_data), 303)
    replacing_rows = np.random.choice(selected_rows,203)
    selected_columns = np.random.choice(3,13,1)
    sample_data = input_data[selected_rows[:,None],selected_columns]
    target_of_sample_data = target_data[selected_rows]

    #replicating data
    replicated_sample_data = sample_data[replacing_rows]
    target_of_replicated_sample_data = target_data[replacing_rows]

    #concatenating data
    sampled_input_data = np.vstack(sample_data, replicated_sample_data)
    target_of_sample_data = target_of_sample_data.reshape(-1,1)
    target_of_replicated_sample_data = target_of_replicated_sample_data.reshape(-1,1)
    sampled_target_data = np.vstack(target_of_sample_data,target_of_replicated_sample_data)

    return sampled_input_data , sampled_target_data, selected_rows,selected_columns

def grader_samples(a,b,c,d):
        length = (len(a)==506  and len(b)==506)
        sampled = (len(a)-len(set([str(i) for i in a]))==203)
        rows_length = (len(c)==303)
        column_length= (len(d)>=3)
        assert(length and sampled and rows_length and column_length)
        return True

a,b,c,d = generating_samples(x, y)
grader_samples(a,b,c,d)

But am getting following error in this.

IndexError                                Traceback (most recent call last)
<ipython-input-14-ca772632e834> in <module>
      7     return True
      8
----> 9 a,b,c,d = generating_samples(x, y)
     10 grader_samples(a,b,c,d)

<ipython-input-13-bcf904f160e5> in generating_samples(input_data, target_data)
     13
     14     #replicating data
---> 15     replicated_sample_data = sample_data[replacing_rows]
     16     target_of_replicated_sample_data = target_data[replacing_rows]
     17

IndexError: index 391 is out of bounds for axis 0 with size 303


问:
Electron app window still animations on minimize, maximize and close events
Working with my electron project(using angular 9), made a custom titlebar with window control buttons (minimize, maximize, restore etc). Now whenever I click those buttons(suppose minimize) window hides abruptly without showing smooth fade-out animation that's normal for windows desktop app. So, I made another dummy electron project (without angular and using plain JavaScript) created 4 buttons for window events code as show below for dummy project:

index.js

const {app, BrowserWindow, ipcMain} = require('electron') ;

let win ;

app.on('ready', () => {
   win = new BrowserWindow({
      width: 800,
      height: 636,
      frame: false,
      webPreferences: {
         nodeIntegration: true
      }
   }) ;

   win.loadFile('./src/index.html') ;
});

app.on('window-all-closed', () => {
   app.quit() ;
})

ipcMain.on('minimize:event', () => {
   win.minimize() ;
}) ;

ipcMain.on('maximize:event', () => {
   win.maximize() ;
}) ;

ipcMain.on('close:event', () => {
   win.close() ;
}) ;

ipcMain.on('restore:event', () => {
   win.restore() ;
}) ;```
</div>
</div>
</p>

<p>index.html</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><!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>

</head>
<body>
   Hello World
   <button id="min" click="minimize()">Minimize</button>
   <button id="max" click="maximize()">Maximize</button>
   <button id="close" click="close()">Close</button>
   <button id="res" click="restore()">Restore</button>

   <script>

      const { ipcRenderer } = require('electron') ;
      document.getElementById('min').onclick = function(){
         ipcRenderer.send('minimize:event') ;
      }
      document.getElementById('max').onclick = function(){
         ipcRenderer.send('maximize:event') ;
      }
      document.getElementById('close').onclick = function(){
         ipcRenderer.send('close:event') ;
      }
      document.getElementById('res').onclick = function(){
         ipcRenderer.send('restore:event') ;
      }
   </script>

</body>
</html></code>```

For my angular project:

main.js(index.js)

const { app, BrowserWindow, ipcMain } = require('electron') ;
const config = require('./config') ;

let win, settings ;

let gotSingleInstanceAccess = app.requestSingleInstanceLock() ;

if(!gotSingleInstanceAccess){
   app.quit() ;
}

app.on('ready', () => {
   /// on redy fetch the settings

   settings = config.createDefaultSettingsAndReturn() ;

   // Create the browser window.

   win = new BrowserWindow({
      width: settings.appSettings.defaultWidth,
      height: settings.appSettings.defaultHeight,
      webPreferences: {
         nodeIntegration: true,
      },
      show: false,
      frame: false,
      transparent: true,
      minHeight: settings.appSettings.minHeight,
      minWidth: settings.appSettings.minWidth
   }) ;

   if(!settings.appSettings.trayMode){
      if(settings.appSettings.wasMaximized){
         win.maximize() ;
      }
      else{
         win.setBounds(settings.windowSettings.windowBounds) ;
      }
   }
   else{
      // do for traymode ;
   }

   win.loadURL('http://localhost:4200') ;

   win.on('ready-to-show', () =>{
      win.show() ;
   }) ;

   win.webContents.on('did-fail-load', () => {
      win.loadURL('http://localhost:4200')
   });

   win.on('closed', () => {
      win = null ;
   })

}) ;

app.on('second-instance', (event,args, cwd) => {
   if(win){
      if(win.isMinimized()){
         win.restore() ;
      }
      win.focus() ;
   }
})

// Quit when all windows are closed.
app.on('window-all-closed', () => {
   // On macOS it is common for applications and their menu bar
   // to stay active until the user quits explicitly with Cmd + Q
   console.log('saved settings successfully')
   if (process.platform !== 'darwin') {
      app.quit()
   }
})

app.on('activate', () => {
   // On macOS it's common to re-create a window in the app when the
   // dock icon is clicked and there are no other windows open.
   if (win = null) {
      createWindow() ;
   }
}) ;

ipcMain.on('window:minimize', () => {
   win.blur() ;
   win.minimize() ;
}) ;

ipcMain.on('window:maximize', () => {
   win.maximize() ;
   win.resizable = false ;
}) ;

ipcMain.on('window:restore', () => {
   win.restore() ;
   win.resizable = true ;
}) ;

ipcMain.on('window:close', () => {
   win.close() ;
}) ;```
</div>
</div>
</p>

<p>app-window.service.ts</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>import { Injectable } from '@angular/core';
import { WindowSettings } from '../interface/settings';
import { AppStoreService } from './app-store.service';
import { BehaviorSubject } from 'rxjs';
import { ElectronService } from 'ngx-electron';
import { ElectronHelperService } from './electron-helper.service';

@Injectable()

export class AppWindowService {
  windowSettings: WindowSettings ;
  maxmizeObservable: BehaviorSubject<boolean> ;
  constructor(private helper: ElectronHelperService, private electron: ElectronService, private config: AppStoreService) {
    this.windowSettings = this.config.store.get('settings.windowSettings') ;
    this.maxmizeObservable = new BehaviorSubject<boolean>(this.windowSettings.wasMaximized) ;
  }
  // showing maximize/restore button
  changeMaximizedState(value: boolean){
    this.maxmizeObservable.next(value) ;
    this.windowSettings.wasMaximized = value ;
  }

  winMaximize(){
    this.windowSettings.windowBounds = this.helper.win.getBounds() ;
    this.electron.ipcRenderer.send('window:maximize') ;
  }

  winRestore(){
    this.helper.win.setBounds(this.windowSettings.windowBounds) ;
    this.electron.ipcRenderer.send('window:restore') ;
  }

  winMinimize(){
    this.electron.ipcRenderer.send('window:minimize') ;
  }

  winClose(){
    this.electron.ipcRenderer.send('window:close') ;
  }
}</code>```

My dummy project has smooth window animation but the angular project has still animations on those window events(it's like windows animations are closed in control panel). How can I fix this ?

答: So, after long trial and error I found that in my angular project I had transparent: true in BrowserWindow configuration after removing that my project had smooth minimize, maximize and restore animation.

Body:
Working with my electron project(using angular 9), made a custom titlebar with window control buttons (minimize, maximize, restore etc). Now whenever I click those buttons(suppose minimize) window hides abruptly without showing smooth fade-out animation that's normal for windows desktop app. So, I made another dummy electron project (without angular and using plain JavaScript) created 4 buttons for window events code as show below for dummy project:

index.js

const {app, BrowserWindow, ipcMain} = require('electron') ;

let win ;

app.on('ready', () => {
   win = new BrowserWindow({
      width: 800,
      height: 636,
      frame: false,
      webPreferences: {
         nodeIntegration: true
      }
   }) ;

   win.loadFile('./src/index.html') ;
});

app.on('window-all-closed', () => {
   app.quit() ;
})

ipcMain.on('minimize:event', () => {
   win.minimize() ;
}) ;

ipcMain.on('maximize:event', () => {
   win.maximize() ;
}) ;

ipcMain.on('close:event', () => {
   win.close() ;
}) ;

ipcMain.on('restore:event', () => {
   win.restore() ;
}) ;

index.html

<!DOCTYPE html>

   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>

   Hello World
   <button id="min" click="minimize()">Minimize</button>
   <button id="max" click="maximize()">Maximize</button>
   <button id="close" click="close()">Close</button>
   <button id="res" click="restore()">Restore</button>

For my angular project:

main.js(index.js)

const { app, BrowserWindow, ipcMain } = require('electron') ;
const config = require('./config') ;

let win, settings ;

let gotSingleInstanceAccess = app.requestSingleInstanceLock() ;

if(!gotSingleInstanceAccess){
   app.quit() ;
}

app.on('ready', () => {
   /// on redy fetch the settings

   settings = config.createDefaultSettingsAndReturn() ;

   // Create the browser window.

   win = new BrowserWindow({
      width: settings.appSettings.defaultWidth,
      height: settings.appSettings.defaultHeight,
      webPreferences: {
         nodeIntegration: true,
      },
      show: false,
      frame: false,
      transparent: true,
      minHeight: settings.appSettings.minHeight,
      minWidth: settings.appSettings.minWidth
   }) ;

   if(!settings.appSettings.trayMode){
      if(settings.appSettings.wasMaximized){
         win.maximize() ;
      }
      else{
         win.setBounds(settings.windowSettings.windowBounds) ;
      }
   }
   else{
      // do for traymode ;
   }

   win.loadURL('http://localhost:4200') ;

   win.on('ready-to-show', () =>{
      win.show() ;
   }) ;

   win.webContents.on('did-fail-load', () => {
      win.loadURL('http://localhost:4200')
   });

   win.on('closed', () => {
      win = null ;
   })

}) ;

app.on('second-instance', (event,args, cwd) => {
   if(win){
      if(win.isMinimized()){
         win.restore() ;
      }
      win.focus() ;
   }
})

// Quit when all windows are closed.
app.on('window-all-closed', () => {
   // On macOS it is common for applications and their menu bar
   // to stay active until the user quits explicitly with Cmd + Q
   console.log('saved settings successfully')
   if (process.platform !== 'darwin') {
      app.quit()
   }
})

app.on('activate', () => {
   // On macOS it's common to re-create a window in the app when the
   // dock icon is clicked and there are no other windows open.
   if (win = null) {
      createWindow() ;
   }
}) ;

ipcMain.on('window:minimize', () => {
   win.blur() ;
   win.minimize() ;
}) ;

ipcMain.on('window:maximize', () => {
   win.maximize() ;
   win.resizable = false ;
}) ;

ipcMain.on('window:restore', () => {
   win.restore() ;
   win.resizable = true ;
}) ;

ipcMain.on('window:close', () => {
   win.close() ;
}) ;

app-window.service.ts

import { Injectable } from '@angular/core';
import { WindowSettings } from '../interface/settings';
import { AppStoreService } from './app-store.service';
import { BehaviorSubject } from 'rxjs';
import { ElectronService } from 'ngx-electron';
import { ElectronHelperService } from './electron-helper.service';

@Injectable()

export class AppWindowService {
  windowSettings: WindowSettings ;
  maxmizeObservable: BehaviorSubject<boolean> ;
  constructor(private helper: ElectronHelperService, private electron: ElectronService, private config: AppStoreService) {
    this.windowSettings = this.config.store.get('settings.windowSettings') ;
    this.maxmizeObservable = new BehaviorSubject<boolean>(this.windowSettings.wasMaximized) ;
  }
  // showing maximize/restore button
  changeMaximizedState(value: boolean){
    this.maxmizeObservable.next(value) ;
    this.windowSettings.wasMaximized = value ;
  }

  winMaximize(){
    this.windowSettings.windowBounds = this.helper.win.getBounds() ;
    this.electron.ipcRenderer.send('window:maximize') ;
  }

  winRestore(){
    this.helper.win.setBounds(this.windowSettings.windowBounds) ;
    this.electron.ipcRenderer.send('window:restore') ;
  }

  winMinimize(){
    this.electron.ipcRenderer.send('window:minimize') ;
  }

  winClose(){
    this.electron.ipcRenderer.send('window:close') ;
  }
}

My dummy project has smooth window animation but the angular project has still animations on those window events(it's like windows animations are closed in control panel). How can I fix this ?


问:
Repository insert with navigation property throws 'FOREIGN KEY constraint failed'
I'm using EF Core and sqlite. Given following 1-to-1 entities:

```<code>  public class Entity1:FullAuditedEntity<int>
  {
    public Entity2 Entity2 { get; set; }

    public string Name { get; set; }

  }

  public class Entity2: FullAuditedEntity<int>
  {

    public string Name { get; set; }

    [ForeignKey("Entity1Id")]
    public Entity1 Entity1{ get; set; }
    public int Entity1Id { get; set; }
  }
</code>```

and following insert logic:

```<code>    entity1.Entity2 = new Entity2();
    entity1= await entity1Repository.InsertAsync(entity1);//entity1Repository is of type IRepository<Entity1>
</code>```

Code above throws:

Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.
---- Microsoft.Data.Sqlite.SqliteException : SQLite Error 19: 'FOREIGN KEY constraint failed'.
   at  ...

This approach doesn't work either, throws the same:

```<code>    var entity2 = new Entity2();
    entity1.Entity2 = entity2;
    entity2.Entity1 = entity1;
    entity1= await entity1Repository.InsertAsync(entity1);//entity1Repository
</code>```

What I'm doing wrong, what I'm missing? What is the correct way to create Entity1 and Entity2 with  Entity2 property being set? Is it possible to create with Entity1 repo only?

Thanks in advance.

Update: Problem solved. In actual code entity2 has it's own reference on entity3, which is obvoiusly was throwing. It was the cause.

答:
Like this?

```<code>public class Entity1:FullAuditedEntity<int>
{
   public Entity2 Entity2 { get; set; } = new Entity2();

   public string Name { get; set; }
}

var entity1 = new Entity1();
entity1 = await entity1Repository.InsertAsync(entity1);//entity1Repository
</code>```

Or do you want to clone? Check out:
https://entityframeworkcore.com/knowledge-base/48873716/how-to-deep-clone-copy-in-ef-core

Body:
I'm using EF Core and sqlite. Given following 1-to-1 entities:

  public class Entity1:FullAuditedEntity<int>
  {
    public Entity2 Entity2 { get; set; }

    public string Name { get; set; }

  }

  public class Entity2: FullAuditedEntity<int>
  {

    public string Name { get; set; }

    [ForeignKey("Entity1Id")]
    public Entity1 Entity1{ get; set; }
    public int Entity1Id { get; set; }
  }

and following insert logic:

    entity1.Entity2 = new Entity2();
    entity1= await entity1Repository.InsertAsync(entity1);//entity1Repository is of type IRepository<Entity1>

Code above throws:

Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.
---- Microsoft.Data.Sqlite.SqliteException : SQLite Error 19: 'FOREIGN KEY constraint failed'.
   at  ...

This approach doesn't work either, throws the same:

    var entity2 = new Entity2();
    entity1.Entity2 = entity2;
    entity2.Entity1 = entity1;
    entity1= await entity1Repository.InsertAsync(entity1);//entity1Repository

What I'm doing wrong, what I'm missing? What is the correct way to create Entity1 and Entity2 with  Entity2 property being set? Is it possible to create with Entity1 repo only?

Thanks in advance.

Update: Problem solved. In actual code entity2 has it's own reference on entity3, which is obvoiusly was throwing. It was the cause.

Body:
Like this?

public class Entity1:FullAuditedEntity<int>
{
   public Entity2 Entity2 { get; set; } = new Entity2();

   public string Name { get; set; }
}

var entity1 = new Entity1();
entity1 = await entity1Repository.InsertAsync(entity1);//entity1Repository

Or do you want to clone? Check out:
https://entityframeworkcore.com/knowledge-base/48873716/how-to-deep-clone-copy-in-ef-core


问:
smarty processes strong (text) format over php -> put out modified php only
Have prepared a string modification with php in the classes file. Now in the smarty template (tpl) file when outputting the string I get a wrong text format. The project uses smarty 3.1-DEV and php 5.6.

I have this php code and assigned the variable in php class file:

```<code>    $pattern = '/' . implode('|', $allergens_searchnames) . '/iu';
    echo preg_replace_callback($pattern, function ($m) {
    return mb_strtoupper($m[0]); }, $prodIngredients);
    }
    $this->assign("articleIngredients", $prodIngredients);
</code>```

Outputting directly with "echo" over classes file I get on front end the desired format:
"Zutaten:
MARILLEn (75%), Zucker, Zitronensaft, Geliermittel: PEKTINe (aus Apfel)"

Implementation over smarty output is wrong:
"Zutaten:
Marillen (75%), Zucker, Zitronensaft, Geliermittel: Pektine (aus Apfel)"

Here like I implemented to the tpl-file:

```<code><span class="pull-right">
{if isset($articleIngredients)}
<p>{$articleIngredients|unescape:'html'}</p>
{/if}
</span>
</code>```

Due to the fact that I don't know much of the project and of smarty it is nearly impossible to fix this for me. Any help is appreciated.

答:
I think one of these 2 might help you. Try using unescape:'htmlall' or Try printing the text as literal text

```<code><span class="pull-right">
{if isset($articleIngredients)}
<p>{$articleIngredients}|unescape:'htmlall'}</p>
{/if}
</code>```

source: https://www.smarty.net/docs/en/language.modifier.unescape.tpl

Anything within {literal}{/literal} tags is not interpreted, but displayed as-is.

```<code><span class="pull-right">
{if isset($articleIngredients)}
<p>{literal}{$articleIngredients}{/literal}</p>
{/if}
</span>
</code>```

Source: https://www.smarty.net/docs/en/language.function.literal.tpl

Body:
Have prepared a string modification with php in the classes file. Now in the smarty template (tpl) file when outputting the string I get a wrong text format. The project uses smarty 3.1-DEV and php 5.6.

I have this php code and assigned the variable in php class file:

    $pattern = '/' . implode('|', $allergens_searchnames) . '/iu';
    echo preg_replace_callback($pattern, function ($m) {
    return mb_strtoupper($m[0]); }, $prodIngredients);
    }
    $this->assign("articleIngredients", $prodIngredients);

Outputting directly with "echo" over classes file I get on front end the desired format:
"Zutaten:
MARILLEn (75%), Zucker, Zitronensaft, Geliermittel: PEKTINe (aus Apfel)"

Implementation over smarty output is wrong:
"Zutaten:
Marillen (75%), Zucker, Zitronensaft, Geliermittel: Pektine (aus Apfel)"

Here like I implemented to the tpl-file:

{if isset($articleIngredients)}

{$articleIngredients|unescape:'html'}

{/if}

Due to the fact that I don't know much of the project and of smarty it is nearly impossible to fix this for me. Any help is appreciated.

Body:
I think one of these 2 might help you. Try using unescape:'htmlall' or Try printing the text as literal text

<span class="pull-right">
{if isset($articleIngredients)}
<p>{$articleIngredients}|unescape:'htmlall'}</p>
{/if}

source: https://www.smarty.net/docs/en/language.modifier.unescape.tpl

Anything within {literal}{/literal} tags is not interpreted, but displayed as-is.

<span class="pull-right">
{if isset($articleIngredients)}
<p>{literal}{$articleIngredients}{/literal}</p>
{/if}
</span>

Source: https://www.smarty.net/docs/en/language.function.literal.tpl


问:
In react-native-webrtc in <RTCView> only video is coming, audio is not working
I am working with react-native-webrtc but I am facing one problem I am able to display video captured by the camera but the audio is not working or we can say I am getting video frames of display and not able to listen any audio. I have given microphone access too and in getusermedia audio and video both parameters are true.

Here is my code:

import React, { Component } from 'react';
import { StyleSheet, View, Button, Text } from 'react-native';
import * as mediasoupClient from 'mediasoup-client';
import {
  RTCPeerConnection,
  RTCIceCandidate,
  RTCSessionDescription,
  RTCView,
  MediaStream,
  MediaStreamTrack,
  mediaDevices,
  registerGlobals,
} from 'react-native-webrtc';
import io from 'socket.io-client/dist/socket.io';
registerGlobals();
class WebRtcScreen extends Component {
  state = {
    MediaStreamx: new MediaStream(),
  };

  componentDidMount() {
    navigator.mediaDevices
      .getUserMedia({ video: true, audio: true })
      .then(this.handleVideo)
      .catch(this.videoError);
  }

  handleVideo = (stream) => {
    this.setState({ MediaStreamx: stream });
  };

  videoError = (err) => {
    console.log(err.name);
  };

  render() {
    return (
      <RTCView
        key={1}
        zOrder={2}
        objectFit="cover"
        style={{ ...styles.rtcView }}
        streamURL={this.state.MediaStreamx.toURL()}
      />
    );
  }
}
const styles = StyleSheet.create({
  rtcView: {
    width: 100, //dimensions.width,
    height: 200, //dimensions.height / 2,
    backgroundColor: 'black',
  },
});

export { WebRtcScreen };
```

Why is the audio not working here?

答:
The issue here is that react-native-webrtc plays audio in earphone. You need to use
https://github.com/react-native-webrtc/react-native-incall-manager
to play audio in phone speaker.

Hope this helps.

Body:
I am working with react-native-webrtc but I am facing one problem I am able to display video captured by the camera but the audio is not working or we can say I am getting video frames of display and not able to listen any audio. I have given microphone access too and in getusermedia audio and video both parameters are true.

Here is my code:

import React, { Component } from 'react';
import { StyleSheet, View, Button, Text } from 'react-native';
import * as mediasoupClient from 'mediasoup-client';
import {
  RTCPeerConnection,
  RTCIceCandidate,
  RTCSessionDescription,
  RTCView,
  MediaStream,
  MediaStreamTrack,
  mediaDevices,
  registerGlobals,
} from 'react-native-webrtc';
import io from 'socket.io-client/dist/socket.io';
registerGlobals();
class WebRtcScreen extends Component {
  state = {
    MediaStreamx: new MediaStream(),
  };

  componentDidMount() {
    navigator.mediaDevices
      .getUserMedia({ video: true, audio: true })
      .then(this.handleVideo)
      .catch(this.videoError);
  }

  handleVideo = (stream) => {
    this.setState({ MediaStreamx: stream });
  };

  videoError = (err) => {
    console.log(err.name);
  };

  render() {
    return (
      <RTCView
        key={1}
        zOrder={2}
        objectFit="cover"
        style={{ ...styles.rtcView }}
        streamURL={this.state.MediaStreamx.toURL()}
      />
    );
  }
}
const styles = StyleSheet.create({
  rtcView: {
    width: 100, //dimensions.width,
    height: 200, //dimensions.height / 2,
    backgroundColor: 'black',
  },
});

export { WebRtcScreen };

Why is the audio not working here?


问:
Using string stream as split result in lambda
I need to split line based on comma and add it to a Map simultaneously in one go. I know that I can collect the splitted stream to list and then iterate over list for same effect. But I need to know if that can be done.

Input : List<String> - (A, B) (A,C)

Output : Map<String, List<String>> -  (A, (B,C))

Example Code : (Contains Error)

```<code>public void edgeListRepresentation(ArrayList<String> edges){
        Map<String, List<String>> edgeList = new HashMap<>();
        edges.forEach(connection -> {

            Stream.of(connection.split(","))
                    .map((arr) -> {
                        edgeList.computeIfAbsent(arr[0], val -> new ArrayList<String>()).add(arr[1]);
                    });
        });

    }

     public static void main(String[] args) throws IOException {
        EdgeList edgeList = new EdgeList();
        edgeList.edgeListRepresentation(new ArrayList<String>(){
            {
                add("A, B");
                add("A, C");
                add("A, E");
                add("B, C");
                add("C, E");
                add("C, D");
                add("D, E");
            }
        });
    }
</code>```

答:
If you want to make it simple in your way, no need to use stream</p>

```<code>edges.forEach(connection -> {
  String[] arr = connection.split(",");
  edgeList.computeIfAbsent(arr[0], val -> new ArrayList<String>()).add(arr[1].trim());
});
</code>```

Body:
I need to split line based on comma and add it to a Map simultaneously in one go. I know that I can collect the splitted stream to list and then iterate over list for same effect. But I need to know if that can be done.

Input : List<String> - (A, B) (A,C)

Output : Map<String, List<String>> -  (A, (B,C))

Example Code : (Contains Error)

public void edgeListRepresentation(ArrayList<String> edges){
        Map<String, List<String>> edgeList = new HashMap<>();
        edges.forEach(connection -> {

            Stream.of(connection.split(","))
                    .map((arr) -> {
                        edgeList.computeIfAbsent(arr[0], val -> new ArrayList<String>()).add(arr[1]);
                    });
        });

    }

     public static void main(String[] args) throws IOException {
        EdgeList edgeList = new EdgeList();
        edgeList.edgeListRepresentation(new ArrayList<String>(){
            {
                add("A, B");
                add("A, C");
                add("A, E");
                add("B, C");
                add("C, E");
                add("C, D");
                add("D, E");
            }
        });
    }

Body:
If you want to make it simple in your way, no need to use stream

edges.forEach(connection -> {
  String[] arr = connection.split(",");
  edgeList.computeIfAbsent(arr[0], val -> new ArrayList<String>()).add(arr[1].trim());
});


问:
Adding a delay in "virus"
We're doing a "virus" now and I was told to make a delay in my code. Help me, please. Here's the code:

```<code>import pygame
from tkinter import *
from tkinter import messagebox
import time
import random
pygame.init()
screen = pygame.display.set_mode((800, 300))
pygame.display.set_caption("ЗАРАЖЕНИЕ АЧЕ)")

Tk().wm_withdraw()
font = pygame.font.SysFont("Lucida Console", 35)
label2 = font.render("DELETING ALL PASSWORDS. . . . .", 1, (12, 140, 0, 1))

a = 0

while True:
    screen.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            time.sleep(0.5)
            screen = pygame.display.set_mode((800, 300))
            pygame.display.set_caption("ЗАРАЖЕНИЕ АЧЕ)")
            messagebox.showerror("ERROR!", " Вы попытались закрыть окно! Начинаю удаление файлов")
    warning = f"Процент удаления: {a}"
    label3 = font.render(warning, 1, (12, 140, 0, 1))
    a = a + 1
    time.sleep(0.1)
    if a >= 100:
        break

    screen.blit(label2, (50, 50))
    screen.blit(label3, (50, 100))
    pygame.display.update()
</code>```

My question is, I don't know which command to use to delay and where to put it.

Thank you in advance!

答:
With pygame, you don't use time.sleep, you need to replace your time.sleep code with pygame.time.wait, which is written in milliseconds, so your updated code would look like so:

```<code>import pygame
from tkinter import *
from tkinter import messagebox
import time
import random
pygame.init()
screen = pygame.display.set_mode((800, 300))
pygame.display.set_caption("ЗАРАЖЕНИЕ АЧЕ)")

Tk().wm_withdraw()
font = pygame.font.SysFont("Lucida Console", 35)
label2 = font.render("DELETING ALL PASSWORDS. . . . .", 1, (12, 140, 0, 1))

a = 0

while True:
    screen.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.display.quit()
            pygame.time.wait(500)
            screen = pygame.display.set_mode((800, 300))
            pygame.display.set_caption("ЗАРАЖЕНИЕ АЧЕ)")
            messagebox.showerror("ERROR!", " Вы попытались закрыть окно! Начинаю удаление файлов")
    warning = f"Процент удаления: {a}"
    label3 = font.render(warning, 1, (12, 140, 0, 1))
    a = a + 1
    pygame.time.wait(100)
    if a >= 100:
        break

    screen.blit(label2, (50, 50))
    screen.blit(label3, (50, 100))
    pygame.display.update()
</code>```

Also with your code I replaced pygame.quit() with pygame.display.quit() so the code will continue after the so called "error".

Title: Adding a delay in "virus"

Body:
We're doing a "virus" now and I was told to make a delay in my code. Help me, please. Here's the code:

import pygame
from tkinter import *
from tkinter import messagebox
import time
import random
pygame.init()
screen = pygame.display.set_mode((800, 300))
pygame.display.set_caption("ЗАРАЖЕНИЕ АЧЕ)")

Tk().wm_withdraw()
font = pygame.font.SysFont("Lucida Console", 35)
label2 = font.render("DELETING ALL PASSWORDS. . . . .", 1, (12, 140, 0, 1))

a = 0

while True:
    screen.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            time.sleep(0.5)
            screen = pygame.display.set_mode((800, 300))
            pygame.display.set_caption("ЗАРАЖЕНИЕ АЧЕ)")
            messagebox.showerror("ERROR!", " Вы попытались закрыть окно! Начинаю удаление файлов")
    warning = f"Процент удаления: {a}"
    label3 = font.render(warning, 1, (12, 140, 0, 1))
    a = a + 1
    time.sleep(0.1)
    if a >= 100:
        break

    screen.blit(label2, (50, 50))
    screen.blit(label3, (50, 100))
    pygame.display.update()

My question is, I don't know which command to use to delay and where to put it.

Thank you in advance!

Body:
With pygame, you don't use time.sleep, you need to replace your time.sleep code with pygame.time.wait, which is written in milliseconds, so your updated code would look like so:

import pygame
from tkinter import *
from tkinter import messagebox
import time
import random
pygame.init()
screen = pygame.display.set_mode((800, 300))
pygame.display.set_caption("ЗАРАЖЕНИЕ АЧЕ)")

Tk().wm_withdraw()
font = pygame.font.SysFont("Lucida Console", 35)
label2 = font.render("DELETING ALL PASSWORDS. . . . .", 1, (12, 140, 0, 1))

a = 0

while True:
    screen.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.display.quit()
            pygame.time.wait(500)
            screen = pygame.display.set_mode((800, 300))
            pygame.display.set_caption("ЗАРАЖЕНИЕ АЧЕ)")
            messagebox.showerror("ERROR!", " Вы попытались закрыть окно! Начинаю удаление файлов")
    warning = f"Процент удаления: {a}"
    label3 = font.render(warning, 1, (12, 140, 0, 1))
    a = a + 1
    pygame.time.wait(100)
    if a >= 100:
        break

    screen.blit(label2, (50, 50))
    screen.blit(label3, (50, 100))
    pygame.display.update()

Also with your code I replaced pygame.quit() with pygame.display.quit() so the code will continue after the so called "error".


问:
Error 400: invalid_scope Some requested scopes cannot be shown: [https://www.googleapis.com/auth/homegraph]
So I'm trying to use the Home Graph API by calling the API endpoint

```<code>https://homegraph.googleapis.com/v1/devices:requestSync
</code>```

It is a HTTP POST request and it needs an ACCESS_TOKEN and service account key.

Getting the service account key is easily done as per Google's documentation. The issue is getting the ACCESS_TOKEN.

As per this documentation by Google, I need to get ACCESS_TOKEN created using the following scope of permissions

```<code>https://www.googleapis.com/auth/homegraph
</code>```

I opened OAuth 2.0 Playground to request a developer temporary ACCESS_TOKEN for testing.  I wrote all the necessary urls and in scope I wrote this-
scope is written to be authorized

Now after this, I am navigated to my Authorization URL (ie, Google's sign in page). I login with email id and password.

If credentials are correct and scope mentioned is valid then I should have been redirected to OAuth playground page with authorization code which I would have exchanged for access token and refresh token.

But, what actually happens is after I enter my credentials, I get following error and I am never redirected to Oauth Playground page-

Authorization Error

Error 400: invalid_scope

Some requested scopes cannot be shown: [https://www.googleapis.com/auth/homegraph]

Request Details

access_type=offline

o2v=2
  response_type=code

redirect_uri=https://developers.google.com/oauthplayground

prompt=consent
  client_id=xxxxxxxxx.apps.googleusercontent.com

scope=https://www.googleapis.com/auth/homegraph**

I searched a lot online too, but couldn't find the actual reason.
So due to this issue with scope, I am not able to get ACCESS_TOKEN.

I have followed Google's documentation and the scope was mentioned there.

This is the pic from oauth 2.0 playground settings- OAuth 2.0 configuration

答:
The issue is that you, a user, should not be getting and sending an access token. The service account should be getting and sending an access token. This is to make sure your service is authorized to talk to the Home Graph API.

You indicated you logged into the OAuth playground with "userid and password". But service accounts don't have passwords.

If you are using one of Google's libraries, it will take care of getting the access token for you, and this is the easiest way to do so. If you are just testing and need an access token, you can use something like oauth2l to get the access token based on the service account credentials.

Body:
So I'm trying to use the Home Graph API by calling the API endpoint

https://homegraph.googleapis.com/v1/devices:requestSync

It is a HTTP POST request and it needs an ACCESS_TOKEN and service account key.

Getting the service account key is easily done as per Google's documentation. The issue is getting the ACCESS_TOKEN.

As per this documentation by Google, I need to get ACCESS_TOKEN created using the following scope of permissions

https://www.googleapis.com/auth/homegraph

I opened OAuth 2.0 Playground to request a developer temporary ACCESS_TOKEN for testing.  I wrote all the necessary urls and in scope I wrote this-
scope is written to be authorized

Now after this, I am navigated to my Authorization URL (ie, Google's sign in page). I login with email id and password.

If credentials are correct and scope mentioned is valid then I should have been redirected to OAuth playground page with authorization code which I would have exchanged for access token and refresh token.

But, what actually happens is after I enter my credentials, I get following error and I am never redirected to Oauth Playground page-

Authorization Error

Error 400: invalid_scope

Some requested scopes cannot be shown: [https://www.googleapis.com/auth/homegraph]

Request Details

access_type=offline

o2v=2
  response_type=code

redirect_uri=https://developers.google.com/oauthplayground

prompt=consent
  client_id=xxxxxxxxx.apps.googleusercontent.com

scope=https://www.googleapis.com/auth/homegraph**

I searched a lot online too, but couldn't find the actual reason.
So due to this issue with scope, I am not able to get ACCESS_TOKEN.

I have followed Google's documentation and the scope was mentioned there.

This is the pic from oauth 2.0 playground settings- OAuth 2.0 configuration


问:
Why would IndexOf be unavailable in my array? I'm targeting .Net 3.5
I have a straight forward string array, why would IndexOf be unavailable? I'm targeting .Net 3.5

Thanks

答:
The reason you thought you could apply IndexOf as though it were an instance method is that some for types an extension method wraps Array.IndexOf() as Microsoft has for the GeoCoordinate class.

The following will work on all arrays:

```<code>public static class ExtensionMethods
{
  public static int IndexOf(this object[] oa, object o)
  {
    return Array.IndexOf(oa, o);
  }
}
</code>```

And here's a snippet of code showing how the code becomes more legible - at the price of making it dependent on the extension method class. I've deliberately undone the syntactic sugar on one of them so you can side-by-side compare.

```<code>  int m = Array.IndexOf(II, closestItems[0]);
  int n = II.IndexOf(closestItems[1]);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The reason you thought you could apply IndexOf as though it were an instance method is that some for types an extension method wraps Array.IndexOf() as Microsoft has for the GeoCoordinate class.

The following will work on all arrays:

public static class ExtensionMethods
{
  public static int IndexOf(this object[] oa, object o)
  {
    return Array.IndexOf(oa, o);
  }
}

And here's a snippet of code showing how the code becomes more legible - at the price of making it dependent on the extension method class. I've deliberately undone the syntactic sugar on one of them so you can side-by-side compare.

  int m = Array.IndexOf(II, closestItems[0]);
  int n = II.IndexOf(closestItems[1]);


问:
Resources not loading in Azure Portal
I have been having trouble with the Azure Portal (portal.azure.com) for the past 36 hours. At first I couldn't even load the log in page but a DNS flush seemed to help (sporadically).  Now that I'm able to log in somewhat successfully, none of my resources/services are loading:

I'm an admin on the Azure account so I don't think it's a permissions issue.

Any ideas?

答:
I too had a similar issue. I recently had created a new Azure account other than the one i use every day.

I started using both the accounts, and suddenly my old account Azure portal wouldn't load.

I tried the first answer's solution, but it did not help.

I just changed the browser through which i access the portal. Keep in mind i never used this other browser ever to access my Azure portal.
And it worked fine in the other browser.

Title: Resources not loading in Azure Portal


问:
Wordpress Woocommerce Show attributes on shop page
I want to add some attributes to the shop page of wordpress.
This code i found on Stackoverflow, is shows all attribute labes but on all the same attribute names.

```<code>add_action('woocommerce_after_shop_loop_item_title','add_attribute');
function add_attribute() {
global $product;

$product_attributes = array( 'pa_country','pa_class','pa_faction','pa_gender' );
$attr_output = array();

foreach( $product_attributes as $taxonomy ){
    if( taxonomy_exists($taxonomy) ){
        $label_name = get_taxonomy( $taxonomy )->labels->singular_name;
        $value = $product->get_attribute('pa_country','pa_class','pa_faction','pa_gender');

        if( ! empty($value) ){

            $attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$value.'</span>';
        }
    }}

echo '<div class="product-attributes">'.implode( '<br>', $attr_output ).'</div>';
</code>```

}

current state

I just need a bit help to get it to show all the right attributes.

答:
There a some little mistakes in your code. Try the following instead:

```<code>add_action('woocommerce_after_shop_loop_item_title', 'display_shop_loop_product_attributes');
function display_shop_loop_product_attributes() {
    global $product;

    // Define you product attribute taxonomies in the array
    $product_attribute_taxonomies = array( 'pa_country', 'pa_class', 'pa_faction', 'pa_gender' );
    $attr_output = array(); // Initializing

    // Loop through your defined product attribute taxonomies
    foreach( $product_attribute_taxonomies as $taxonomy ){
        if( taxonomy_exists($taxonomy) ){
            $label_name = wc_attribute_label( $taxonomy, $product );

            $term_names = $product->get_attribute( $taxonomy );

            if( ! empty($term_names) ){
                $attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$term_names.'</span>';
            }
        }
    }

    // Output
    echo '<div class="product-attributes">'.implode( '<br>', $attr_output ).'</div>';
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). tested and works.

For simple products only you will use the following instead:

```<code>add_action('woocommerce_after_shop_loop_item_title', 'display_shop_loop_product_attributes');
function display_shop_loop_product_attributes() {
    global $product;

    // Only for simple products
    if ( ! $product->is_type( 'simple' ) ) return;

    // Define you product attribute taxonomies in the array
    $product_attribute_taxonomies = array( 'pa_country', 'pa_class', 'pa_faction', 'pa_gender' );
    $attr_output = array(); // Initializing

    // Loop through your defined product attribute taxonomies
    foreach( $product_attribute_taxonomies as $taxonomy ){
        if( taxonomy_exists($taxonomy) ){
            $label_name = wc_attribute_label( $taxonomy, $product );

            $term_names = $product->get_attribute( $taxonomy );

            if( ! empty($term_names) ){
                $attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$term_names.'</span>';
            }
        }
    }

    // Output
    echo '<div class="product-attributes">'.implode( '<br>', $attr_output ).'</div>';
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). tested and works.

Body:
I want to add some attributes to the shop page of wordpress.
This code i found on Stackoverflow, is shows all attribute labes but on all the same attribute names.

add_action('woocommerce_after_shop_loop_item_title','add_attribute');
function add_attribute() {
global $product;

$product_attributes = array( 'pa_country','pa_class','pa_faction','pa_gender' );
$attr_output = array();

foreach( $product_attributes as $taxonomy ){
    if( taxonomy_exists($taxonomy) ){
        $label_name = get_taxonomy( $taxonomy )->labels->singular_name;
        $value = $product->get_attribute('pa_country','pa_class','pa_faction','pa_gender');

        if( ! empty($value) ){

            $attr_output[] = ''.$label_name.': '.$value.'';
        }
    }}

echo '
'.implode( '
', $attr_output ).'
';

}

current state

I just need a bit help to get it to show all the right attributes.

Body:
There a some little mistakes in your code. Try the following instead:

add_action('woocommerce_after_shop_loop_item_title', 'display_shop_loop_product_attributes');
function display_shop_loop_product_attributes() {
    global $product;

    // Define you product attribute taxonomies in the array
    $product_attribute_taxonomies = array( 'pa_country', 'pa_class', 'pa_faction', 'pa_gender' );
    $attr_output = array(); // Initializing

    // Loop through your defined product attribute taxonomies
    foreach( $product_attribute_taxonomies as $taxonomy ){
        if( taxonomy_exists($taxonomy) ){
            $label_name = wc_attribute_label( $taxonomy, $product );

            $term_names = $product->get_attribute( $taxonomy );

            if( ! empty($term_names) ){
                $attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$term_names.'</span>';
            }
        }
    }

    // Output
    echo '<div class="product-attributes">'.implode( '<br>', $attr_output ).'</div>';
}

Code goes in functions.php file of your active child theme (or active theme). tested and works.

For simple products only you will use the following instead:

add_action('woocommerce_after_shop_loop_item_title', 'display_shop_loop_product_attributes');
function display_shop_loop_product_attributes() {
    global $product;

    // Only for simple products
    if ( ! $product->is_type( 'simple' ) ) return;

    // Define you product attribute taxonomies in the array
    $product_attribute_taxonomies = array( 'pa_country', 'pa_class', 'pa_faction', 'pa_gender' );
    $attr_output = array(); // Initializing

    // Loop through your defined product attribute taxonomies
    foreach( $product_attribute_taxonomies as $taxonomy ){
        if( taxonomy_exists($taxonomy) ){
            $label_name = wc_attribute_label( $taxonomy, $product );

            $term_names = $product->get_attribute( $taxonomy );

            if( ! empty($term_names) ){
                $attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$term_names.'</span>';
            }
        }
    }

    // Output
    echo '<div class="product-attributes">'.implode( '<br>', $attr_output ).'</div>';
}

Code goes in functions.php file of your active child theme (or active theme). tested and works.


问:
ORA-04092: cannot ROLLBACK in a trigger after exceeding number of applications made daily
May I know how a trigger would be written if lets say there are applicant, position, applies relations and applies is like the association class as an applicant can apply many position and a position can by applied by many applicants and the applies relation has its own attribute called dateApp and I want to limit the amount of applications to twice a day, so this means a customer can only apply 2 items in one day. So far I have this code:

```<code>CREATE OR REPLACE TRIGGER APPLYTWICEONLY
AFTER INSERT ON APPLIES
DECLARE
CURSOR C IS
SELECT ANUMBER, COUNT(APPDATE) AS TOTAL
FROM APPLIES
WHERE APPDATE = TRUNC(SYSDATE)
GROUP BY ANUMBER;
BEGIN

FOR APPLY IN C
LOOP

   IF APPLY.TOTAL > 2 THEN
      DBMS_OUTPUT.PUT_LINE('AN APPLICANT CAN APPLY MAXIMUM TWICE A DAY.');
      ROLLBACK;
   END IF;
END LOOP;

END;
/
</code>```

so what is happening here is, after an applicant applies for a position, i check the total number of applications made today for each applicant using the anumber, if the total applications exceed 2 for an applicant today, then i will roll back and undo that insert. I want to do this using a statement  trigger instead of a row trigger, but i keep getting ORA-04092: cannot ROLLBACK in a trigger, after an applicant has exceeded the number of applications for the day. Can someone help me?

答:
You cannot run COMMIT or ROLLBACK in a trigger:</p>

```<code>$ oerr ora 4092
04092, 00000, "cannot %s in a trigger"
// *Cause: A trigger attempted to commit or rollback.
// *Action: Rewrite the trigger so it does not commit or rollback.
$
</code>```

Body:
May I know how a trigger would be written if lets say there are applicant, position, applies relations and applies is like the association class as an applicant can apply many position and a position can by applied by many applicants and the applies relation has its own attribute called dateApp and I want to limit the amount of applications to twice a day, so this means a customer can only apply 2 items in one day. So far I have this code:

CREATE OR REPLACE TRIGGER APPLYTWICEONLY
AFTER INSERT ON APPLIES
DECLARE
CURSOR C IS
SELECT ANUMBER, COUNT(APPDATE) AS TOTAL
FROM APPLIES
WHERE APPDATE = TRUNC(SYSDATE)
GROUP BY ANUMBER;
BEGIN

FOR APPLY IN C
LOOP

   IF APPLY.TOTAL > 2 THEN
      DBMS_OUTPUT.PUT_LINE('AN APPLICANT CAN APPLY MAXIMUM TWICE A DAY.');
      ROLLBACK;
   END IF;
END LOOP;

END;
/

so what is happening here is, after an applicant applies for a position, i check the total number of applications made today for each applicant using the anumber, if the total applications exceed 2 for an applicant today, then i will roll back and undo that insert. I want to do this using a statement  trigger instead of a row trigger, but i keep getting ORA-04092: cannot ROLLBACK in a trigger, after an applicant has exceeded the number of applications for the day. Can someone help me?

Body:
You cannot run COMMIT or ROLLBACK in a trigger:

$ oerr ora 4092
04092, 00000, "cannot %s in a trigger"
// *Cause: A trigger attempted to commit or rollback.
// *Action: Rewrite the trigger so it does not commit or rollback.
$


问:
How to change the style of a Ant-Design 'Select' component?
Suppose I want to change the standard white background color of the Select component to green.

My try...

```<code><Select
 style={{ backgroundColor: 'green' }}>
   // Options...
</Select>
</code>```

...didn't do it.

Can someone point me in the right direction?

[EDIT]

I ended up using the suggested approach from Jesper We.

Overwriting the color for all selections...

```<code>.ant-select-selection {
  background-color: transparent;
}
</code>```

...then I could style the Select components individually.

答:
From their official docs https://pro.ant.design/docs/style

Override the component style
Because of the special needs of the project, we often meet the need to cover the component style, here is a simple example.

Antd Select In multi-select state, the default will show all the select items, here we add a limit height for display scroll bar when the content beyond this height.

// TestPage.ts
import { Select } from 'antd';
import styles from './TestPage.less';
const Option = Select.Option;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

ReactDOM.render(
  <Select
    mode="multiple"
    style={{ width: 300 }}
    placeholder="Please select"
    className={styles.customSelect}
  >
        {children}

  </Select>,
  mountNode,
);
```
<pre class="lang-css prettyprint-override"><code>/* TestPage.less */
.customSelect {
  :global {
    .ant-select-selection {
      max-height: 51px;
      overflow: auto;
    }
  }
}
</code>```

Two points need to be noted:

The imported antd component class name is not translated by CSS Modules, so the overridden class name .ant-select-selection must be put in :global.
Because of the previous note, the override is global. To avoid affecting other Select components, the setting needs to be wrapped by an extra classname to add range restriction

Body:
Suppose I want to change the standard white background color of the Select component to green.

My try...

<Select
 style={{ backgroundColor: 'green' }}>
   // Options...
</Select>

...didn't do it.

Can someone point me in the right direction?

[EDIT]

I ended up using the suggested approach from Jesper We.

Overwriting the color for all selections...

.ant-select-selection {
  background-color: transparent;
}

...then I could style the Select components individually.

Body:
From their official docs https://pro.ant.design/docs/style

Override the component style
Because of the special needs of the project, we often meet the need to cover the component style, here is a simple example.

Antd Select In multi-select state, the default will show all the select items, here we add a limit height for display scroll bar when the content beyond this height.

// TestPage.ts
import { Select } from 'antd';
import styles from './TestPage.less';
const Option = Select.Option;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

ReactDOM.render(
  <Select
    mode="multiple"
    style={{ width: 300 }}
    placeholder="Please select"
    className={styles.customSelect}
  >
        {children}

  </Select>,
  mountNode,
);

/* TestPage.less */
.customSelect {
  :global {
    .ant-select-selection {
      max-height: 51px;
      overflow: auto;
    }
  }
}

Two points need to be noted:

The imported antd component class name is not translated by CSS Modules, so the overridden class name .ant-select-selection must be put in :global.
Because of the previous note, the override is global. To avoid affecting other Select components, the setting needs to be wrapped by an extra classname to add range restriction


问:
Arduino object constructor in class sets rubbish values
I am currently trying to create a class that has a member object with a non-default constructor for an Arduino project. The object is a pointer so that I can construct when MyClass is constructed (MyObjClass *my_obj;)

```<code>// MyObjClass:
class MyObjClass(){
    const int param;
public:
    MyObjClass(const int param): param(param){ ... }
};

// MyClass:
class MyClass(){
     MyObjClass *my_obj;
public:
     MyClass::MyClass(const int param): my_obj(param){ ... }
};
</code>```

It builds fine, but the value param in my_obj is rubbish (random value). Does it already initialize the object before the constructor call? My workaround is to use no const values but there must be a better way (the right way).

答:
You are holding pointer to MyObjClass and try to init him with some int, the
right way will be my_obj(new MyObjClass(param)).

Also I would suggest to use smart pointers to avoid memory leaks.

Body:
I am currently trying to create a class that has a member object with a non-default constructor for an Arduino project. The object is a pointer so that I can construct when MyClass is constructed (MyObjClass *my_obj;)

// MyObjClass:
class MyObjClass(){
    const int param;
public:
    MyObjClass(const int param): param(param){ ... }
};

// MyClass:
class MyClass(){
     MyObjClass *my_obj;
public:
     MyClass::MyClass(const int param): my_obj(param){ ... }
};

It builds fine, but the value param in my_obj is rubbish (random value). Does it already initialize the object before the constructor call? My workaround is to use no const values but there must be a better way (the right way).


问:
How can I avoid using *ngIf in an Angular template?
I tried using async/await to avoid *ngIf in the component template.

I'm getting an error in the Chrome console when I remove *ngIf in component template.

Can anyone help to get a solution. I do not want to use *ngIf in the component template as a requirement

I'm calling the GET REST API and used subscribe. Also, I'm getting results without the error if I'm using *ngIf, but I want the same results without using *ngIf

CODE:
component.ts

```<code>export class DisplayComponent implements OnInit {
users : user[];
user: user;
userResult: any;

  constructor(private http: HttpClient) { }

  ngOnInit() {
  }

  async readUser(id){
     this.userResult = await this.http.get<user>("http://localhost:8090/user/" +id).subscribe(
       data => {
         this.user = data;
       },
       error =>{
         return console.error();
         ;
       }
     )
    console.log("Fuuhhh! Client will wait till promise is resolved.");
  }
}
</code>```

CODE: DisplayComponent.html

```<code><div style="text-align: center;">
    <button (click)="loadUsers()">load Users</button>
    <table style="margin: 0 auto;" border="1">
        <tr>
            <th>Identity</th>
        </tr>
        <tr *ngFor="let user of users">
           <td>
            <button style="background: transparent;border: transparent;cursor: pointer;" (click)="readUser(user.id)">{{user?.id}}</button>
            </td>
        </tr>
    </table>

</div>
<div style="text-align: center;">
    <span style="color: darkgray;">Identity:</span> <span style="color: gray;">{{user.id}}</span> <br>
    <span>Name:</span> {{user.name}} <br>
    <span>School:</span> {{user.school}} <br>
</div>
</code>```

答:
I think you have to use the ngIf because, your template loads before it gets your data.
So your HTML is prepared to get the data. What you can do, and its more clean, is to create a boolean var:

```<code>isDataReady: Boolean = false;
</code>```

Then in your html just use it because it will always be false until you change it in your component when the subscription gets the data.

Also, in my projects i use an angular material spinner, to let the user know its loading the back end data with this variable i created.

Hope it helps!

Body:
I tried using async/await to avoid *ngIf in the component template.

I'm getting an error in the Chrome console when I remove *ngIf in component template.

Can anyone help to get a solution. I do not want to use *ngIf in the component template as a requirement

I'm calling the GET REST API and used subscribe. Also, I'm getting results without the error if I'm using *ngIf, but I want the same results without using *ngIf

CODE:
component.ts

export class DisplayComponent implements OnInit {
users : user[];
user: user;
userResult: any;

  constructor(private http: HttpClient) { }

  ngOnInit() {
  }

  async readUser(id){
     this.userResult = await this.http.get<user>("http://localhost:8090/user/" +id).subscribe(
       data => {
         this.user = data;
       },
       error =>{
         return console.error();
         ;
       }
     )
    console.log("Fuuhhh! Client will wait till promise is resolved.");
  }
}

CODE: DisplayComponent.html

    <button (click)="loadUsers()">load Users</button>

            Identity

            <button style="background: transparent;border: transparent;cursor: pointer;" (click)="readUser(user.id)">{{user?.id}}</button>

    Identity: {{user.id}}

    Name: {{user.name}}

    School: {{user.school}}

Body:
I think you have to use the ngIf because, your template loads before it gets your data.
So your HTML is prepared to get the data. What you can do, and its more clean, is to create a boolean var:

isDataReady: Boolean = false;

Then in your html just use it because it will always be false until you change it in your component when the subscription gets the data.

Also, in my projects i use an angular material spinner, to let the user know its loading the back end data with this variable i created.

Hope it helps!


问:
how to find all the text in a column where text without white space
I have data frame which has a column text it contain many text.I want to display only the text without white space.
eg.,

'hi how are you'  - I dont want this

'good'     - want this.

final column look like

hi

good

答:
You can use str.contains:

```<code>In [512]: df
Out[512]:
             text
0  hi how are you
1            good
2   hello friends

## check for whitespaces and take a `not` of it
In [516]: df = df[~df.text.str.contains(' ')]

In [516]: df
Out[516]:
   text
1  good
</code>```

Body:
You can use str.contains:

In [512]: df
Out[512]:
             text
0  hi how are you
1            good
2   hello friends

## check for whitespaces and take a `not` of it
In [516]: df = df[~df.text.str.contains(' ')]

In [516]: df
Out[516]:
   text
1  good


问:
unable to install apollo/react-hooks , requires peer of graphql
While installing npm install @apollo/react-hooks, I got the following error message. It tells me about installing graphql with a version higher than 14.3.1, but I have 15.0 installed.

```<code>npm WARN @apollo/react-common@3.1.4 requires a peer of graphql@^14.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN @apollo/react-components@3.1.5 requires a peer of graphql@^14.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN @apollo/react-hoc@3.1.5 requires a peer of graphql@^14.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN graphql-tag@2.10.3 requires a peer of graphql@^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 but none is installed. You
must install peer dependencies yourself.
npm WARN react-apollo@3.1.5 requires a peer of graphql@^14.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@3.17.1 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN @apollo/react-hooks@3.1.5 requires a peer of graphql@^14.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\jest-haste-map\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\webpack-dev-server\node_modules\fsevents):
 >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN @apollo/react-hooks@3.1.5 requires a peer of graphql@^14.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\jest-haste-map\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\webpack-dev-server\node_modules\fsevents):
32","arch":"x64"})
</code>```

答:
From the official github repo it seems like you need to install the following peer dependencies & also graphql should be < 15.0.0 since ^ means minor release i.e >= 14.5.8 and < 15.0.0

So do this npm install graphql@14.6.0

Body:
While installing npm install @apollo/react-hooks, I got the following error message. It tells me about installing graphql with a version higher than 14.3.1, but I have 15.0 installed.

npm WARN @apollo/react-common@3.1.4 requires a peer of graphql@^14.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN @apollo/react-components@3.1.5 requires a peer of graphql@^14.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN @apollo/react-hoc@3.1.5 requires a peer of graphql@^14.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN graphql-tag@2.10.3 requires a peer of graphql@^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 but none is installed. You
must install peer dependencies yourself.
npm WARN react-apollo@3.1.5 requires a peer of graphql@^14.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@3.17.1 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN @apollo/react-hooks@3.1.5 requires a peer of graphql@^14.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\jest-haste-map\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\webpack-dev-server\node_modules\fsevents):
 >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN @apollo/react-hooks@3.1.5 requires a peer of graphql@^14.3.1 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\jest-haste-map\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\webpack-dev-server\node_modules\fsevents):
32","arch":"x64"})


问:
How to use Firefox responsive design mode for media queries
Whenever I press ctrl+shift+m to enter responsive design mode in Firefox, it shows the screen dimensions in the upper left, but if I see 992px as the width here and then create this media query:

```<code>@media (min-width: 992px) {
    /*stuff to happen at 992px*/
}
</code>```

, the stuff that is supposed to happen at 992px actually happens at 1082px, according to Firefox.  Why is this?  Is there a way to get Firefox's measurements to match exactly with the results that media queries produce?

Additionally, stuff that is supposed to happen at 768px according to the media query appears to be happening at 838px.

答:
In Firefox, Make Sure while testing for website responsiveness , the browser zoom setting to be 100% only. It effects the screen width shown to you in RDM (Responsive Design Mode).

I am not sure about others but i got same issue earlier.

Body:
Whenever I press ctrl+shift+m to enter responsive design mode in Firefox, it shows the screen dimensions in the upper left, but if I see 992px as the width here and then create this media query:

@media (min-width: 992px) {
    /*stuff to happen at 992px*/
}

, the stuff that is supposed to happen at 992px actually happens at 1082px, according to Firefox.  Why is this?  Is there a way to get Firefox's measurements to match exactly with the results that media queries produce?

Additionally, stuff that is supposed to happen at 768px according to the media query appears to be happening at 838px.