问:
How to save audio of AudioRecord in a file?
Background:
I am making an android application by which I would capture the live audio of user and then transmit it to his PC via Socket. I am using AudioRecord for live recording, and AudioTrack for listening the Audio. I am able to capture the live audio and then play it at same time.

Problem:
I want to save the voice of user that I am capturing live, in a file which is Playable. I tried saving the output in a file with a .mp3 and .pcm extension, but these files are not playable. How  I can save the output genereated by AudioRecord Object in a file that can be Playable.

Below is my Code for Capturing and Playing Live Audio:

```<code> AudioRecord recorder;
AudioTrack audioTrack;

short[] buffer;
int sampleRate = AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_MUSIC);//48000
int channelConfig = AudioFormat.CHANNEL_IN_MONO;
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);//3840

DataOutputStream dos;

                        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                                sampleRate,
                                channelConfig ,
                                AudioFormat.ENCODING_PCM_16BIT,
                                bufferSize );

                        recorder.startRecording();

                        //For playing audio
                        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC
                                , sampleRate
                                , AudioFormat.CHANNEL_OUT_MONO
                                , AudioFormat.ENCODING_PCM_16BIT
                                , bufferSize
                                , AudioTrack.MODE_STREAM);

                        audioTrack.setPlaybackRate(sampleRate);
                        audioTrack.play();

                        buffer = new short[bufferSize/4];
                        audioPlaying =true;

                        try {
                            dataOutputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(getRecordingFilePath())));

                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.d(TAG,"Exception >>"+e.toString());

                        }

                        while (audioPlaying){
                            //reading audio from buffer
                            int bufferReadResult =recorder.read(buffer, 0, bufferSize/4);

                            //playing that audio simultaneously
                            audioTrack.write(buffer, 0, bufferSize/4);

                            //Saving file (Unable to Play it)
                            try {
                                     for (int i = 0; i < bufferReadResult; i++ )
                                     {
                                         dataOutputStream.writeShort(buffer[i]);
                                     }

                                Log.d(TAG,"Writing file");

                            } catch (Exception e) {
                                Log.d(TAG,"183 Eception>>"+e.toString());
                                e.printStackTrace();
                            }
                        }

private String getRecordingFilePath()
    {
        Log.d(TAG, "Creating File for Audio");
        //I am using android 11

        ContextWrapper contextWrapper= new ContextWrapper(getApplicationContext());
        File musicDirectory = contextWrapper.getExternalFilesDir(Environment.DIRECTORY_MUSIC);
        File file = new File(musicDirectory,"testAudioFile.pcm");
        String path = file.getPath();
        Log.d(TAG, "File created at path:" + path);

        return path;
    }
</code>```

答:
After some research, I found a solution. Not perfect, but somehow helped me. If anyone knows better answer then then the below code, Post it.</p>
```<code>private void playFileAudio() {
    byte[] byteData = null;
    File file = null;
    file = new File(getRecordingFilePath());
    byteData = new byte[(int) file.length()];
    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream( file );
        fileInputStream.read( byteData );
        fileInputStream.close();
        Log.d(TAG,"File Readed");

    } catch (Exception e) {
        Log.d(TAG,"Exception>>:"+e.toString());
        e.printStackTrace();
    }

    if (audioTrack!=null) {
        audioTrack.play();
        Log.d(TAG, "File is being played");
        audioTrack.write(byteData, 0, byteData.length);
        audioTrack.stop();
        audioTrack.release();
    }
    else{
        Log.d(TAG, "audio track is not initialised ");

    }
}
</code>```

Body:
Background:
I am making an android application by which I would capture the live audio of user and then transmit it to his PC via Socket. I am using AudioRecord for live recording, and AudioTrack for listening the Audio. I am able to capture the live audio and then play it at same time.

Problem:
I want to save the voice of user that I am capturing live, in a file which is Playable. I tried saving the output in a file with a .mp3 and .pcm extension, but these files are not playable. How  I can save the output genereated by AudioRecord Object in a file that can be Playable.

Below is my Code for Capturing and Playing Live Audio:

 AudioRecord recorder;
AudioTrack audioTrack;

short[] buffer;
int sampleRate = AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_MUSIC);//48000
int channelConfig = AudioFormat.CHANNEL_IN_MONO;
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);//3840

DataOutputStream dos;

                        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                                sampleRate,
                                channelConfig ,
                                AudioFormat.ENCODING_PCM_16BIT,
                                bufferSize );

                        recorder.startRecording();

                        //For playing audio
                        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC
                                , sampleRate
                                , AudioFormat.CHANNEL_OUT_MONO
                                , AudioFormat.ENCODING_PCM_16BIT
                                , bufferSize
                                , AudioTrack.MODE_STREAM);

                        audioTrack.setPlaybackRate(sampleRate);
                        audioTrack.play();

                        buffer = new short[bufferSize/4];
                        audioPlaying =true;

                        try {
                            dataOutputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(getRecordingFilePath())));

                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.d(TAG,"Exception >>"+e.toString());

                        }

                        while (audioPlaying){
                            //reading audio from buffer
                            int bufferReadResult =recorder.read(buffer, 0, bufferSize/4);

                            //playing that audio simultaneously
                            audioTrack.write(buffer, 0, bufferSize/4);

                            //Saving file (Unable to Play it)
                            try {
                                     for (int i = 0; i < bufferReadResult; i++ )
                                     {
                                         dataOutputStream.writeShort(buffer[i]);
                                     }

                                Log.d(TAG,"Writing file");

                            } catch (Exception e) {
                                Log.d(TAG,"183 Eception>>"+e.toString());
                                e.printStackTrace();
                            }
                        }

private String getRecordingFilePath()
    {
        Log.d(TAG, "Creating File for Audio");
        //I am using android 11

        ContextWrapper contextWrapper= new ContextWrapper(getApplicationContext());
        File musicDirectory = contextWrapper.getExternalFilesDir(Environment.DIRECTORY_MUSIC);
        File file = new File(musicDirectory,"testAudioFile.pcm");
        String path = file.getPath();
        Log.d(TAG, "File created at path:" + path);

        return path;
    }

Body:
After some research, I found a solution. Not perfect, but somehow helped me. If anyone knows better answer then then the below code, Post it.

private void playFileAudio() {
    byte[] byteData = null;
    File file = null;
    file = new File(getRecordingFilePath());
    byteData = new byte[(int) file.length()];
    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream( file );
        fileInputStream.read( byteData );
        fileInputStream.close();
        Log.d(TAG,"File Readed");

    } catch (Exception e) {
        Log.d(TAG,"Exception>>:"+e.toString());
        e.printStackTrace();
    }

    if (audioTrack!=null) {
        audioTrack.play();
        Log.d(TAG, "File is being played");
        audioTrack.write(byteData, 0, byteData.length);
        audioTrack.stop();
        audioTrack.release();
    }
    else{
        Log.d(TAG, "audio track is not initialised ");

    }
}


来源: stackexchange

问:
Pass data to a child components in RDK LightningJS
I am trying to build a page with multiple row of tiles using LightningJS. I have looked at the examples in https://github.com/rdkcentral/Lightning-UI-Components/blob/master/components/FocusManager/FocusManager.stories.js and have used ColumnWithRowsExample as my starting point. All the examples rely on data being available at the point of initializing a component.
I need to pass data down to child components dynamically, and be able to refresh them. I am unable to find how to get this info in their samples or docs.
I have done trial and error for a week and have not progressed. Any snippets/samples or docs with this info would be helpful.</p>

答:
You can use this.application.emit("func name", {data})
and access anywhere, using this.application.on("func name", (data)=>{ logic })

ContentLicense: CC BY-SA 4.0


问:
How to create an increasing index based on a certain condition?
Suppose I have this dataframe:

```<code>df <- data.frame(co11 = c(rep(1, 5), 5, 6, rep(1, 3), 2, 3, 4, 5, 8, rep(1, 2), rep(2, 2), 8, 10))
</code>```

I would like to create another column (col2) with increasing group index whenever a value in a row is at least 5. To illustrate, here is the resulting df that I would like to get:

```<code>   co11  col2
1     1     1
2     1     1
3     1     1
4     1     1
5     1     1
6     5     2
7     6     3
8     1     3
9     1     3
10    1     3
11    2     3
12    3     3
13    4     3
14    5     4
15    8     5
16    1     5
17    1     5
18    2     5
19    2     5
20    8     6
21   10     7
</code>```

Is there an available function in dplyr that can do this?

答:
You could use pmax to find maximum value of each row, and cumsum to sum occurences above 5 :

```<code>df  %>% mutate(newcol=cumsum(do.call(pmax,select(.,everything()))>=5)+1)

   co11 newcol
1     1      1
2     1      1
3     1      1
4     1      1
5     1      1
6     5      2
7     6      3
8     1      3
9     1      3
10    1      3
11    2      3
12    3      3
13    4      3
14    5      4
15    8      5
16    1      5
17    1      5
18    2      5
19    2      5
20    8      6
21   10      7
</code>```

Body:
Suppose I have this dataframe:

df <- data.frame(co11 = c(rep(1, 5), 5, 6, rep(1, 3), 2, 3, 4, 5, 8, rep(1, 2), rep(2, 2), 8, 10))

I would like to create another column (col2) with increasing group index whenever a value in a row is at least 5. To illustrate, here is the resulting df that I would like to get:

   co11  col2
1     1     1
2     1     1
3     1     1
4     1     1
5     1     1
6     5     2
7     6     3
8     1     3
9     1     3
10    1     3
11    2     3
12    3     3
13    4     3
14    5     4
15    8     5
16    1     5
17    1     5
18    2     5
19    2     5
20    8     6
21   10     7

Is there an available function in dplyr that can do this?

Body:
You could use pmax to find maximum value of each row, and cumsum to sum occurences above 5 :

df  %>% mutate(newcol=cumsum(do.call(pmax,select(.,everything()))>=5)+1)

   co11 newcol
1     1      1
2     1      1
3     1      1
4     1      1
5     1      1
6     5      2
7     6      3
8     1      3
9     1      3
10    1      3
11    2      3
12    3      3
13    4      3
14    5      4
15    8      5
16    1      5
17    1      5
18    2      5
19    2      5
20    8      6
21   10      7


问:
why is javascript script not working in html code
im making a website and im trying to put some javascript but it gives me an error can anyone tell me why?

HTML code

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <link rel="stylesheet" href="css/main.css">

Searching now...

                MyWebsite

This is My Website.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa ea vel eius voluptas perspiciatis accusantium ut sed veritatis et porro.

                <form action="">

                        Enter your city:
                        <input type="text" name="city" id="city">

Example: New York city

                    <input type="button" value="Enter" id="cta-btn">
                </form>

Lorem, ipsum.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Aliquid dolorem in animi. Fugit ab iusto commodi corporis voluptatum enim, illum nostrum beatae facilis voluptates et facere ipsum inventore nemo repellat rerum itaque obcaecati magni fugiat molestiae? Illo, quod neque cum nam porro necessitatibus qui iure vel nesciunt a veritatis placeat magnam exercitationem veniam, nemo adipisci est quaerat. Placeat repellendus aperiam consectetur voluptas saepe quae, fugiat dolores tempora nobis, maxime corporis nulla non, suscipit voluptate! Cumque.

```
<p><strong>error</strong></p>
<pre class="lang-html prettyprint-override"><code>
        let btn = document.getElementById('ctn-btn')
        let overlay = document.getElementById('overlay')

        btn.addEventListener('click' () = {  /*this is not working*/
            overlay.style.display = 'grid'
        })

</code>```

in the video it was also ('click' () => { but that gave me an error so i deleted the >
this is my first time trying javascript in a website

it gives me an error under the . in overlay.style did i forget to add something in the head tag?

anyone know the problem?

答:
You are missing a comma after your "click"

the code should be.

```<code>let btn = document.getElementById("ctn-btn");
let overlay = document.getElementById("overlay");

btn.addEventListener("click", () => {
  overlay.style.display = "grid";
});
</code>```

As you are starting out now, remember every code, need to be of a specific structure (syntax), if you change the structure, it may not work as expected. For now, try to learn the syntax as much as possible, whiles learning the logic behind the code that you write.

Body:
im making a website and im trying to put some javascript but it gives me an error can anyone tell me why?

HTML code

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <link rel="stylesheet" href="css/main.css">

Searching now...

                MyWebsite

This is My Website.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa ea vel eius voluptas perspiciatis accusantium ut sed veritatis et porro.

                <form action="">

                        Enter your city:
                        <input type="text" name="city" id="city">

Example: New York city

                    <input type="button" value="Enter" id="cta-btn">
                </form>

Lorem, ipsum.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Aliquid dolorem in animi. Fugit ab iusto commodi corporis voluptatum enim, illum nostrum beatae facilis voluptates et facere ipsum inventore nemo repellat rerum itaque obcaecati magni fugiat molestiae? Illo, quod neque cum nam porro necessitatibus qui iure vel nesciunt a veritatis placeat magnam exercitationem veniam, nemo adipisci est quaerat. Placeat repellendus aperiam consectetur voluptas saepe quae, fugiat dolores tempora nobis, maxime corporis nulla non, suscipit voluptate! Cumque.

error

        let btn = document.getElementById('ctn-btn')
        let overlay = document.getElementById('overlay')

        btn.addEventListener('click' () = {  /*this is not working*/
            overlay.style.display = 'grid'
        })

in the video it was also ('click' () => { but that gave me an error so i deleted the >
this is my first time trying javascript in a website

it gives me an error under the . in overlay.style did i forget to add something in the head tag?

anyone know the problem?

Body:
You are missing a comma after your "click"

the code should be.

let btn = document.getElementById("ctn-btn");
let overlay = document.getElementById("overlay");

btn.addEventListener("click", () => {
  overlay.style.display = "grid";
});

As you are starting out now, remember every code, need to be of a specific structure (syntax), if you change the structure, it may not work as expected. For now, try to learn the syntax as much as possible, whiles learning the logic behind the code that you write.


问:
radio button's vertical align and it's width
I have noticed that if I have a text and then a radio, like:

```<code><label for "myradio">Radio name</label>
<div class="holder">Yes <input type="radio" name="myradio" value="Yes"></div>
<div class="holder">No <input type="radio" name="myradio" value="No"></div>
</code>```

Where:

```<code>label       { width: auto; margin-left: 15px; float: left; }
.holder     { float: left; line-height: 13px; margin: 6px 0 0 7px;  }
.holder input[type=radio]   { float: right; }
</code>```

Now the problem with this is that, the radio appears after and a bit below (as if there is a top margin) the text "yes" or "no".

Now if I add a width (wide enough) to my .holder, I get both text and radio at the same line. However, if the width is smaller than the width of yes + radio, the radio gets positioned lower as before.

If it were only "yes" and "no", I could use a fixed width, but the problem is that those "yes" and "no" are database generated, and hence I can't control the text width. So I need a different way to put the text and radio in the same line.

Any idea guys ?

答:
check my jsfiddle

is it what you wanted to achieve? just add

```<code> .holder span{float: left;margin-right: 3px;}
 .holder input{float: left;}
</code>```

and wrap "yes" and "no" in

```<code> <span></span>
</code>```

tag

ContentLicense: CC BY-SA 3.0

Body:
I have noticed that if I have a text and then a radio, like:

Radio name

Yes <input type="radio" name="myradio" value="Yes">

No <input type="radio" name="myradio" value="No">

Where:

label       { width: auto; margin-left: 15px; float: left; }
.holder     { float: left; line-height: 13px; margin: 6px 0 0 7px;  }
.holder input[type=radio]   { float: right; }

Now the problem with this is that, the radio appears after and a bit below (as if there is a top margin) the text "yes" or "no".

Now if I add a width (wide enough) to my .holder, I get both text and radio at the same line. However, if the width is smaller than the width of yes + radio, the radio gets positioned lower as before.

If it were only "yes" and "no", I could use a fixed width, but the problem is that those "yes" and "no" are database generated, and hence I can't control the text width. So I need a different way to put the text and radio in the same line.

Any idea guys ?

Body:
check my jsfiddle

is it what you wanted to achieve? just add

 .holder span{float: left;margin-right: 3px;}
 .holder input{float: left;}

and wrap "yes" and "no" in

 <span></span>

tag


问:
Why are the open system call mode values different for equivalent code?
Below code and the quoted statement are from Linux System Programming by Robert Love.
I don't understand how are the modes in the first and the second code examples the same.

From the first example, I calculated the mode values as

```<code>USR -> 2+1 = 3
GRP -> 2+1 = 3
OTH -> 1 =   1
</code>```

So my expectation was 0331, but it the book says it's 0664.

What's wrong in my logic?

Copied from the book below:

```<code>int fd;
fd = open (file, O_WRONLY | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IROTH);
if(fd == -1)
 /* error */
</code>```

Trading portability (in theory at least) for readability, we could
have written the following, to identical effect:

```<code>int fd;
fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0664);
if(fd == -1)
 /*error*/
</code>```

答:
For whichever reason, you have chosen to use the wrong values for the constants.

Instead of S_IRUSR being 0400, you decided it was 0200.

Instead of S_IWUSR being 0200, you decided it was 0100.

etc

If you use the correct values for the constants, you will get the same result.

Body:
Below code and the quoted statement are from Linux System Programming by Robert Love.
I don't understand how are the modes in the first and the second code examples the same.

From the first example, I calculated the mode values as

USR -> 2+1 = 3
GRP -> 2+1 = 3
OTH -> 1 =   1

So my expectation was 0331, but it the book says it's 0664.

What's wrong in my logic?

Copied from the book below:

int fd;
fd = open (file, O_WRONLY | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IROTH);
if(fd == -1)
 /* error */

Trading portability (in theory at least) for readability, we could
have written the following, to identical effect:

int fd;
fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0664);
if(fd == -1)
 /*error*/


问:
how to disable ripple in nuxt js with vuetify?
I have created a NuxtJS project and selected Vuetify as the UI framework from default selections. I would like to disable the ripple effect on buttons and other possible vuetify components. Since there is no dedicated Vuetify.js file and all are configured in the nuxt.config.js file, I tried editing the same.

```<code>vuetify: {
button: {
  disableRipple: true,
},
}
</code>```

but no use. So, any help on this would be appreciated

答:
After a long research, found out that, remove ripple effect on icon button accepted answer solved my case too. Answer maybe common but question is different

In case if anything changes/for future reference,

```<code>.v-btn:before {
   opacity: 0 !important;
}
.v-ripple__container {
   opacity: 0 !important;
}
</code>```

Thanks to Anant Vikram Singh

Body:
I have created a NuxtJS project and selected Vuetify as the UI framework from default selections. I would like to disable the ripple effect on buttons and other possible vuetify components. Since there is no dedicated Vuetify.js file and all are configured in the nuxt.config.js file, I tried editing the same.

vuetify: {
button: {
  disableRipple: true,
},
}

but no use. So, any help on this would be appreciated

Body:
After a long research, found out that, remove ripple effect on icon button accepted answer solved my case too. Answer maybe common but question is different

In case if anything changes/for future reference,

.v-btn:before {
   opacity: 0 !important;
}
.v-ripple__container {
   opacity: 0 !important;
}

Thanks to Anant Vikram Singh


问:
How to concatenate more sql queries to get one table?
I have 4 tables that I have used following queries to get data,

```<code>query1 : select * from userdetails1.UserTable;

Result1:
UserID  Username    Status
1         John      Active
2         Micheal   Active
3         Ann       Active
4         Shasha    Resigned
5         mike      Resigned

query2 : select * from userdetails2.AmountTable;

result2:
UserId  TotalAmount TotalAmountResetDate
1          -12         1/31/2022
2          345         1/31/2022
3          213         1/31/2022
4          0           1/31/2022
5          0           1/31/2022

query3:
select Username,TotalInvested from userdetails2.TotalInvestmentsTable group by Username;

result3:

Username    Totalnvested
John         45000
Micheal      45000
Ann          45000

query4:
select Username,TotalExpenses from userdetails2.TotalExpensesTable group by Username;

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290
</code>```

Now I need to get another table by combining all these queries as follows. How should I get that by concatenating all these queries?

```<code>UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested    TotalExpenses   TotalBalance
1        John              1/31/2022               -12       45000            2543          42445
2        Micheal           1/31/2022               345       45000            2345          43000
3        Ann               1/31/2022               213       45000            3290          41923
4        Shasha            1/31/2022               0         0                 0            0
5        mike              1/31/2022               0         0                 0            0
</code>```

Here TotalBalance column need to get from TotalBalance=TotalAmount+Totalnvested -TotalExpenses.Is this possible to get using one query?

Update:

If the total expenses and total investments are more than one value we need to get sum of each user to the total investements. Then how we can get that one?

Example:

```<code>Username    Totalnvested
    John         45000
    Micheal      45000
    Ann          45000
    John         21000
    Micheal       5000

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290
Ann            2345
John            5478
</code>```

答:
try like below using join and aggregation</p>
```<code>    select ut.UserId,
ut.Username,
ua.TotalAmountResetDate,
sum(TotalAmount) as TotalAmount,
sum(Totalnvested) as TotalInvested,
sum(TotalExpenses) as TotalExpenses,
sum(TotalAmount+coalesce(Totalnvested ,0)- coalesce(TotalExpenses,0)) as TotalBalance

from userdetails1.UserTable ut
left join
userdetails2.AmountTable ua on ut.UserId=ua.UserId

LEFT JOIN userdetails2.TotalInvestmentsTable env on
ut.Username = env.Username
LEFT JOIN userdetails2.TotalExpensesTable ex
on ut.Username = ex.Username
group by ut.UserId,
ut.Username,
ua.TotalAmountResetDate
</code>```

Body:
I have 4 tables that I have used following queries to get data,

query1 : select * from userdetails1.UserTable;

Result1:
UserID  Username    Status
1         John      Active
2         Micheal   Active
3         Ann       Active
4         Shasha    Resigned
5         mike      Resigned

query2 : select * from userdetails2.AmountTable;

result2:
UserId  TotalAmount TotalAmountResetDate
1          -12         1/31/2022
2          345         1/31/2022
3          213         1/31/2022
4          0           1/31/2022
5          0           1/31/2022

query3:
select Username,TotalInvested from userdetails2.TotalInvestmentsTable group by Username;

result3:

Username    Totalnvested
John         45000
Micheal      45000
Ann          45000

query4:
select Username,TotalExpenses from userdetails2.TotalExpensesTable group by Username;

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290

Now I need to get another table by combining all these queries as follows. How should I get that by concatenating all these queries?

UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested    TotalExpenses   TotalBalance
1        John              1/31/2022               -12       45000            2543          42445
2        Micheal           1/31/2022               345       45000            2345          43000
3        Ann               1/31/2022               213       45000            3290          41923
4        Shasha            1/31/2022               0         0                 0            0
5        mike              1/31/2022               0         0                 0            0

Here TotalBalance column need to get from TotalBalance=TotalAmount+Totalnvested -TotalExpenses.Is this possible to get using one query?

Update:

If the total expenses and total investments are more than one value we need to get sum of each user to the total investements. Then how we can get that one?

Example:

Username    Totalnvested
    John         45000
    Micheal      45000
    Ann          45000
    John         21000
    Micheal       5000

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290
Ann            2345
John            5478

Body:
try like below using join and aggregation

    select ut.UserId,
ut.Username,
ua.TotalAmountResetDate,
sum(TotalAmount) as TotalAmount,
sum(Totalnvested) as TotalInvested,
sum(TotalExpenses) as TotalExpenses,
sum(TotalAmount+coalesce(Totalnvested ,0)- coalesce(TotalExpenses,0)) as TotalBalance

from userdetails1.UserTable ut
left join
userdetails2.AmountTable ua on ut.UserId=ua.UserId

LEFT JOIN userdetails2.TotalInvestmentsTable env on
ut.Username = env.Username
LEFT JOIN userdetails2.TotalExpensesTable ex
on ut.Username = ex.Username
group by ut.UserId,
ut.Username,
ua.TotalAmountResetDate


问:
SFTP error - Exhausted available authentication methods
```<code>private SSHClient initSSHj(String remoteHost, String username, String password)
      throws IOException {
    SSHClient client = new SSHClient();
    client.addHostKeyVerifier(new PromiscuousVerifier());
    client.connect(remoteHost);
    client.authPassword(username, password);
    return client;
  }

protected void uploadFile(
  String localFilePath,
  String remoteHost,
  String username,
  String remotePassword,
  String remoteFilePath) {
try {
  SSHClient sshClient = initSSHj(remoteHost, username, remotePassword);
  SFTPClient sftpClient = sshClient.newSFTPClient();
  sftpClient.getFileTransfer().setPreserveAttributes(false);
  sftpClient.put(localFilePath, remoteFilePath);
  sftpClient.close();
  sshClient.disconnect();
} catch (IOException ex) {
  log.info("Error file to the server :: {}", ex.getMessage());
  throw new Exception("Error file to the server");
}
</code>```

}

The error

{"@timestamp":"2022-02-11T19:38:43.867+05:30","@version":"1","message":"Received SSH_MSG_DISCONNECT (reason=BY_APPLICATION, msg=)","logger_name":"net.schmizz.sshj.transport.TransportImpl","thread_name":"reader","level":"INFO","level_value":20000}
{"@timestamp":"2022-02-11T19:38:43.868+05:30","@version":"1","message":"Dying because - ","logger_name":"net.schmizz.sshj.transport.TransportImpl","thread_name":"reader","level":"ERROR","level_value":40000,"stack_trace":"net.schmizz.sshj.transport.TransportException: \n\tat net.schmizz.sshj.transport.TransportImpl.gotDisconnect(TransportImpl.java:565)\n\tat net.schmizz.sshj.transport.TransportImpl.handle(TransportImpl.java:521)\n\tat net.schmizz.sshj.transport.Decoder.decodeMte(Decoder.java:159)\n\tat net.schmizz.sshj.transport.Decoder.decode(Decoder.java:79)\n\tat net.schmizz.sshj.transport.Decoder.received(Decoder.java:231)\n\tat net.schmizz.sshj.transport.Reader.run(Reader.java:60)\n"}
{"@timestamp":"2022-02-11T19:38:43.868+05:30","@version":"1","message":"Disconnected - BY_APPLICATION","logger_name":"net.schmizz.sshj.transport.TransportImpl","thread_name":"reader","level":"INFO","level_value":20000}

I have checked username and password, there is no issue. I also have write permission to upload the file in sftp.

From the command line , same creds work for sftp connection.

答:
The error message means that it (the client) has tried all of the methods of authentication that the server allows (at this time / for this kind of connection) and exhausted them.

Have checked username and password, there is no issue.

It may be that the server does not permit user/password authentication in this context.  Maybe it requires public key authentication.

(It is common practice to disallow user / password authentication when connecting to a public IP address.  Its a good way to eliminate the risk of hacking by password guessing.)

If you have (for example) fail2ban set up on the server, it may be that access is temporarily blocked due to too many recent failed attempts to login.

Also have write permission to upload the file in sftp.

That won't be relevant.  The session hasn't gotten to the point where it needs to check file's permissions.

Check the server-side logs (e.g. the security log).  If there is nothing helpful there, you could try increasing the logging level on the server side (e.g. for sshd) to get more information about why the authentication is failing.

Body:
private SSHClient initSSHj(String remoteHost, String username, String password)
      throws IOException {
    SSHClient client = new SSHClient();
    client.addHostKeyVerifier(new PromiscuousVerifier());
    client.connect(remoteHost);
    client.authPassword(username, password);
    return client;
  }

protected void uploadFile(
  String localFilePath,
  String remoteHost,
  String username,
  String remotePassword,
  String remoteFilePath) {
try {
  SSHClient sshClient = initSSHj(remoteHost, username, remotePassword);
  SFTPClient sftpClient = sshClient.newSFTPClient();
  sftpClient.getFileTransfer().setPreserveAttributes(false);
  sftpClient.put(localFilePath, remoteFilePath);
  sftpClient.close();
  sshClient.disconnect();
} catch (IOException ex) {
  log.info("Error file to the server :: {}", ex.getMessage());
  throw new Exception("Error file to the server");
}

}

The error

{"@timestamp":"2022-02-11T19:38:43.867+05:30","@version":"1","message":"Received SSH_MSG_DISCONNECT (reason=BY_APPLICATION, msg=)","logger_name":"net.schmizz.sshj.transport.TransportImpl","thread_name":"reader","level":"INFO","level_value":20000}
{"@timestamp":"2022-02-11T19:38:43.868+05:30","@version":"1","message":"Dying because - ","logger_name":"net.schmizz.sshj.transport.TransportImpl","thread_name":"reader","level":"ERROR","level_value":40000,"stack_trace":"net.schmizz.sshj.transport.TransportException: \n\tat net.schmizz.sshj.transport.TransportImpl.gotDisconnect(TransportImpl.java:565)\n\tat net.schmizz.sshj.transport.TransportImpl.handle(TransportImpl.java:521)\n\tat net.schmizz.sshj.transport.Decoder.decodeMte(Decoder.java:159)\n\tat net.schmizz.sshj.transport.Decoder.decode(Decoder.java:79)\n\tat net.schmizz.sshj.transport.Decoder.received(Decoder.java:231)\n\tat net.schmizz.sshj.transport.Reader.run(Reader.java:60)\n"}
{"@timestamp":"2022-02-11T19:38:43.868+05:30","@version":"1","message":"Disconnected - BY_APPLICATION","logger_name":"net.schmizz.sshj.transport.TransportImpl","thread_name":"reader","level":"INFO","level_value":20000}

I have checked username and password, there is no issue. I also have write permission to upload the file in sftp.

From the command line , same creds work for sftp connection.


问:
Installing node-sass fails on Ubuntu 18.04
I have a simple next.js project, which I created following their tutorial. It builds and runs well on my Windows development machine.

I want to deploy it on Ubuntu 18.04.02 LTS but when I clone the git project and run npm install it fails to install node-sass with the following error message:

```<code>> node-sass@4.12.0 install /var/www/example.com/beta/node_modules/node-sass
> node scripts/install.js

internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module '/var/www/example.com/beta/node_modules/node-sass/scripts/install.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.12.0 install: `node scripts/install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@4.12.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: ...
</code>```

Here is a gist of the log file. See the last few lines for the error (I have included the whole file in case there is other information that is useful).

My NodeJS version is 10.15.3 and my NPM version is 6.4.1. I am not sure how to run next.js project on Ubuntu.

答:
This module has striction about node versions, as below:

solution is: specify the module version when you install it.

P.S. Other approach:

if you just want to use scss/sass, use this module:

```<code> npm install sass sass-loader
</code>```

this does NOT work for: node 16, ubuntu 18

```<code>npm install --unsafe-perms
</code>```

for node 14, ubuntu 18 , I can install it:

```<code>npm install node-sass
</code>```

Body:
I have a simple next.js project, which I created following their tutorial. It builds and runs well on my Windows development machine.

I want to deploy it on Ubuntu 18.04.02 LTS but when I clone the git project and run npm install it fails to install node-sass with the following error message:

> node-sass@4.12.0 install /var/www/example.com/beta/node_modules/node-sass
> node scripts/install.js

internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module '/var/www/example.com/beta/node_modules/node-sass/scripts/install.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.12.0 install: `node scripts/install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@4.12.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: ...

Here is a gist of the log file. See the last few lines for the error (I have included the whole file in case there is other information that is useful).

My NodeJS version is 10.15.3 and my NPM version is 6.4.1. I am not sure how to run next.js project on Ubuntu.

Body:
This module has striction about node versions, as below:

solution is: specify the module version when you install it.

P.S. Other approach:

if you just want to use scss/sass, use this module:

 npm install sass sass-loader

this does NOT work for: node 16, ubuntu 18

npm install --unsafe-perms

for node 14, ubuntu 18 , I can install it:

npm install node-sass


问:
.NET error handling
I have been writing .NET applications and have been impressed with the error handling included in the framework.

When catching an error that has been throw by the processes or somewhere in the code I like to include the message (ex.Message, which is usually pretty general) but also the stacktrace (ex.stacktrace) which helps to trace the problem back to a specific spot.

For a simple example let's say for instance that we are recording numbers to a log in a method:

```<code>public void ExampleMethod(int number){
    try{
        int num = number
        ...open connection to file
        ...write number to file
    }
    catch(Exception ex){
        .... deal with exception (ex.message,ex.stacktrace etc...)
    }
    finally{
    ...close file connection
    }
}
</code>```

Is there any way to see the method called (in this case ExampleMethod) with the specific number that was passed that potentially crashed the method call? I believe you could log this perhaps in the catch block but I am interested essentially in catching the method call and parameters that caused the system to throw the exception.

Any ideas?

答: You could make a class that inherits Exception and add some arguments to it so you could pass the number to it.</p>

Title: .NET error handling

Body:
I have been writing .NET applications and have been impressed with the error handling included in the framework.

When catching an error that has been throw by the processes or somewhere in the code I like to include the message (ex.Message, which is usually pretty general) but also the stacktrace (ex.stacktrace) which helps to trace the problem back to a specific spot.

For a simple example let's say for instance that we are recording numbers to a log in a method:

public void ExampleMethod(int number){
    try{
        int num = number
        ...open connection to file
        ...write number to file
    }
    catch(Exception ex){
        .... deal with exception (ex.message,ex.stacktrace etc...)
    }
    finally{
    ...close file connection
    }
}

Is there any way to see the method called (in this case ExampleMethod) with the specific number that was passed that potentially crashed the method call? I believe you could log this perhaps in the catch block but I am interested essentially in catching the method call and parameters that caused the system to throw the exception.

Any ideas?


问:
Update an array of objects to store daily data, Mongoose
I have documents in a collection that contain an array of objects. Each object in the array contains a date field. I want to update this array with a new object if the date is new, if it isn't I want to update the object with the same date in the array...

Here's an example schema:

```<code>const ExampleSchema = new Schema(
  {
    name: { type: String },
    members: [{ roleId: String, roleName: String, quantity: Number, color: String }],
    dailyLogs: [{ members: Number, verifiedMembers: Number, date: String }]
  },
);
</code>```

I want to end up with an array that creates an object if the date doesn't exist, and if it exists I want to update the object with that date

```<code>name: 'name',
members: [...],
dailyLogs: [
{
  members: 4,
  verifiedMembers: 2,
  date: '02.13.2022'
},
{
  members: 8,
  verifiedMembers: 5,
  date: '02.14.2022'
},
]
</code>```

答:
You can use $addToSet for that,</p>
```<code>db.collection.update({_id:"yourId"}, {$addToSet:{members: "yourMembers", verifiedMembers: "yourVerifiedMembers", dailyLogs:{date: "yourDate"}}});
</code>```

Body:
I have documents in a collection that contain an array of objects. Each object in the array contains a date field. I want to update this array with a new object if the date is new, if it isn't I want to update the object with the same date in the array...

Here's an example schema:

const ExampleSchema = new Schema(
  {
    name: { type: String },
    members: [{ roleId: String, roleName: String, quantity: Number, color: String }],
    dailyLogs: [{ members: Number, verifiedMembers: Number, date: String }]
  },
);

I want to end up with an array that creates an object if the date doesn't exist, and if it exists I want to update the object with that date

name: 'name',
members: [...],
dailyLogs: [
{
  members: 4,
  verifiedMembers: 2,
  date: '02.13.2022'
},
{
  members: 8,
  verifiedMembers: 5,
  date: '02.14.2022'
},
]

Body:
You can use $addToSet for that,

db.collection.update({_id:"yourId"}, {$addToSet:{members: "yourMembers", verifiedMembers: "yourVerifiedMembers", dailyLogs:{date: "yourDate"}}});


问:
Default font for Windows Forms application
Every time that I create a new form in my application, it uses the "Microsoft Sans Serif, 8.25pt" font by default. I'm not changing it because I know that in this case my form should pick up whatever the default font is for the system. However, when I run my application, the font that is used is still anything but Segoe UI (my default system font in my Windows Vista OS).

Why does this happen? How do I make sure that my application looks like a normal Windows application?

答:
In .NET Core we (.NET team) updated the default font to Segoe UI and in .NET 6 we have added an API to change your default font all over your application.

In project file inside <PropertyGroup> add:

<ApplicationDefaultFont>Curlz MT, 18pt</ApplicationDefaultFont>
```
<p>This will update every control that is using the default font (everything that was not explicitly overwritten by you) in the designer and your running application.</p>
<p>You can also call <code>Application.SetDefaultFont()</code> directly in you <code>Main()</code> like in the example below:</p>
```static void Main()
{
    ApplicationConfiguration.Initialize();

    Application.SetDefaultFont(new Font(new FontFamily("Curlz MT"), 18f));

    Application.Run(new AirQualityForm());
}
```

this will update the font in your running application but not in the designer.

Body:
In .NET Core we (.NET team) updated the default font to Segoe UI and in .NET 6 we have added an API to change your default font all over your application.

In project file inside <PropertyGroup> add:

<ApplicationDefaultFont>Curlz MT, 18pt</ApplicationDefaultFont>

This will update every control that is using the default font (everything that was not explicitly overwritten by you) in the designer and your running application.

You can also call Application.SetDefaultFont() directly in you Main() like in the example below:

static void Main()
{
    ApplicationConfiguration.Initialize();

    Application.SetDefaultFont(new Font(new FontFamily("Curlz MT"), 18f));

    Application.Run(new AirQualityForm());
}

this will update the font in your running application but not in the designer.


问:
Flexbox image and text size are not same
I am trying to make flexboxes with the same height and width by using:

```<code>flex: 1;
</code>```

But it is not working as I thought, image box becomes bigger than text box.

Here I made little example:
https://jsfiddle.net/p3uowcdg/9/

答:
You should use grid layout:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.box-image {
  width: 100%;
}

.box-text {
  width: 100%;
}
```

Result

Body:
I am trying to make flexboxes with the same height and width by using:

flex: 1;

But it is not working as I thought, image box becomes bigger than text box.

Here I made little example:
https://jsfiddle.net/p3uowcdg/9/

Body:
You should use grid layout:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.box-image {
  width: 100%;
}

.box-text {
  width: 100%;
}

Result


问:
Predict next numbers
I would like to write script to predict the next numbers in a lottery. I downloaded a dataset and prepared it for using it with the script as shown below.

```<code>[[1, 3, 4, 20, 21. 12],
[44, 33, 22, 11, 10, 3] ...]
</code>```

I also did a script which is using keras to predicate numbers but now I got an error
'ValueError: Error when checking target: expected dense_1 to have shape (6,) but got array with shape (1,)'.
When I change Dense(6) to Dense(1) I get another error on line

trainPredict = scaler.inverse_transform(trainPredict)

ValueError: non-broadcastable output operand with shape (4440,1) doesn't match the broadcast shape (4440,6)'.

How I can resolve this problems to get 6 numbers? Is there a way to delete create_data_set? I found it but I don't even understand that. Maybe someone has an example with that type of problem where scripts have to predict some numbers

```<code>def create_data_set(_data_set, _look_back=1):
    data_x, data_y = [], []
    for i in range(len(_data_set) - _look_back - 1):
        a = _data_set[i:(i + _look_back), 0]
        data_x.append(a)
        data_y.append(_data_set[i + _look_back, 0])
    return np.array(data_x), np.array(data_y)

pathToFile = './dl.txt'
dataset = pd.read_csv(pathToFile, sep=' ', header=None, usecols=(1,2), names=['date', 'numbers'])
dataset = dataset['numbers'].values
parsedDataset = []
for i in dataset:
    parsedDataset.append(i.split(','))
dataset = parsedDataset
dataset = np.array(dataset)
dataset.astype('float64')

scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
train, test = train_test_split(dataset, test_size=0.30, random_state=40)
train_x, train_y = create_data_set(train, 1)
test_x, test_y = create_data_set(test, 1)
print(train_x.shape[0])
train_x = np.reshape(train_x, (train_x.shape[0],1, train_x.shape[1]))
test_x = np.reshape(test_x, (test_x.shape[0], 1, test_x.shape[1]))

model = Sequential()
model.add(LSTM(256, input_shape=(train_x.shape[1], train_x.shape[2]),return_sequences=True))
model.add(LSTM(128))
model.add(Dense(6))
model.compile(loss='mse', optimizer='adam',metrics=['acc'])
model.fit(train_x, train_y, epochs=3, batch_size=1, verbose=0)
trainPredict = model.predict(train_x)
testPredict = model.predict(test_x)

trainPredict = scaler.inverse_transform(trainPredict)
train_y = scaler.inverse_transform([train_y])
testPredict = scaler.inverse_transform(testPredict)
test_y = scaler.inverse_transform([test_y])
for i in range(testPredict.shape[1]):
        print("%.1f"%(testPredict[0,i]), end=' ')
print('\n',end="")
</code>```

答:
First off this is an educational question stop looking at it as someone is asking you for the winning numbers.
simply put how do you write an LSTM to do prediction on multiple features.

The first problem, you are trying to predict six features but only select two columns "usecols=(1,2)"

The next problem, "def create_data_set" is made to be use with one column datset.

Title: Predict next numbers

Body:
I would like to write script to predict the next numbers in a lottery. I downloaded a dataset and prepared it for using it with the script as shown below.

[[1, 3, 4, 20, 21. 12],
[44, 33, 22, 11, 10, 3] ...]

I also did a script which is using keras to predicate numbers but now I got an error
'ValueError: Error when checking target: expected dense_1 to have shape (6,) but got array with shape (1,)'.
When I change Dense(6) to Dense(1) I get another error on line

trainPredict = scaler.inverse_transform(trainPredict)

ValueError: non-broadcastable output operand with shape (4440,1) doesn't match the broadcast shape (4440,6)'.

How I can resolve this problems to get 6 numbers? Is there a way to delete create_data_set? I found it but I don't even understand that. Maybe someone has an example with that type of problem where scripts have to predict some numbers

def create_data_set(_data_set, _look_back=1):
    data_x, data_y = [], []
    for i in range(len(_data_set) - _look_back - 1):
        a = _data_set[i:(i + _look_back), 0]
        data_x.append(a)
        data_y.append(_data_set[i + _look_back, 0])
    return np.array(data_x), np.array(data_y)

pathToFile = './dl.txt'
dataset = pd.read_csv(pathToFile, sep=' ', header=None, usecols=(1,2), names=['date', 'numbers'])
dataset = dataset['numbers'].values
parsedDataset = []
for i in dataset:
    parsedDataset.append(i.split(','))
dataset = parsedDataset
dataset = np.array(dataset)
dataset.astype('float64')

scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
train, test = train_test_split(dataset, test_size=0.30, random_state=40)
train_x, train_y = create_data_set(train, 1)
test_x, test_y = create_data_set(test, 1)
print(train_x.shape[0])
train_x = np.reshape(train_x, (train_x.shape[0],1, train_x.shape[1]))
test_x = np.reshape(test_x, (test_x.shape[0], 1, test_x.shape[1]))

model = Sequential()
model.add(LSTM(256, input_shape=(train_x.shape[1], train_x.shape[2]),return_sequences=True))
model.add(LSTM(128))
model.add(Dense(6))
model.compile(loss='mse', optimizer='adam',metrics=['acc'])
model.fit(train_x, train_y, epochs=3, batch_size=1, verbose=0)
trainPredict = model.predict(train_x)
testPredict = model.predict(test_x)

trainPredict = scaler.inverse_transform(trainPredict)
train_y = scaler.inverse_transform([train_y])
testPredict = scaler.inverse_transform(testPredict)
test_y = scaler.inverse_transform([test_y])
for i in range(testPredict.shape[1]):
        print("%.1f"%(testPredict[0,i]), end=' ')
print('\n',end="")


问:
How do I change the order of items on resize?
Is there a way to force the third element to always be directly below the first element when the screen size is 500px or less?

.user {
  width: 100px;
  height: 100px;
  padding: 4px;
}

@media screen and (max-width: 500px) {
    #block >div:nth-child(3) {
      display:inline-block;
      position: absolute;
      top:120px;
      left: 120px; /* errorful line as the elements are not sync */
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main">
  <div class="user">Element One</div>
  <div class="user">Element two</div>
  <div class="user">Element three</div>
</div></code>```

答:
The order of the wrapped
 elements can be changed by assigning flex to the display style of the
 element whose id attribute is main. To change the order of the items, change the order style of the items within the media query.

#main {
  /* The following styles have been applied to the outer container. */
  display: flex;
  flex-direction: column;
}
.user {
  width: 100px;
  height: 100px;
  padding: 4px;
  border: 1px solid black;
}
#user1 {
  color: red;
}
#user2 {
  color: blue;
}
#user3 {
  color: green;
}

/* I set max-width to 768px to test app on mobile screen size. */
@media screen and (max-width: 768px) {
    /* Change the order style to change the order of the items. */
    #user1 {
      order: 1;
    }
    #user2 {
      order: 3;
    }
    #user3 {
      order: 2;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main">
  <div id="user1" class="user">One</div>
  <div id="user2" class="user">Two</div>
  <div id="user3" class="user">Three</div>
</div></code>```

Body:
Is there a way to force the third element to always be directly below the first element when the screen size is 500px or less?

.user {
  width: 100px;
  height: 100px;
  padding: 4px;
}

@media screen and (max-width: 500px) {
    #block >div:nth-child(3) {
      display:inline-block;
      position: absolute;
      top:120px;
      left: 120px; /* errorful line as the elements are not sync */
    }
}

Element One

Element two

Element three

Body:
The order of the wrapped <div> elements can be changed by assigning flex to the display style of the <div> element whose id attribute is main. To change the order of the items, change the order style of the items within the media query.

#main {
  /* The following styles have been applied to the outer container. */
  display: flex;
  flex-direction: column;
}
.user {
  width: 100px;
  height: 100px;
  padding: 4px;
  border: 1px solid black;
}
#user1 {
  color: red;
}
#user2 {
  color: blue;
}
#user3 {
  color: green;
}

/* I set max-width to 768px to test app on mobile screen size. */
@media screen and (max-width: 768px) {
    /* Change the order style to change the order of the items. */
    #user1 {
      order: 1;
    }
    #user2 {
      order: 3;
    }
    #user3 {
      order: 2;
    }
}

<div id="main">
  <div id="user1" class="user">One</div>
  <div id="user2" class="user">Two</div>
  <div id="user3" class="user">Three</div>
</div>


答:
You missed a comma after 'click'.  code -</p>
```<code>btn.addEventListener('click', () => {
    overlay.style.display = 'grid';
});
</code>```

Title: why is javascript script not working in html code

Body:
im making a website and im trying to put some javascript but it gives me an error can anyone tell me why?

HTML code

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <link rel="stylesheet" href="css/main.css">

Searching now...

                MyWebsite

This is My Website.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa ea vel eius voluptas perspiciatis accusantium ut sed veritatis et porro.

                <form action="">

                        Enter your city:
                        <input type="text" name="city" id="city">

Example: New York city

                    <input type="button" value="Enter" id="cta-btn">
                </form>

Lorem, ipsum.

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Aliquid dolorem in animi. Fugit ab iusto commodi corporis voluptatum enim, illum nostrum beatae facilis voluptates et facere ipsum inventore nemo repellat rerum itaque obcaecati magni fugiat molestiae? Illo, quod neque cum nam porro necessitatibus qui iure vel nesciunt a veritatis placeat magnam exercitationem veniam, nemo adipisci est quaerat. Placeat repellendus aperiam consectetur voluptas saepe quae, fugiat dolores tempora nobis, maxime corporis nulla non, suscipit voluptate! Cumque.

error

        let btn = document.getElementById('ctn-btn')
        let overlay = document.getElementById('overlay')

        btn.addEventListener('click' () = {  /*this is not working*/
            overlay.style.display = 'grid'
        })

in the video it was also ('click' () => { but that gave me an error so i deleted the >
this is my first time trying javascript in a website

it gives me an error under the . in overlay.style did i forget to add something in the head tag?

anyone know the problem?

Body:
You missed a comma after 'click'.  code -

btn.addEventListener('click', () => {
    overlay.style.display = 'grid';
});


问:
How to encrypt a password and save it in MySQL database.
Now I am just saving the password as it is

```<code>protected void Save_Click(object sender, EventArgs e)
    {

        string userName = Label13.Text;
        DateTime now = DateTime.Now;
        MySqlConnection connectionString = new MySqlConnection("Server=127.0.0.1;Database=surelyknown;Uid=root");
        connectionString.Open();
        MySqlDataAdapter adapter = new MySqlDataAdapter();
        MySqlCommand command = new MySqlCommand();
adapter.InsertCommand = new MySqlCommand("INSERT INTO tbl_user (FirstName,LastName,Email,U_Password,CompanyName,UserPermission,PhoneNumber,Created,Modified,Active,CreatedBy,tbl_organisation_OrganisationID) VALUES(@FirstName,@LastName,@Email,@U_Password,@CompanyName,@UserPermission,@PhoneNumber,@Created,@Modified,@Active,@CreatedBy,@tbl_organisation_OrganisationID)", connectionString);
    adapter.InsertCommand.Parameters.Add("@FirstName", MySqlDbType.VarChar).Value = FirstName.Text;
            adapter.InsertCommand.Parameters.Add("@LastName", MySqlDbType.VarChar).Value = Surname.Text;
            adapter.InsertCommand.Parameters.Add("@Email", MySqlDbType.VarChar).Value = Email.Text;
            adapter.InsertCommand.Parameters.Add("@U_Password", MySqlDbType.VarChar).Value = Password.Text;
            adapter.InsertCommand.Parameters.Add("@CompanyName", MySqlDbType.VarChar).Value = Convert.ToString(nID);
</code>```

and when the user login to the website how can the encrypted password used to do authentication. i want to do the decryption in the server side itself. please help

答:
Basically, hash + salt your password, save the hash into the database, do not save the clear-text password.

When the user logs into your system, hash the same password from him with the salt, compare that hash with the hash saved to your database, if they match, then your user is authenticated.

Hashing your password hides the real password from any successful attempts to hack into your password.

Salting your password with another arbitrary value saves you a margin from dictionary based brute force attacks.

See OWASP for Salt + Hashing + High number of iterations technique
This is in Java, but i believe the theory covered is portable across any languages / implementations.

Body:
Now I am just saving the password as it is

protected void Save_Click(object sender, EventArgs e)
    {

        string userName = Label13.Text;
        DateTime now = DateTime.Now;
        MySqlConnection connectionString = new MySqlConnection("Server=127.0.0.1;Database=surelyknown;Uid=root");
        connectionString.Open();
        MySqlDataAdapter adapter = new MySqlDataAdapter();
        MySqlCommand command = new MySqlCommand();
adapter.InsertCommand = new MySqlCommand("INSERT INTO tbl_user (FirstName,LastName,Email,U_Password,CompanyName,UserPermission,PhoneNumber,Created,Modified,Active,CreatedBy,tbl_organisation_OrganisationID) VALUES(@FirstName,@LastName,@Email,@U_Password,@CompanyName,@UserPermission,@PhoneNumber,@Created,@Modified,@Active,@CreatedBy,@tbl_organisation_OrganisationID)", connectionString);
    adapter.InsertCommand.Parameters.Add("@FirstName", MySqlDbType.VarChar).Value = FirstName.Text;
            adapter.InsertCommand.Parameters.Add("@LastName", MySqlDbType.VarChar).Value = Surname.Text;
            adapter.InsertCommand.Parameters.Add("@Email", MySqlDbType.VarChar).Value = Email.Text;
            adapter.InsertCommand.Parameters.Add("@U_Password", MySqlDbType.VarChar).Value = Password.Text;
            adapter.InsertCommand.Parameters.Add("@CompanyName", MySqlDbType.VarChar).Value = Convert.ToString(nID);

and when the user login to the website how can the encrypted password used to do authentication. i want to do the decryption in the server side itself. please help


答:
You have to use => otherwise it will give you a syntax error. I think the comma occurring the problem.
After passing the event type you have to use a comma ("click",) then you can pass an arrow ()=>{} or simple function function(){} with it. So, when the button is clicked the function will be triggered.

I hope, this will help you.


问:
PyCharm Not Always Plotting In New Figures
I have the latest version of PyCharm installed (2020.2.2 Pro). I have PyCharm configured to plot into the SciView.

When I run the following code 5 times it generates a new plot only twice. All other times it overwrites the previous figure.

```<code>import matplotlib.pyplot as plt
import numpy as np

plt.figure()
plt.plot(np.sin(np.linspace(0,5,100)))
plt.show()
</code>```

This behavior is pretty obnoxious when one wants to compare the results of multiple plots.

My PyCharm is also configured to start a new python instance on every run of the file. I also see the same behavior if I omit the plt.figure() line.

Additionally, the new plots don't appear in any repeatable way. Like I run this code 3 times I only get one plot from the first run, but then on the 4th run I get a second plot.

If I disable plotting in SciView through Settings>Python Scientific>Show plots in tool window. I generate a new plot every time I run the code.

The plot which is replaced when I rerun the code is randomly selected as well. If I have say 4 plots and one of them gets replaced it is usually the one with the bottom thumbnail, but sometimes another random one in the list is replaced instead.

If I set Settings>Build, Execution, Deployment>Console>Use existing console for "Run with Python Console" I get a new figure each time. This is fine, except I require a fresh console for every run as I'm often modifying libraries that are imported by the code that generates the plots. If I don't get a fresh console the the imports are ignored and the existing version of the library stays in the interpreters memory. I suppose I can work around this by setting %autoreload in iPython, but it's a bit of a hack...

If you're having this issue try setting Use existing console for "Run with Python Console" and putting the following somewhere in the python file you're running

```<code>from IPython import get_ipython
ipython = get_ipython()
if ipython is not None:
    ipython.magic("%load_ext autoreload")
    ipython.magic("%autoreload")
</code>```

答:
I has same problem.  I was plotting two plots in PyCharm and sometimes both would plot and other times only 1.  It was always the first plot of the two that was hit or miss for me.

I am using Settings>Python Scientific>Show plots in tool window and Settings>Build, Execution, Deployment>Console>Use existing console for "Run with Python Console

adding this code seemed to have fixed for me.  I am on a Mac.

```<code>import matplotlib
matplotlib.use('wxAgg')
</code>```

Body:
I have the latest version of PyCharm installed (2020.2.2 Pro). I have PyCharm configured to plot into the SciView.

When I run the following code 5 times it generates a new plot only twice. All other times it overwrites the previous figure.

import matplotlib.pyplot as plt
import numpy as np

plt.figure()
plt.plot(np.sin(np.linspace(0,5,100)))
plt.show()

This behavior is pretty obnoxious when one wants to compare the results of multiple plots.

My PyCharm is also configured to start a new python instance on every run of the file. I also see the same behavior if I omit the plt.figure() line.

Additionally, the new plots don't appear in any repeatable way. Like I run this code 3 times I only get one plot from the first run, but then on the 4th run I get a second plot.

If I disable plotting in SciView through Settings>Python Scientific>Show plots in tool window. I generate a new plot every time I run the code.

The plot which is replaced when I rerun the code is randomly selected as well. If I have say 4 plots and one of them gets replaced it is usually the one with the bottom thumbnail, but sometimes another random one in the list is replaced instead.

If I set Settings>Build, Execution, Deployment>Console>Use existing console for "Run with Python Console" I get a new figure each time. This is fine, except I require a fresh console for every run as I'm often modifying libraries that are imported by the code that generates the plots. If I don't get a fresh console the the imports are ignored and the existing version of the library stays in the interpreters memory. I suppose I can work around this by setting %autoreload in iPython, but it's a bit of a hack...

If you're having this issue try setting Use existing console for "Run with Python Console" and putting the following somewhere in the python file you're running

from IPython import get_ipython
ipython = get_ipython()
if ipython is not None:
    ipython.magic("%load_ext autoreload")
    ipython.magic("%autoreload")

Body:
I has same problem.  I was plotting two plots in PyCharm and sometimes both would plot and other times only 1.  It was always the first plot of the two that was hit or miss for me.

I am using Settings>Python Scientific>Show plots in tool window and Settings>Build, Execution, Deployment>Console>Use existing console for "Run with Python Console

adding this code seemed to have fixed for me.  I am on a Mac.

import matplotlib
matplotlib.use('wxAgg')


问:
Macro definition conflict
I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.

I have two header files

```<code>test1.h
#define TEST 123
test2.h
#define TEST 456
</code>```

Now I have a program included  both these two headers, but I want my actually TEST to be 123.
How can I avoid defining TEST as 456?

You might think I'm crazy not to simply change the macro, but the situation is: I have a third-party decoder, which has this macro (defined in test1.h), and there's another WINAPI macro (defined in test2.h). Both of these files are controlled by others; I should not change either of them.
I don't need the test2.h at all, but I guess it's implicitly included by some other WINAPI header.

So, could anyone please tell me how to work around this issue? To overwrite the WINAPI macro with my third-party macro? Or how to nullify the definition from the WINAPI header in my own code? Is there a way to specify which header I don't want to include.

答:
```<code>#ifdef TEST
#undef TEST
#define TEST 123
#endif
</code>```

Title: Macro definition conflict

Body:
I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.

I have two header files

test1.h
#define TEST 123
test2.h
#define TEST 456

Now I have a program included  both these two headers, but I want my actually TEST to be 123.
How can I avoid defining TEST as 456?

You might think I'm crazy not to simply change the macro, but the situation is: I have a third-party decoder, which has this macro (defined in test1.h), and there's another WINAPI macro (defined in test2.h). Both of these files are controlled by others; I should not change either of them.
I don't need the test2.h at all, but I guess it's implicitly included by some other WINAPI header.

So, could anyone please tell me how to work around this issue? To overwrite the WINAPI macro with my third-party macro? Or how to nullify the definition from the WINAPI header in my own code? Is there a way to specify which header I don't want to include.


问:
Can't install 'node-sass' on Ubuntu 20
I use webpack 4, sass, pug and bemto. Module on windows  worked normal, but on Ubuntu:

```<code>npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! node-sass@4.14.1 postinstall: `node scripts/build.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the node-sass@4.14.1 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

I tried enter command:

```<code>sudo npm install -g --unsafe-perm node-sass
</code>```

>

```<code>(node:8310) [DEP0139] DeprecationWarning: Calling process.umask() with no arguments is prone to race conditions and is a potential security vulnerability.
(Use `node --trace-deprecation ...` to show where the warning was created)
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/usr/local/bin/node-sass -> /usr/local/lib/node_modules/node-sass/bin/node-sass
npm WARN lifecycle The node binary used for scripts is /snap/bin/node but npm is using /snap/node/2725/bin/node itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.

> node-sass@4.14.1 install /usr/local/lib/node_modules/node-sass
> node scripts/install.js

Cached binary found at /root/.npm/node-sass/4.14.1/linux-x64-83_binding.node

> node-sass@4.14.1 postinstall /usr/local/lib/node_modules/node-sass
> node scripts/build.js

Binary found at /usr/local/lib/node_modules/node-sass/vendor/linux-x64-83/binding.node
Testing binary
/snap/node/2725/bin/node: symbol lookup error: /usr/local/lib/node_modules/node-sass/vendor/linux-x64-83/binding.node: undefined symbol: _ZN2v816FunctionTemplate3NewEPNS_7IsolateEPFvRKNS_20FunctionCallbackInfoINS_5ValueEEEENS_5LocalIS4_EENSA_INS_9SignatureEEEiNS_19ConstructorBehaviorENS_14SideEffectTypeEPKNS_9CFunctionE
npm WARN You are using a pre-release version of node and things may not work as expected

npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! node-sass@4.14.1 postinstall: `node scripts/build.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the node-sass@4.14.1 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

UPD:

I tried:
npm uninstall node-sass
After:
npm install node-sass
Did not help.

I tried:
npm install node-gyp global, save, savedev

```<code>ERROR in ./src/sсss/critical.scss (./node_modules/css-loader??ref--5-1!./node_modules/sass-loader/lib/loader.js??ref--5-2!./src/sсss/critical.scss)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
Error: Cannot find module 'node-sass'
Require stack:
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/sass-loader/lib/loader.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/loadLoader.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/LoaderRunner.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/webpack/lib/NormalModule.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/webpack/lib/NormalModuleFactory.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/webpack/lib/Compiler.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/webpack/lib/webpack.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/webpack-dev-server/bin/webpack-dev-server.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1020:15)
    at Function.Module._load (internal/modules/cjs/loader.js:890:27)
    at Module.require (internal/modules/cjs/loader.js:1080:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/home/gorevanova/Documents/WebStorm/webpack-static/node_modules/sass-loader/lib/loader.js:3:14)
    at Module._compile (internal/modules/cjs/loader.js:1176:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1196:10)
    at Module.load (internal/modules/cjs/loader.js:1040:32)
    at Function.Module._load (internal/modules/cjs/loader.js:929:14)
    at Module.require (internal/modules/cjs/loader.js:1080:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at loadLoader (/home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/loadLoader.js:18:17)
    at iteratePitchingLoaders (/home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
    at iteratePitchingLoaders (/home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/LoaderRunner.js:165:10)
    at /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/LoaderRunner.js:176:18
    at loadLoader (/home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/loadLoader.js:47:3)
</code>```

But problem don't leave me.

答:
Please check your node version before install it, node-sass has striction about node versions, shown as below:

refer to https://github.com/sass/node-sass

Title: Can't install 'node-sass' on Ubuntu 20

Body:
I use webpack 4, sass, pug and bemto. Module on windows  worked normal, but on Ubuntu:

npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! node-sass@4.14.1 postinstall: `node scripts/build.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the node-sass@4.14.1 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I tried enter command:

sudo npm install -g --unsafe-perm node-sass

>

(node:8310) [DEP0139] DeprecationWarning: Calling process.umask() with no arguments is prone to race conditions and is a potential security vulnerability.
(Use `node --trace-deprecation ...` to show where the warning was created)
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/usr/local/bin/node-sass -> /usr/local/lib/node_modules/node-sass/bin/node-sass
npm WARN lifecycle The node binary used for scripts is /snap/bin/node but npm is using /snap/node/2725/bin/node itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.

> node-sass@4.14.1 install /usr/local/lib/node_modules/node-sass
> node scripts/install.js

Cached binary found at /root/.npm/node-sass/4.14.1/linux-x64-83_binding.node

> node-sass@4.14.1 postinstall /usr/local/lib/node_modules/node-sass
> node scripts/build.js

Binary found at /usr/local/lib/node_modules/node-sass/vendor/linux-x64-83/binding.node
Testing binary
/snap/node/2725/bin/node: symbol lookup error: /usr/local/lib/node_modules/node-sass/vendor/linux-x64-83/binding.node: undefined symbol: _ZN2v816FunctionTemplate3NewEPNS_7IsolateEPFvRKNS_20FunctionCallbackInfoINS_5ValueEEEENS_5LocalIS4_EENSA_INS_9SignatureEEEiNS_19ConstructorBehaviorENS_14SideEffectTypeEPKNS_9CFunctionE
npm WARN You are using a pre-release version of node and things may not work as expected

npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! node-sass@4.14.1 postinstall: `node scripts/build.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the node-sass@4.14.1 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

UPD:

I tried:
npm uninstall node-sass
After:
npm install node-sass
Did not help.

I tried:
npm install node-gyp global, save, savedev

ERROR in ./src/sсss/critical.scss (./node_modules/css-loader??ref--5-1!./node_modules/sass-loader/lib/loader.js??ref--5-2!./src/sсss/critical.scss)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
Error: Cannot find module 'node-sass'
Require stack:
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/sass-loader/lib/loader.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/loadLoader.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/LoaderRunner.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/webpack/lib/NormalModule.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/webpack/lib/NormalModuleFactory.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/webpack/lib/Compiler.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/webpack/lib/webpack.js
- /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/webpack-dev-server/bin/webpack-dev-server.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1020:15)
    at Function.Module._load (internal/modules/cjs/loader.js:890:27)
    at Module.require (internal/modules/cjs/loader.js:1080:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/home/gorevanova/Documents/WebStorm/webpack-static/node_modules/sass-loader/lib/loader.js:3:14)
    at Module._compile (internal/modules/cjs/loader.js:1176:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1196:10)
    at Module.load (internal/modules/cjs/loader.js:1040:32)
    at Function.Module._load (internal/modules/cjs/loader.js:929:14)
    at Module.require (internal/modules/cjs/loader.js:1080:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at loadLoader (/home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/loadLoader.js:18:17)
    at iteratePitchingLoaders (/home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
    at iteratePitchingLoaders (/home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/LoaderRunner.js:165:10)
    at /home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/LoaderRunner.js:176:18
    at loadLoader (/home/gorevanova/Documents/WebStorm/webpack-static/node_modules/loader-runner/lib/loadLoader.js:47:3)

But problem don't leave me.


问:
Null check operator used on a null even if the ? is already added
I have 2 newbie questions here.

1st question: Why it won't go through the statement print('it will NOT go here.');

I got the error Null check operator used on a null value. But I already added ? to say that it can be null in the Price? class.

2nd question: Why this statement if (_price != null) shows The operand can't be null, so the condition is always true. But I know that it can be null since it is possible that it is not existing. Please help me understand what's going on. Thanks!

This is my code:

```<code>DocumentReference<Map<String, dynamic>> docRefPrice =
db.collection('dataPath').doc('ThisIsNotExisting');
print('it will go here - 1');
final DocumentSnapshot<Map<String, dynamic>> documentSnapshotPrice = await docRefPrice.get();
print('it will go here - 2');
Price? _price = Price.fromFirestore(documentSnapshotPrice);
print('it will NOT go here.');
if (_price != null) {
  print('_price is not null');
}
else { print('_price is null');
  return false;
}
</code>```

Edit add fromFirestore:

```<code>  factory Price.fromFirestore(DocumentSnapshot<Map<String, dynamic>> doc) {
    Map data = doc.data()!;

    return Price(
      price1: data['text1'],
      price2: data['text2'],
    );
  }
</code>```

This is the link that I tried to understand: https://dart.dev/codelabs/dart-cheatsheet

答:
Regarding your first question, the function fromFirestore is what's causing the error, add the code for it to your question.

the second question, _price won't be null cause Price.fromFirestore(documentSnapshotPrice); is a constructor so it will return a Price object and never null.

Edit

Most probably this line is the reason for the error: Map data = doc.data()!; remove the ! and make the Map nullable and handle this case

I will need the Price class code to write the code but here is the idea

```<code>factory Price.fromFirestore(DocumentSnapshot<Map<String, dynamic>> doc) {
Map? data = doc.data();

return Price(
  price1: data == null ? null : data['text1'], // price1 must accept null in this case
  price2: data == null ? null : data['text2'], // price2 must accept null in this case
);
}
</code>```

Body:
I have 2 newbie questions here.

1st question: Why it won't go through the statement print('it will NOT go here.');

I got the error Null check operator used on a null value. But I already added ? to say that it can be null in the Price? class.

2nd question: Why this statement if (_price != null) shows The operand can't be null, so the condition is always true. But I know that it can be null since it is possible that it is not existing. Please help me understand what's going on. Thanks!

This is my code:

DocumentReference<Map<String, dynamic>> docRefPrice =
db.collection('dataPath').doc('ThisIsNotExisting');
print('it will go here - 1');
final DocumentSnapshot<Map<String, dynamic>> documentSnapshotPrice = await docRefPrice.get();
print('it will go here - 2');
Price? _price = Price.fromFirestore(documentSnapshotPrice);
print('it will NOT go here.');
if (_price != null) {
  print('_price is not null');
}
else { print('_price is null');
  return false;
}

Edit add fromFirestore:

  factory Price.fromFirestore(DocumentSnapshot<Map<String, dynamic>> doc) {
    Map data = doc.data()!;

    return Price(
      price1: data['text1'],
      price2: data['text2'],
    );
  }

This is the link that I tried to understand: https://dart.dev/codelabs/dart-cheatsheet

Body:
Regarding your first question, the function fromFirestore is what's causing the error, add the code for it to your question.

the second question, _price won't be null cause Price.fromFirestore(documentSnapshotPrice); is a constructor so it will return a Price object and never null.

Edit

Most probably this line is the reason for the error: Map data = doc.data()!; remove the ! and make the Map nullable and handle this case

I will need the Price class code to write the code but here is the idea

factory Price.fromFirestore(DocumentSnapshot<Map<String, dynamic>> doc) {
Map? data = doc.data();

return Price(
  price1: data == null ? null : data['text1'], // price1 must accept null in this case
  price2: data == null ? null : data['text2'], // price2 must accept null in this case
);
}


问:
How to release a new version on GitHub?
We weren’t able to create the release for you. Please help me correct the errors below.

Can anyone help me creating releases on GitHub?

答:
we have to "Create a tag" first before we can publish.
 type tag name and hit create new tag button on the dropdown to create one

It feels like preety bad ui/ux from github's part, the error message says "invalid" tag, and what it actually means is we need to type and hit "create new tag" and then select the tag to be able to use it. Jesus!

Title: How to release a new version on GitHub?


问:
Start Cypress tests from DevOps
I'm trying to set up Cypress to run automated tests directly from DevOps using a pipeline. It looks like it's already partially communicating to me, but I don't know why I'm getting the following error there:

I call . \\phasp13jm29\UICypress\cypress open:

There is such a structure in this directory.

The package.json file contains:

Can anyone advise?

答:
It appears to me that you are calling cypress in tfs agent (test runner) from a remote machine (\\phasp13jm29) which potentially a mis-usage. In a nutshell, cypress is nodejs package. By that said, you need to install nodejs and cypress in tfs agent. You may want to check out cypress system requirements for further details.

To fulfill the pipeline, you also need to make sure cypress test scripts are available in tfs agent (by copying them over network or git checkout or your own way).

The last step is to kick of the test execution by calling npx cypress run with appropriate flags and/or configuration or npm run test (from your package.json).

Just my 2 cents and I hope it's somewhat helpful for you.

Title: Start Cypress tests from DevOps


答:
Use subquery for retrieving user name wise total invested and total expense and then use INNER JOIN between user table and amount table and also use LEFT JOIN for invested and expense related result with this for getting desired result. Use aggregate function like SUM() in inside subquery because using group by in given query. If only single row is existed in both invested and expense table then no need to use group by. At this case aggregate function will not use.</p>
```<code>select t1.UserID
     , t1.Username
     , t2.TotalAmountResetDate
     , t2.TotalAmount
     , t3.TotalInvested
     , t4.TotalExpenses
     , t2.TotalAmount + COALESCE(t3.TotalInvested, 0) - COALESCE(t4.TotalExpenses, 0) TotalBalance
from userdetails1.UserTable t1
inner join userdetails2.AmountTable t2
        on t1.UserID = t2.UserID
left join (select Username, SUM(TotalInvested) TotalInvested
           from userdetails2.TotalInvestmentsTable
           group by Username) t3
       on t1.Username = t3.Username
left join (select Username, SUM(TotalExpenses) TotalExpenses
           from userdetails2.TotalExpensesTable
           group by Username) t4
       on t1.Username = t4.Username

</code>```

Title: How to concatenate more sql queries to get one table?

Body:
I have 4 tables that I have used following queries to get data,

query1 : select * from userdetails1.UserTable;

Result1:
UserID  Username    Status
1         John      Active
2         Micheal   Active
3         Ann       Active
4         Shasha    Resigned
5         mike      Resigned

query2 : select * from userdetails2.AmountTable;

result2:
UserId  TotalAmount TotalAmountResetDate
1          -12         1/31/2022
2          345         1/31/2022
3          213         1/31/2022
4          0           1/31/2022
5          0           1/31/2022

query3:
select Username,TotalInvested from userdetails2.TotalInvestmentsTable group by Username;

result3:

Username    Totalnvested
John         45000
Micheal      45000
Ann          45000

query4:
select Username,TotalExpenses from userdetails2.TotalExpensesTable group by Username;

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290

Now I need to get another table by combining all these queries as follows. How should I get that by concatenating all these queries?

UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested    TotalExpenses   TotalBalance
1        John              1/31/2022               -12       45000            2543          42445
2        Micheal           1/31/2022               345       45000            2345          43000
3        Ann               1/31/2022               213       45000            3290          41923
4        Shasha            1/31/2022               0         0                 0            0
5        mike              1/31/2022               0         0                 0            0

Here TotalBalance column need to get from TotalBalance=TotalAmount+Totalnvested -TotalExpenses.Is this possible to get using one query?

Update:

If the total expenses and total investments are more than one value we need to get sum of each user to the total investements. Then how we can get that one?

Example:

Username    Totalnvested
    John         45000
    Micheal      45000
    Ann          45000
    John         21000
    Micheal       5000

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290
Ann            2345
John            5478

Body:
Use subquery for retrieving user name wise total invested and total expense and then use INNER JOIN between user table and amount table and also use LEFT JOIN for invested and expense related result with this for getting desired result. Use aggregate function like SUM() in inside subquery because using group by in given query. If only single row is existed in both invested and expense table then no need to use group by. At this case aggregate function will not use.

select t1.UserID
     , t1.Username
     , t2.TotalAmountResetDate
     , t2.TotalAmount
     , t3.TotalInvested
     , t4.TotalExpenses
     , t2.TotalAmount + COALESCE(t3.TotalInvested, 0) - COALESCE(t4.TotalExpenses, 0) TotalBalance
from userdetails1.UserTable t1
inner join userdetails2.AmountTable t2
        on t1.UserID = t2.UserID
left join (select Username, SUM(TotalInvested) TotalInvested
           from userdetails2.TotalInvestmentsTable
           group by Username) t3
       on t1.Username = t3.Username
left join (select Username, SUM(TotalExpenses) TotalExpenses
           from userdetails2.TotalExpensesTable
           group by Username) t4
       on t1.Username = t4.Username


问:
Using jQuery to Swap Out Body Background Image on click and randomize on load
I've got a body background image that is being "placed" by a plugin called ezBigResize that basically allows the image to scale with the browser window.

The designer wants to image though to be able to be swapped out by a series of thumbnails on the page, along with that image being randomized on page load from that series of images.

Initially before those two additions, I just had it setup like this:

```<code>$(document).ready(function() {$("body").ezBgResize({img : "/lib/img/bkgr/mainBG.jpg"});});
</code>```

Then this is the code now (in a jQuery Tools scrollable)

```<code><div id="bkgrSelector">
    <div class="scrollNav">
        <a class="prev browse left"></a>
    </div>
    <div class="scrollable">
        <div class="items">
            <img src="/lib/img/bkgr/selections/main-bg.jpg" width="77" height="44" />
            <img src="/lib/img/bkgr/selections/main-bg02.jpg" width="77" height="44" />
            <img src="/lib/img/bkgr/selections/main-bg03.jpg" width="77" height="44" />
        </div>
    </div>
    <div class="scrollNav">
        <a class="next browse right"></a>
    </div>
</div>
</code>```

I'm a little over my head though to allow these to both randomize on page load and to swap out the image via the value in the href.

I tried something like this, but it didn't work and is obviously inclomplete. Plus, it doesn't address the randomization at all.

```<code>$('#bkgrSelector .items img[href]').click(function()
{
            $("body").css("background-image", "url()");
        });
</code>```

Any ideas, help, etc. would be appreciated.

答:
Are those  pointing at the full-sized image file? I absolutely LOATHE sites that use full-size images and shrink them to thumbnail size. The load times are attrocious.

If they're actually thumbnail-sized images, you won't be able to use that url directly as your background url, as you'd just be stretching a small thumbnail-sized image to cover the window and get a hideous pixelized mess.

If the page is being dynamically generated, you'd want to create a JS array that contains the URLs of the full-sized image urls, so that when a thumbnail is clicked, you can get the fullsize url from that array. Or at least have a standardized naming convention so a simple string manipulation lets you turn the thumbnail url into a fullsize image url.

Once you've got that array, it's a simple matter to randomize a choice from it:

```<code>var imgs = ['/url/for/img1.jpg', '/url/for/img2.jpg', etc....];

$(document).ready(function() {
   randomUrl = imgs[Math.round(Math.random() * (imgs.length - 1)) + 1];
   $("body").css("background-image", 'url(' + randomURL + ')');
});
</code>```

Body:
I've got a body background image that is being "placed" by a plugin called ezBigResize that basically allows the image to scale with the browser window.

The designer wants to image though to be able to be swapped out by a series of thumbnails on the page, along with that image being randomized on page load from that series of images.

Initially before those two additions, I just had it setup like this:

$(document).ready(function() {$("body").ezBgResize({img : "/lib/img/bkgr/mainBG.jpg"});});

Then this is the code now (in a jQuery Tools scrollable)

I'm a little over my head though to allow these to both randomize on page load and to swap out the image via the value in the href.

I tried something like this, but it didn't work and is obviously inclomplete. Plus, it doesn't address the randomization at all.

$('#bkgrSelector .items img[href]').click(function()
{
            $("body").css("background-image", "url()");
        });

Any ideas, help, etc. would be appreciated.

Body:
Are those <img> pointing at the full-sized image file? I absolutely LOATHE sites that use full-size images and shrink them to thumbnail size. The load times are attrocious.

If they're actually thumbnail-sized images, you won't be able to use that url directly as your background url, as you'd just be stretching a small thumbnail-sized image to cover the window and get a hideous pixelized mess.

If the page is being dynamically generated, you'd want to create a JS array that contains the URLs of the full-sized image urls, so that when a thumbnail is clicked, you can get the fullsize url from that array. Or at least have a standardized naming convention so a simple string manipulation lets you turn the thumbnail url into a fullsize image url.

Once you've got that array, it's a simple matter to randomize a choice from it:

var imgs = ['/url/for/img1.jpg', '/url/for/img2.jpg', etc....];

$(document).ready(function() {
   randomUrl = imgs[Math.round(Math.random() * (imgs.length - 1)) + 1];
   $("body").css("background-image", 'url(' + randomURL + ')');
});